summaryrefslogtreecommitdiff
path: root/src/sp_execute.c
blob: 3a474a37593beaeaa9dfc7361f8c1adea72aefd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#include "php_snuffleupagus.h"
#include "ext/standard/php_string.h"

static void (*orig_execute_ex)(zend_execute_data *execute_data) = NULL;
static void (*orig_zend_execute_internal)(zend_execute_data *execute_data,
                                          zval *return_value) = NULL;
#if PHP_VERSION_ID < 80100
static int (*orig_zend_stream_open)(const char *filename, zend_file_handle *handle) = NULL;
#else
static zend_result (*orig_zend_stream_open)(zend_file_handle *handle) = NULL;
#endif

// FIXME handle symlink
ZEND_COLD static inline void terminate_if_writable(const char *filename) {
  const sp_config_readonly_exec *config_ro_exec = &(SPCFG(readonly_exec));
  char *errmsg = "unknown access problem";

  // check write access
  if (0 == access(filename, W_OK)) {
    errmsg = "Attempted execution of a writable file";
    goto violation;
  }
  if (errno != EACCES) {
    goto err;
  }

  // other checks are 'extended checks' that can be enabled/disabled via config
  if (!config_ro_exec->extended_checks) {
    return;
  }

  // check effective uid
  struct stat buf;
  if (0 != stat(filename, &buf)) {
    goto err;
  }
  if (buf.st_uid == geteuid()) {
    errmsg = "Attempted execution of file owned by process";
    goto violation;
  }

  // check write access on directory
  char *dirname = estrndup(filename, strlen(filename));
  php_dirname(dirname, strlen(dirname));
  if (0 == access(dirname, W_OK)) {
    errmsg = "Attempted execution of file in writable directory";
    efree(dirname);
    goto violation;
  }
  if (errno != EACCES) {
    efree(dirname);
    goto err;
  }

  // check effecite uid of directory
  if (0 != stat(dirname, &buf)) {
    efree(dirname);
    goto err;
  }
  efree(dirname);
  if (buf.st_uid == geteuid()) {
    errmsg = "Attempted execution of file in directory owned by process";
    goto violation;
  }

  // we would actually need to check all parent directories as well, but that task is left for other tools
  return;

violation:
  if (config_ro_exec->dump) {
    sp_log_request(config_ro_exec->dump, config_ro_exec->textual_representation);
  }
  if (config_ro_exec->simulation) {
    sp_log_simulation("readonly_exec", "%s (%s)", errmsg, filename);
  } else {
    sp_log_drop("readonly_exec", "%s (%s)", errmsg, filename);
  }
  return;

err:
  sp_log_err("readonly_exec", "Error while accessing %s: %s", filename, strerror(errno));
}

inline static void is_builtin_matching(
    const zend_string *restrict const param_value,
    const char *restrict const function_name,
    const char *restrict const param_name, const sp_list_node *config,
    const HashTable *ht) {
  if (!config || !config->data) {
    return;
  }

  should_disable_ht(EG(current_execute_data), function_name, param_value, param_name, SPCFG(disabled_functions_reg).disabled_functions, ht);
}

static void ZEND_HOT is_in_eval_and_whitelisted(const zend_execute_data *execute_data) {
  const sp_config_eval *config_eval = &(SPCFG(eval));

  if (EXPECTED(0 == SPG(in_eval))) {
    return;
  }

  if (EXPECTED(NULL == config_eval->whitelist)) {
    return;
  }

  if (zend_is_executing() && !EX(func)) {
    return;  // LCOV_EXCL_LINE
  }

  char *function_name = get_complete_function_path(execute_data);
  if (!function_name) {
    return;
  }

    if (UNEXPECTED(false == check_is_in_eval_whitelist(function_name))) {
      if (config_eval->dump) {
        sp_log_request(config_eval->dump, config_eval->textual_representation);
      }
      if (config_eval->simulation) {
        sp_log_simulation("Eval_whitelist", "The function '%s' isn't in the eval whitelist, logging its call.", function_name);
        goto out;
      } else {
        sp_log_drop("Eval_whitelist", "The function '%s' isn't in the eval whitelist, dropping its call.", function_name);
      }
    }
  // }
out:
  efree(function_name);
}

/* This function gets the filename in which `eval()` is called from,
 * since it looks like "foo.php(1) : eval()'d code", so we're starting
 * from the end of the string until the second closing parenthesis. */
