xref: /PHP-8.0/sapi/fuzzer/fuzzer-sapi.c (revision 2f95af99)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | http://www.php.net/license/3_01.txt                                  |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Johannes Schlüter <johanes@php.net>                         |
14    |          Stanislav Malyshev <stas@php.net>                           |
15    +----------------------------------------------------------------------+
16  */
17 
18 #include <main/php.h>
19 #include <main/php_main.h>
20 #include <main/SAPI.h>
21 #include <ext/standard/info.h>
22 #include <ext/standard/php_var.h>
23 #include <main/php_variables.h>
24 #include <zend_exceptions.h>
25 
26 #ifdef __SANITIZE_ADDRESS__
27 # include "sanitizer/lsan_interface.h"
28 #endif
29 
30 #include "fuzzer.h"
31 #include "fuzzer-sapi.h"
32 
33 const char HARDCODED_INI[] =
34 	"html_errors=0\n"
35 	"implicit_flush=1\n"
36 	"output_buffering=0\n"
37 	"error_reporting=0\n"
38 	/* Let the timeout be enforced by libfuzzer, not PHP. */
39 	"max_execution_time=0\n"
40 	/* Reduce oniguruma limits to speed up fuzzing */
41 	"mbstring.regex_stack_limit=10000\n"
42 	"mbstring.regex_retry_limit=10000\n"
43 	/* For the "execute" fuzzer disable some functions that are likely to have
44 	 * undesirable consequences (shell execution, file system writes). */
45 	"allow_url_include=0\n"
46 	"allow_url_fopen=0\n"
47 	"open_basedir=/tmp\n"
48 	"disable_functions=dl,mail,mb_send_mail"
49 	",shell_exec,exec,system,proc_open,popen,passthru,pcntl_exec"
50 	",chgrp,chmod,chown,copy,file_put_contents,lchgrp,lchown,link,mkdir"
51 	",move_uploaded_file,rename,rmdir,symlink,tempname,touch,unlink,fopen"
52 	/* Networking code likes to wait and wait. */
53 	",fsockopen,pfsockopen"
54 	",stream_socket_pair,stream_socket_client,stream_socket_server"
55 	/* crypt() can be very slow. */
56 	",crypt"
57 	/* openlog() has a known memory-management issue. */
58 	",openlog"
59 	/* Can cause long loops that bypass the executor step limit. */
60 	"\ndisable_classes=InfiniteIterator"
61 ;
62 
startup(sapi_module_struct * sapi_module)63 static int startup(sapi_module_struct *sapi_module)
64 {
65 	if (php_module_startup(sapi_module, NULL, 0)==FAILURE) {
66 		return FAILURE;
67 	}
68 	return SUCCESS;
69 }
70 
ub_write(const char * str,size_t str_length)71 static size_t ub_write(const char *str, size_t str_length)
72 {
73 	/* quiet */
74 	return str_length;
75 }
76 
fuzzer_flush(void * server_context)77 static void fuzzer_flush(void *server_context)
78 {
79 	/* quiet */
80 }
81 
send_header(sapi_header_struct * sapi_header,void * server_context)82 static void send_header(sapi_header_struct *sapi_header, void *server_context)
83 {
84 }
85 
read_cookies()86 static char* read_cookies()
87 {
88 	/* TODO: fuzz these! */
89 	return NULL;
90 }
91 
register_variables(zval * track_vars_array)92 static void register_variables(zval *track_vars_array)
93 {
94 	php_import_environment_variables(track_vars_array);
95 }
96 
log_message(const char * message,int level)97 static void log_message(const char *message, int level)
98 {
99 }
100 
101 
102 static sapi_module_struct fuzzer_module = {
103 	"fuzzer",               /* name */
104 	"clang fuzzer", /* pretty name */
105 
106 	startup,             /* startup */
107 	php_module_shutdown_wrapper,   /* shutdown */
108 
109 	NULL,                          /* activate */
110 	NULL,                          /* deactivate */
111 
112 	ub_write,            /* unbuffered write */
113 	fuzzer_flush,               /* flush */
114 	NULL,                          /* get uid */
115 	NULL,                          /* getenv */
116 
117 	php_error,                     /* error handler */
118 
119 	NULL,                          /* header handler */
120 	NULL,                          /* send headers handler */
121 	send_header,         /* send header handler */
122 
123 	NULL,                          /* read POST data */
124 	read_cookies,        /* read Cookies */
125 
126 	register_variables,  /* register server variables */
127 	log_message,         /* Log message */
128 	NULL,                          /* Get request time */
129 	NULL,                          /* Child terminate */
130 
131 	STANDARD_SAPI_MODULE_PROPERTIES
132 };
133 
fuzzer_init_php()134 int fuzzer_init_php()
135 {
136 #ifdef __SANITIZE_ADDRESS__
137 	/* We're going to leak all the memory allocated during startup,
138 	 * so disable lsan temporarily. */
139 	__lsan_disable();
140 #endif
141 
142 	sapi_startup(&fuzzer_module);
143 	fuzzer_module.phpinfo_as_text = 1;
144 
145 	fuzzer_module.ini_entries = malloc(sizeof(HARDCODED_INI));
146 	memcpy(fuzzer_module.ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI));
147 
148 	/*
149 	 * TODO: we might want to test both Zend and malloc MM, but testing with malloc
150 	 * is more likely to find bugs, so use that for now.
151 	 */
152 	putenv("USE_ZEND_ALLOC=0");
153 
154 	if (fuzzer_module.startup(&fuzzer_module)==FAILURE) {
155 		return FAILURE;
156 	}
157 
158 #ifdef __SANITIZE_ADDRESS__
159 	__lsan_enable();
160 #endif
161 
162 	return SUCCESS;
163 }
164 
fuzzer_request_startup()165 int fuzzer_request_startup()
166 {
167 	if (php_request_startup() == FAILURE) {
168 		php_module_shutdown();
169 		return FAILURE;
170 	}
171 
172 #ifdef ZEND_SIGNALS
173 	/* Some signal handlers will be overridden,
174 	 * don't complain about them during shutdown. */
175 	SIGG(check) = 0;
176 #endif
177 
178 	return SUCCESS;
179 }
180 
fuzzer_request_shutdown()181 void fuzzer_request_shutdown()
182 {
183 	zend_try {
184 		/* Destroy thrown exceptions. This does not happen as part of request shutdown. */
185 		if (EG(exception)) {
186 			zend_object_release(EG(exception));
187 			EG(exception) = NULL;
188 		}
189 
190 		/* Some fuzzers (like unserialize) may create circular structures. Make sure we free them.
191 		 * Two calls are performed to handle objects with destructors. */
192 		zend_gc_collect_cycles();
193 		zend_gc_collect_cycles();
194 	} zend_end_try();
195 
196 	php_request_shutdown(NULL);
197 }
198 
199 /* Set up a dummy stack frame so that exceptions may be thrown. */
fuzzer_setup_dummy_frame()200 void fuzzer_setup_dummy_frame()
201 {
202 	static zend_execute_data execute_data;
203 	static zend_function func;
204 
205 	memset(&execute_data, 0, sizeof(zend_execute_data));
206 	memset(&func, 0, sizeof(zend_function));
207 
208 	func.type = ZEND_INTERNAL_FUNCTION;
209 	func.common.function_name = ZSTR_EMPTY_ALLOC();
210 	execute_data.func = &func;
211 	EG(current_execute_data) = &execute_data;
212 }
213 
fuzzer_set_ini_file(const char * file)214 void fuzzer_set_ini_file(const char *file)
215 {
216 	if (fuzzer_module.php_ini_path_override) {
217 		free(fuzzer_module.php_ini_path_override);
218 	}
219 	fuzzer_module.php_ini_path_override = strdup(file);
220 }
221 
222 
fuzzer_shutdown_php()223 int fuzzer_shutdown_php()
224 {
225 	php_module_shutdown();
226 	sapi_shutdown();
227 
228 	free(fuzzer_module.ini_entries);
229 	return SUCCESS;
230 }
231 
fuzzer_do_request_from_buffer(char * filename,const char * data,size_t data_len,zend_bool execute)232 int fuzzer_do_request_from_buffer(
233 		char *filename, const char *data, size_t data_len, zend_bool execute)
234 {
235 	int retval = FAILURE; /* failure by default */
236 
237 	SG(options) |= SAPI_OPTION_NO_CHDIR;
238 	SG(request_info).argc=0;
239 	SG(request_info).argv=NULL;
240 
241 	if (fuzzer_request_startup() == FAILURE) {
242 		return FAILURE;
243 	}
244 
245 	// Commented out to avoid leaking the header callback.
246 	//SG(headers_sent) = 1;
247 	//SG(request_info).no_headers = 1;
248 	php_register_variable("PHP_SELF", filename, NULL);
249 
250 	zend_first_try {
251 		zend_file_handle file_handle;
252 		zend_stream_init_filename(&file_handle, filename);
253 		file_handle.buf = estrndup(data, data_len);
254 		file_handle.len = data_len;
255 
256 		zend_op_array *op_array = zend_compile_file(&file_handle, ZEND_REQUIRE);
257 		if (op_array) {
258 			if (execute) {
259 				zend_execute(op_array, NULL);
260 			}
261 			destroy_op_array(op_array);
262 			efree(op_array);
263 		}
264 	} zend_end_try();
265 
266 	CG(compiled_filename) = NULL; /* ??? */
267 	fuzzer_request_shutdown();
268 
269 	return (retval == SUCCESS) ? SUCCESS : FAILURE;
270 }
271 
272 // Call named PHP function with N zval arguments
fuzzer_call_php_func_zval(const char * func_name,int nargs,zval * args)273 void fuzzer_call_php_func_zval(const char *func_name, int nargs, zval *args) {
274 	zval retval, func;
275 
276 	ZVAL_STRING(&func, func_name);
277 	ZVAL_UNDEF(&retval);
278 	call_user_function(CG(function_table), NULL, &func, &retval, nargs, args);
279 
280 	// TODO: check result?
281 	/* to ensure retval is not broken */
282 	php_var_dump(&retval, 0);
283 
284 	/* cleanup */
285 	zval_ptr_dtor(&retval);
286 	zval_ptr_dtor(&func);
287 }
288 
289 // Call named PHP function with N string arguments
fuzzer_call_php_func(const char * func_name,int nargs,char ** params)290 void fuzzer_call_php_func(const char *func_name, int nargs, char **params) {
291 	zval args[nargs];
292 	int i;
293 
294 	for(i=0;i<nargs;i++) {
295 		ZVAL_STRING(&args[i], params[i]);
296 	}
297 
298 	fuzzer_call_php_func_zval(func_name, nargs, args);
299 
300 	for(i=0;i<nargs;i++) {
301 		zval_ptr_dtor(&args[i]);
302 		ZVAL_UNDEF(&args[i]);
303 	}
304 }
305