xref: /PHP-7.4/ext/standard/exec.c (revision 14fcc813)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) The PHP Group                                          |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Author: Rasmus Lerdorf <rasmus@php.net>                              |
16    |         Ilia Alshanetsky <iliaa@php.net>                             |
17    +----------------------------------------------------------------------+
18  */
19 
20 #include <stdio.h>
21 #include "php.h"
22 #include <ctype.h>
23 #include "php_string.h"
24 #include "ext/standard/head.h"
25 #include "ext/standard/file.h"
26 #include "basic_functions.h"
27 #include "exec.h"
28 #include "php_globals.h"
29 #include "SAPI.h"
30 
31 #if HAVE_SYS_WAIT_H
32 #include <sys/wait.h>
33 #endif
34 
35 #include <signal.h>
36 
37 #if HAVE_SYS_TYPES_H
38 #include <sys/types.h>
39 #endif
40 #if HAVE_SYS_STAT_H
41 #include <sys/stat.h>
42 #endif
43 #if HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46 
47 #if HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50 
51 #include <limits.h>
52 
53 #ifdef PHP_WIN32
54 # include "win32/nice.h"
55 #endif
56 
57 static size_t cmd_max_len;
58 
59 /* {{{ PHP_MINIT_FUNCTION(exec) */
PHP_MINIT_FUNCTION(exec)60 PHP_MINIT_FUNCTION(exec)
61 {
62 #ifdef _SC_ARG_MAX
63 	cmd_max_len = sysconf(_SC_ARG_MAX);
64 	if ((size_t)-1 == cmd_max_len) {
65 #ifdef _POSIX_ARG_MAX
66 		cmd_max_len = _POSIX_ARG_MAX;
67 #else
68 		cmd_max_len = 4096;
69 #endif
70 	}
71 #elif defined(ARG_MAX)
72 	cmd_max_len = ARG_MAX;
73 #elif defined(PHP_WIN32)
74 	/* Executed commands will run through cmd.exe. As long as it's the case,
75 		it's just the constant limit.*/
76 	cmd_max_len = 8192;
77 #else
78 	/* This is just an arbitrary value for the fallback case. */
79 	cmd_max_len = 4096;
80 #endif
81 
82 	return SUCCESS;
83 }
84 /* }}} */
85 
86 /* {{{ php_exec
87  * If type==0, only last line of output is returned (exec)
88  * If type==1, all lines will be printed and last lined returned (system)
89  * If type==2, all lines will be saved to given array (exec with &$array)
90  * If type==3, output will be printed binary, no lines will be saved or returned (passthru)
91  *
92  */
php_exec(int type,char * cmd,zval * array,zval * return_value)93 PHPAPI int php_exec(int type, char *cmd, zval *array, zval *return_value)
94 {
95 	FILE *fp;
96 	char *buf;
97 	size_t l = 0;
98 	int pclose_return;
99 	char *b, *d=NULL;
100 	php_stream *stream;
101 	size_t buflen, bufl = 0;
102 #if PHP_SIGCHILD
103 	void (*sig_handler)() = NULL;
104 #endif
105 
106 #if PHP_SIGCHILD
107 	sig_handler = signal (SIGCHLD, SIG_DFL);
108 #endif
109 
110 #ifdef PHP_WIN32
111 	fp = VCWD_POPEN(cmd, "rb");
112 #else
113 	fp = VCWD_POPEN(cmd, "r");
114 #endif
115 	if (!fp) {
116 		php_error_docref(NULL, E_WARNING, "Unable to fork [%s]", cmd);
117 		goto err;
118 	}
119 
120 	stream = php_stream_fopen_from_pipe(fp, "rb");
121 
122 	buf = (char *) emalloc(EXEC_INPUT_BUF);
123 	buflen = EXEC_INPUT_BUF;
124 
125 	if (type != 3) {
126 		b = buf;
127 
128 		while (php_stream_get_line(stream, b, EXEC_INPUT_BUF, &bufl)) {
129 			/* no new line found, let's read some more */
130 			if (b[bufl - 1] != '\n' && !php_stream_eof(stream)) {
131 				if (buflen < (bufl + (b - buf) + EXEC_INPUT_BUF)) {
132 					bufl += b - buf;
133 					buflen = bufl + EXEC_INPUT_BUF;
134 					buf = erealloc(buf, buflen);
135 					b = buf + bufl;
136 				} else {
137 					b += bufl;
138 				}
139 				continue;
140 			} else if (b != buf) {
141 				bufl += b - buf;
142 			}
143 
144 			if (type == 1) {
145 				PHPWRITE(buf, bufl);
146 				if (php_output_get_level() < 1) {
147 					sapi_flush();
148 				}
149 			} else if (type == 2) {
150 				/* strip trailing whitespaces */
151 				l = bufl;
152 				while (l-- > 0 && isspace(((unsigned char *)buf)[l]));
153 				if (l != (bufl - 1)) {
154 					bufl = l + 1;
155 					buf[bufl] = '\0';
156 				}
157 				add_next_index_stringl(array, buf, bufl);
158 			}
159 			b = buf;
160 		}
161 		if (bufl) {
162 			/* output remaining data in buffer */
163 			if (type == 1 && buf != b) {
164 				PHPWRITE(buf, bufl);
165 				if (php_output_get_level() < 1) {
166 					sapi_flush();
167 				}
168 			}
169 			/* strip trailing whitespaces if we have not done so already */
170 			if ((type == 2 && buf != b) || type != 2) {
171 				l = bufl;
172 				while (l-- > 0 && isspace(((unsigned char *)buf)[l]));
173 				if (l != (bufl - 1)) {
174 					bufl = l + 1;
175 					buf[bufl] = '\0';
176 				}
177 				if (type == 2) {
178 					add_next_index_stringl(array, buf, bufl);
179 				}
180 			}
181 
182 			/* Return last line from the shell command */
183 			RETVAL_STRINGL(buf, bufl);
184 		} else { /* should return NULL, but for BC we return "" */
185 			RETVAL_EMPTY_STRING();
186 		}
187 	} else {
188 		ssize_t read;
189 		while ((read = php_stream_read(stream, buf, EXEC_INPUT_BUF)) > 0) {
190 			PHPWRITE(buf, read);
191 		}
192 	}
193 
194 	pclose_return = php_stream_close(stream);
195 	efree(buf);
196 
197 done:
198 #if PHP_SIGCHILD
199 	if (sig_handler) {
200 		signal(SIGCHLD, sig_handler);
201 	}
202 #endif
203 	if (d) {
204 		efree(d);
205 	}
206 	return pclose_return;
207 err:
208 	pclose_return = -1;
209 	goto done;
210 }
211 /* }}} */
212 
php_exec_ex(INTERNAL_FUNCTION_PARAMETERS,int mode)213 static void php_exec_ex(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */
214 {
215 	char *cmd;
216 	size_t cmd_len;
217 	zval *ret_code=NULL, *ret_array=NULL;
218 	int ret;
219 
220 	ZEND_PARSE_PARAMETERS_START(1, (mode ? 2 : 3))
221 		Z_PARAM_STRING(cmd, cmd_len)
222 		Z_PARAM_OPTIONAL
223 		if (!mode) {
224 			Z_PARAM_ZVAL(ret_array)
225 		}
226 		Z_PARAM_ZVAL(ret_code)
227 	ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
228 
229 	if (!cmd_len) {
230 		php_error_docref(NULL, E_WARNING, "Cannot execute a blank command");
231 		RETURN_FALSE;
232 	}
233 	if (strlen(cmd) != cmd_len) {
234 		php_error_docref(NULL, E_WARNING, "NULL byte detected. Possible attack");
235 		RETURN_FALSE;
236 	}
237 
238 	if (!ret_array) {
239 		ret = php_exec(mode, cmd, NULL, return_value);
240 	} else {
241 		if (Z_TYPE_P(Z_REFVAL_P(ret_array)) == IS_ARRAY) {
242 			ZVAL_DEREF(ret_array);
243 			SEPARATE_ARRAY(ret_array);
244 		} else {
245 			ret_array = zend_try_array_init(ret_array);
246 			if (!ret_array) {
247 				return;
248 			}
249 		}
250 
251 		ret = php_exec(2, cmd, ret_array, return_value);
252 	}
253 	if (ret_code) {
254 		ZEND_TRY_ASSIGN_REF_LONG(ret_code, ret);
255 	}
256 }
257 /* }}} */
258 
259 /* {{{ proto string exec(string command [, array &output [, int &return_value]])
260    Execute an external program */
PHP_FUNCTION(exec)261 PHP_FUNCTION(exec)
262 {
263 	php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
264 }
265 /* }}} */
266 
267 /* {{{ proto int system(string command [, int &return_value])
268    Execute an external program and display output */
PHP_FUNCTION(system)269 PHP_FUNCTION(system)
270 {
271 	php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
272 }
273 /* }}} */
274 
275 /* {{{ proto void passthru(string command [, int &return_value])
276    Execute an external program and display raw output */
PHP_FUNCTION(passthru)277 PHP_FUNCTION(passthru)
278 {
279 	php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 3);
280 }
281 /* }}} */
282 
283 /* {{{ php_escape_shell_cmd
284    Escape all chars that could possibly be used to
285    break out of a shell command
286 
287    This function emalloc's a string and returns the pointer.
288    Remember to efree it when done with it.
289 
290    *NOT* safe for binary strings
291 */
php_escape_shell_cmd(char * str)292 PHPAPI zend_string *php_escape_shell_cmd(char *str)
293 {
294 	register size_t x, y;
295 	size_t l = strlen(str);
296 	uint64_t estimate = (2 * (uint64_t)l) + 1;
297 	zend_string *cmd;
298 #ifndef PHP_WIN32
299 	char *p = NULL;
300 #endif
301 
302 	/* max command line length - two single quotes - \0 byte length */
303 	if (l > cmd_max_len - 2 - 1) {
304 		php_error_docref(NULL, E_ERROR, "Command exceeds the allowed length of %zu bytes", cmd_max_len);
305 		return ZSTR_EMPTY_ALLOC();
306 	}
307 
308 	cmd = zend_string_safe_alloc(2, l, 0, 0);
309 
310 	for (x = 0, y = 0; x < l; x++) {
311 		int mb_len = php_mblen(str + x, (l - x));
312 
313 		/* skip non-valid multibyte characters */
314 		if (mb_len < 0) {
315 			continue;
316 		} else if (mb_len > 1) {
317 			memcpy(ZSTR_VAL(cmd) + y, str + x, mb_len);
318 			y += mb_len;
319 			x += mb_len - 1;
320 			continue;
321 		}
322 
323 		switch (str[x]) {
324 #ifndef PHP_WIN32
325 			case '"':
326 			case '\'':
327 				if (!p && (p = memchr(str + x + 1, str[x], l - x - 1))) {
328 					/* noop */
329 				} else if (p && *p == str[x]) {
330 					p = NULL;
331 				} else {
332 					ZSTR_VAL(cmd)[y++] = '\\';
333 				}
334 				ZSTR_VAL(cmd)[y++] = str[x];
335 				break;
336 #else
337 			/* % is Windows specific for environmental variables, ^%PATH% will
338 				output PATH while ^%PATH^% will not. escapeshellcmd->val will escape all % and !.
339 			*/
340 			case '%':
341 			case '!':
342 			case '"':
343 			case '\'':
344 #endif
345 			case '#': /* This is character-set independent */
346 			case '&':
347 			case ';':
348 			case '`':
349 			case '|':
350 			case '*':
351 			case '?':
352 			case '~':
353 			case '<':
354 			case '>':
355 			case '^':
356 			case '(':
357 			case ')':
358 			case '[':
359 			case ']':
360 			case '{':
361 			case '}':
362 			case '$':
363 			case '\\':
364 			case '\x0A': /* excluding these two */
365 			case '\xFF':
366 #ifdef PHP_WIN32
367 				ZSTR_VAL(cmd)[y++] = '^';
368 #else
369 				ZSTR_VAL(cmd)[y++] = '\\';
370 #endif
371 				/* fall-through */
372 			default:
373 				ZSTR_VAL(cmd)[y++] = str[x];
374 
375 		}
376 	}
377 	ZSTR_VAL(cmd)[y] = '\0';
378 
379 	if (y > cmd_max_len + 1) {
380 		php_error_docref(NULL, E_ERROR, "Escaped command exceeds the allowed length of %zu bytes", cmd_max_len);
381 		zend_string_release_ex(cmd, 0);
382 		return ZSTR_EMPTY_ALLOC();
383 	}
384 
385 	if ((estimate - y) > 4096) {
386 		/* realloc if the estimate was way overill
387 		 * Arbitrary cutoff point of 4096 */
388 		cmd = zend_string_truncate(cmd, y, 0);
389 	}
390 
391 	ZSTR_LEN(cmd) = y;
392 
393 	return cmd;
394 }
395 /* }}} */
396 
397 /* {{{ php_escape_shell_arg
398  */
php_escape_shell_arg(char * str)399 PHPAPI zend_string *php_escape_shell_arg(char *str)
400 {
401 	size_t x, y = 0;
402 	size_t l = strlen(str);
403 	zend_string *cmd;
404 	uint64_t estimate = (4 * (uint64_t)l) + 3;
405 
406 	/* max command line length - two single quotes - \0 byte length */
407 	if (l > cmd_max_len - 2 - 1) {
408 		php_error_docref(NULL, E_ERROR, "Argument exceeds the allowed length of %zu bytes", cmd_max_len);
409 		return ZSTR_EMPTY_ALLOC();
410 	}
411 
412 	cmd = zend_string_safe_alloc(4, l, 2, 0); /* worst case */
413 
414 #ifdef PHP_WIN32
415 	ZSTR_VAL(cmd)[y++] = '"';
416 #else
417 	ZSTR_VAL(cmd)[y++] = '\'';
418 #endif
419 
420 	for (x = 0; x < l; x++) {
421 		int mb_len = php_mblen(str + x, (l - x));
422 
423 		/* skip non-valid multibyte characters */
424 		if (mb_len < 0) {
425 			continue;
426 		} else if (mb_len > 1) {
427 			memcpy(ZSTR_VAL(cmd) + y, str + x, mb_len);
428 			y += mb_len;
429 			x += mb_len - 1;
430 			continue;
431 		}
432 
433 		switch (str[x]) {
434 #ifdef PHP_WIN32
435 		case '"':
436 		case '%':
437 		case '!':
438 			ZSTR_VAL(cmd)[y++] = ' ';
439 			break;
440 #else
441 		case '\'':
442 			ZSTR_VAL(cmd)[y++] = '\'';
443 			ZSTR_VAL(cmd)[y++] = '\\';
444 			ZSTR_VAL(cmd)[y++] = '\'';
445 #endif
446 			/* fall-through */
447 		default:
448 			ZSTR_VAL(cmd)[y++] = str[x];
449 		}
450 	}
451 #ifdef PHP_WIN32
452 	if (y > 0 && '\\' == ZSTR_VAL(cmd)[y - 1]) {
453 		int k = 0, n = y - 1;
454 		for (; n >= 0 && '\\' == ZSTR_VAL(cmd)[n]; n--, k++);
455 		if (k % 2) {
456 			ZSTR_VAL(cmd)[y++] = '\\';
457 		}
458 	}
459 
460 	ZSTR_VAL(cmd)[y++] = '"';
461 #else
462 	ZSTR_VAL(cmd)[y++] = '\'';
463 #endif
464 	ZSTR_VAL(cmd)[y] = '\0';
465 
466 	if (y > cmd_max_len + 1) {
467 		php_error_docref(NULL, E_ERROR, "Escaped argument exceeds the allowed length of %zu bytes", cmd_max_len);
468 		zend_string_release_ex(cmd, 0);
469 		return ZSTR_EMPTY_ALLOC();
470 	}
471 
472 	if ((estimate - y) > 4096) {
473 		/* realloc if the estimate was way overill
474 		 * Arbitrary cutoff point of 4096 */
475 		cmd = zend_string_truncate(cmd, y, 0);
476 	}
477 	ZSTR_LEN(cmd) = y;
478 	return cmd;
479 }
480 /* }}} */
481 
482 /* {{{ proto string escapeshellcmd(string command)
483    Escape shell metacharacters */
PHP_FUNCTION(escapeshellcmd)484 PHP_FUNCTION(escapeshellcmd)
485 {
486 	char *command;
487 	size_t command_len;
488 
489 	ZEND_PARSE_PARAMETERS_START(1, 1)
490 		Z_PARAM_STRING(command, command_len)
491 	ZEND_PARSE_PARAMETERS_END();
492 
493 	if (command_len) {
494 		if (command_len != strlen(command)) {
495 			php_error_docref(NULL, E_ERROR, "Input string contains NULL bytes");
496 			return;
497 		}
498 		RETVAL_STR(php_escape_shell_cmd(command));
499 	} else {
500 		RETVAL_EMPTY_STRING();
501 	}
502 }
503 /* }}} */
504 
505 /* {{{ proto string escapeshellarg(string arg)
506    Quote and escape an argument for use in a shell command */
PHP_FUNCTION(escapeshellarg)507 PHP_FUNCTION(escapeshellarg)
508 {
509 	char *argument;
510 	size_t argument_len;
511 
512 	ZEND_PARSE_PARAMETERS_START(1, 1)
513 		Z_PARAM_STRING(argument, argument_len)
514 	ZEND_PARSE_PARAMETERS_END();
515 
516 	if (argument) {
517 		if (argument_len != strlen(argument)) {
518 			php_error_docref(NULL, E_ERROR, "Input string contains NULL bytes");
519 			return;
520 		}
521 		RETVAL_STR(php_escape_shell_arg(argument));
522 	}
523 }
524 /* }}} */
525 
526 /* {{{ proto string shell_exec(string cmd)
527    Execute command via shell and return complete output as string */
PHP_FUNCTION(shell_exec)528 PHP_FUNCTION(shell_exec)
529 {
530 	FILE *in;
531 	char *command;
532 	size_t command_len;
533 	zend_string *ret;
534 	php_stream *stream;
535 
536 	ZEND_PARSE_PARAMETERS_START(1, 1)
537 		Z_PARAM_STRING(command, command_len)
538 	ZEND_PARSE_PARAMETERS_END();
539 
540 	if (!command_len) {
541 		php_error_docref(NULL, E_WARNING, "Cannot execute a blank command");
542 		RETURN_FALSE;
543 	}
544 	if (strlen(command) != command_len) {
545 		php_error_docref(NULL, E_WARNING, "NULL byte detected. Possible attack");
546 		RETURN_FALSE;
547 	}
548 
549 #ifdef PHP_WIN32
550 	if ((in=VCWD_POPEN(command, "rt"))==NULL) {
551 #else
552 	if ((in=VCWD_POPEN(command, "r"))==NULL) {
553 #endif
554 		php_error_docref(NULL, E_WARNING, "Unable to execute '%s'", command);
555 		RETURN_FALSE;
556 	}
557 
558 	stream = php_stream_fopen_from_pipe(in, "rb");
559 	ret = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0);
560 	php_stream_close(stream);
561 
562 	if (ret && ZSTR_LEN(ret) > 0) {
563 		RETVAL_STR(ret);
564 	}
565 }
566 /* }}} */
567 
568 #ifdef HAVE_NICE
569 /* {{{ proto bool proc_nice(int priority)
570    Change the priority of the current process */
571 PHP_FUNCTION(proc_nice)
572 {
573 	zend_long pri;
574 
575 	ZEND_PARSE_PARAMETERS_START(1, 1)
576 		Z_PARAM_LONG(pri)
577 	ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
578 
579 	errno = 0;
580 	php_ignore_value(nice(pri));
581 	if (errno) {
582 #ifdef PHP_WIN32
583 		char *err = php_win_err();
584 		php_error_docref(NULL, E_WARNING, "%s", err);
585 		php_win_err_free(err);
586 #else
587 		php_error_docref(NULL, E_WARNING, "Only a super user may attempt to increase the priority of a process");
588 #endif
589 		RETURN_FALSE;
590 	}
591 
592 	RETURN_TRUE;
593 }
594 /* }}} */
595 #endif
596