zend_string *get_eval_filename(const char *const filename) {
  int count = 0;
  zend_string *clean_filename = zend_string_init(filename, strlen(filename), 0);

  for (int i = ZSTR_LEN(clean_filename); i >= 0; i--) {
    if (ZSTR_VAL(clean_filename)[i] == '(') {
      if (count == 1) {
        ZSTR_VAL(clean_filename)[i] = '\0';
        clean_filename = zend_string_truncate(clean_filename, i, 0);
        break;
      }
      count++;
    }
  }
  return clean_filename;
}

static inline void sp_orig_execute(zend_execute_data *execute_data) {
  SPG(execution_depth)++;
  if (SPCFG(max_execution_depth) > 0 && SPG(execution_depth) > SPCFG(max_execution_depth)) {
    sp_log_drop("execute", "Maximum recursion limit reached. Script terminated.");
  }
  orig_execute_ex(execute_data);
  SPG(execution_depth)--;
}

static inline void sp_check_writable(zend_execute_data *execute_data) {
  if (execute_data && EX(func) && EX(func)->op_array.filename && SPCFG(readonly_exec).enable) {
    terminate_if_writable(ZSTR_VAL(EX(func)->op_array.filename));
  }
}

static inline void sp_call_orig_execute(INTERNAL_FUNCTION_PARAMETERS, bool internal) {
  if (internal) {
    if (UNEXPECTED(NULL != orig_zend_execute_internal)) {
      orig_zend_execute_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
    } else {
      EX(func)->internal_function.handler(INTERNAL_FUNCTION_PARAM_PASSTHRU);
    }
  } else {
    sp_orig_execute(execute_data);
  }
}

static inline void sp_execute_handler(INTERNAL_FUNCTION_PARAMETERS, bool internal) {
  if (!execute_data) {
    return;  // LCOV_EXCL_LINE
  }

  is_in_eval_and_whitelisted(execute_data);

  if (!internal) {
    if (UNEXPECTED(EX(func)->op_array.type == ZEND_EVAL_CODE)) {
      const sp_list_node *config = zend_hash_str_find_ptr(SPCFG(disabled_functions), ZEND_STRL("eval"));

      zend_string *filename = get_eval_filename(zend_get_executed_filename());
      is_builtin_matching(filename, "eval", NULL, config, SPCFG(disabled_functions));
      zend_string_release(filename);

      SPG(in_eval)++;
      sp_orig_execute(execute_data);
      SPG(in_eval)--;
      return;
    }

    sp_check_writable(execute_data);
  }

  if (!SPG(hook_execute)) {
    sp_call_orig_execute(INTERNAL_FUNCTION_PARAM_PASSTHRU, internal);
    return;
  }

  char *function_name = get_complete_function_path(execute_data);

  if (!function_name) {
    sp_call_orig_execute(INTERNAL_FUNCTION_PARAM_PASSTHRU, internal);
    return;
  }

  bool is_hooked = (zend_hash_str_find(SPG(disabled_functions_hook), VAR_AND_LEN(function_name)) || zend_hash_str_find(SPG(disabled_functions_hook), VAR_AND_LEN(function_name)));
  if (is_hooked) {
    sp_call_orig_execute(INTERNAL_FUNCTION_PARAM_PASSTHRU, internal);
    return;
  }

  // If we're at an internal function
  if (!execute_data->prev_execute_data ||
      !execute_data->prev_execute_data->func ||
      !ZEND_USER_CODE(execute_data->prev_execute_data->func->type) ||
      !execute_data->prev_execute_data->opline) {
    should_disable_ht(execute_data, function_name, NULL, NULL, SPCFG(disabled_functions_reg).disabled_functions, SPCFG(disabled_functions));
  } else {  // If we're at a userland function call
    switch (execute_data->prev_execute_data->opline->opcode) {
      case ZEND_DO_FCALL:
      case ZEND_DO_FCALL_BY_NAME:
      case ZEND_DO_ICALL:
      case ZEND_DO_UCALL:
      case ZEND_TICKS:
        should_disable_ht(execute_data, function_name, NULL, NULL, SPCFG(disabled_functions_reg).disabled_functions, SPCFG(disabled_functions));
      default:
        break;
    }
  }

  // When a function's return value isn't used, php doesn't store it in the
  // execute_data, so we need to use a local variable to be able to match on
  // it later.
  zval ret_val;
  if (EX(return_value) == NULL && return_value == NULL) {
    memset(&ret_val, 0, sizeof(ret_val));
    return_value = EX(return_value) = &ret_val;
  }

  sp_call_orig_execute(INTERNAL_FUNCTION_PARAM_PASSTHRU, internal);

  should_drop_on_ret_ht(return_value, function_name, SPCFG(disabled_functions_reg_ret).disabled_functions, SPCFG(disabled_functions_ret), execute_data);

  efree(function_name);

  if (EX(return_value) == &ret_val) {
    return_value = EX(return_value) = NULL;
  }

}


static void sp_execute_ex(zend_execute_data *execute_data) {
  sp_execute_handler(execute_data, execute_data ? EX(return_value) : NULL, false);
}

static void sp_zend_execute_internal(INTERNAL_FUNCTION_PARAMETERS) {
  sp_execute_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU, true);
}

static inline void sp_stream_open_checks(zend_string *zend_filename, zend_file_handle *handle) {
  zend_execute_data const *const data = EG(current_execute_data);

  if ((NULL == data) || (NULL == data->opline) ||
      (data->func->type != ZEND_USER_FUNCTION)) {
    return;
  }

  const HashTable *disabled_functions_hooked = SPCFG(disabled_functions_hooked);

  switch (data->opline->opcode) {
    case ZEND_INCLUDE_OR_EVAL:
      if (SPCFG(readonly_exec).enable) {
        char *fn = ZSTR_VAL(zend_filename);
        if (ZSTR_LEN(zend_filename) >= strlen("file://") && memcmp(fn, "file://", strlen("file://")) == 0) {
          fn += strlen("file://");
        } else if (!php_memnstr(ZSTR_VAL(zend_filename), "://", strlen("://"), ZSTR_VAL(zend_filename) + ZSTR_LEN(zend_filename))) {
          // ignore stream wrappers other than file:// for now
          terminate_if_writable(fn);
        }
      }
      switch (data->opline->extended_value) {
        case ZEND_INCLUDE:
          is_builtin_matching(
              zend_filename, "include", "inclusion path",
              zend_hash_str_find_ptr(disabled_functions_hooked, ZEND_STRL("include")),
              disabled_functions_hooked);
          break;
        case ZEND_REQUIRE:
          is_builtin_matching(
              zend_filename, "require", "inclusion path",
              zend_hash_str_find_ptr(disabled_functions_hooked, ZEND_STRL("require")),
              disabled_functions_hooked);
          break;
        case ZEND_REQUIRE_ONCE:
          is_builtin_matching(
              zend_filename, "require_once", "inclusion path",
              zend_hash_str_find_ptr(disabled_functions_hooked, ZEND_STRL("require_once")),
              disabled_functions_hooked);
          break;
        case ZEND_INCLUDE_ONCE:
          is_builtin_matching(
              zend_filename, "include_once", "inclusion path",
              zend_hash_str_find_ptr(disabled_functions_hooked, ZEND_STRL("include_once")),
              disabled_functions_hooked);
          break;
          EMPTY_SWITCH_DEFAULT_CASE();  // LCOV_EXCL_LINE
      }
  }
  // efree(zend_filename);

// end:
  // return orig_zend_stream_open(filename, handle);
}

#if PHP_VERSION_ID < 80100

static int sp_stream_open(const char *filename, zend_file_handle *handle) {
  zend_string *zend_filename = zend_string_init(filename, strlen(filename), 0);

  sp_stream_open_checks(zend_filename, handle);

  zend_string_release_ex(zend_filename, 0);
  return orig_zend_stream_open(filename, handle);
}

#else // PHP >= 8.1

static zend_result sp_stream_open(zend_file_handle *handle) {
  sp_stream_open_checks(handle->filename, handle);
  return orig_zend_stream_open(handle);
}

#endif

int hook_execute(void) {
  TSRMLS_FETCH();

  if (NULL == orig_execute_ex && NULL == orig_zend_stream_open) {
    if (zend_execute_ex != sp_execute_ex) {
      /* zend_execute_ex is used for "user" function calls */
      orig_execute_ex = zend_execute_ex;
      zend_execute_ex = sp_execute_ex;
    }

    if (zend_execute_internal != sp_zend_execute_internal) {
      /* zend_execute_internal is used for "builtin" functions calls */
      orig_zend_execute_internal = zend_execute_internal;
      zend_execute_internal = sp_zend_execute_internal;
    }

    if (zend_stream_open_function != sp_stream_open) {
      /* zend_stream_open_function is used for include-related stuff */
      orig_zend_stream_open = zend_stream_open_function;
      zend_stream_open_function = sp_stream_open;
    }
  }

  return SUCCESS;
}