xref: /PHP-7.3/ext/standard/exec.c (revision 14fcc813)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2018 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 #if HAVE_SIGNAL_H
35 #include <signal.h>
36 #endif
37 
38 #if HAVE_SYS_TYPES_H
39 #include <sys/types.h>
40 #endif
41 #if HAVE_SYS_STAT_H
42 #include <sys/stat.h>
43 #endif
44 #if HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47 
48 #if HAVE_UNISTD_H
49 #include <unistd.h>
50 #endif
51 
52 #if HAVE_LIMITS_H
53 #include <limits.h>
54 #endif
55 
56 #ifdef PHP_WIN32
57 # include "win32/nice.h"
58 #endif
59 
60 static size_t cmd_max_len;
61 
62 /* {{{ PHP_MINIT_FUNCTION(exec) */
PHP_MINIT_FUNCTION(exec)63 PHP_MINIT_FUNCTION(exec)
64 {
65 #ifdef _SC_ARG_MAX
66 	cmd_max_len = sysconf(_SC_ARG_MAX);
67 	if ((size_t)-1 == cmd_max_len) {
68 #ifdef _POSIX_ARG_MAX
69 		cmd_max_len = _POSIX_ARG_MAX;
70 #else
71 		cmd_max_len = 4096;
72 #endif
73 	}
74 #elif defined(ARG_MAX)
75 	cmd_max_len = ARG_MAX;
76 #elif defined(PHP_WIN32)
77 	/* Executed commands will run through cmd.exe. As long as it's the case,
78 		it's just the constant limit.*/
79 	cmd_max_len = 8192;
80 #else
81 	/* This is just an arbitrary value for the fallback case. */
82 	cmd_max_len = 4096;
83 #endif
84 
85 	return SUCCESS;
86 }
87 /* }}} */
88 
89 /* {{{ php_exec
90  * If type==0, only last line of output is returned (exec)
91  * If type==1, all lines will be printed and last lined returned (system)
92  * If type==2, all lines will be saved to given array (exec with &$array)
93  * If type==3, output will be printed binary, no lines will be saved or returned (passthru)
94  *
95  */
php_exec(int type,char * cmd,zval * array,zval * return_value)96 PHPAPI int php_exec(int type, char *cmd, zval *array, zval *return_value)
97 {
98 	FILE *fp;
99 	char *buf;
100 	size_t l = 0;
101 	int pclose_return;
102 	char *b, *d=NULL;
103 	php_stream *stream;
104 	size_t buflen, bufl = 0;
105 #if PHP_SIGCHILD
106 	void (*sig_handler)() = NULL;
107 #endif
108 
109 #if PHP_SIGCHILD
110 	sig_handler = signal (SIGCHLD, SIG_DFL);
111 #endif
112 
113 #ifdef PHP_WIN32
114 	fp = VCWD_POPEN(cmd, "rb");
115 #else
116 	fp = VCWD_POPEN(cmd, "r");
117 #endif
118 	if (!fp) {
119 		php_error_docref(NULL, E_WARNING, "Unable to fork [%s]", cmd);
120 		goto err;
121 	}
122 
123 	stream = php_stream_fopen_from_pipe(fp, "rb");
124 
125 	buf = (char *) emalloc(EXEC_INPUT_BUF);
126 	buflen = EXEC_INPUT_BUF;
127 
128 	if (type != 3) {
129 		b = buf;
130 
131 		while (php_stream_get_line(stream, b, EXEC_INPUT_BUF, &bufl)) {
132 			/* no new line found, let's read some more */
133 			if (b[bufl - 1] != '\n' && !php_stream_eof(stream)) {
134 				if (buflen < (bufl + (b - buf) + EXEC_INPUT_BUF)) {
135 					bufl += b - buf;
136 					buflen = bufl + EXEC_INPUT_BUF;
137 					buf = erealloc(buf, buflen);
138 					b = buf + bufl;
139 				} else {
140 					b += bufl;
141 				}
142 				continue;
143 			} else if (b != buf) {
144 				bufl += b - buf;
145 			}
146 
147 			if (type == 1) {
148 				PHPWRITE(buf, bufl);
149 				if (php_output_get_level() < 1) {
150 					sapi_flush();
151 				}
152 			} else if (type == 2) {
153 				/* strip trailing whitespaces */
154 				l = bufl;
155 				while (l-- > 0 && isspace(((unsigned char *)buf)[l]));
156 				if (l != (bufl - 1)) {
157 					bufl = l + 1;
158 					buf[bufl] = '\0';
159 				}
160 				add_next_index_stringl(array, buf, bufl);
161 			}
162 			b = buf;
163 		}
164 		if (bufl) {
165 			/* output remaining data in buffer */
166 			if (type == 1 && buf != b) {
167 				PHPWRITE(buf, bufl);
168 				if (php_output_get_level() < 1) {
169 					sapi_flush();
170 				}
171 			}
172 			/* strip trailing whitespaces if we have not done so already */
173 			if ((type == 2 && buf != b) || type != 2) {
174 				l = bufl;
175 				while (l-- > 0 && isspace(((unsigned char *)buf)[l]));
176 				if (l != (bufl - 1)) {
177 					bufl = l + 1;
178 					buf[bufl] = '\0';
179 				}
180 				if (type == 2) {
181 					add_next_index_stringl(array, buf, bufl);
182 				}
183 			}
184 
185 			/* Return last line from the shell command */
186 			RETVAL_STRINGL(buf, bufl);
187 		} else { /* should return NULL, but for BC we return "" */
188 			RETVAL_EMPTY_STRING();
189 		}
190 	} else {
191 		while((bufl = php_stream_read(stream, buf, EXEC_INPUT_BUF)) > 0) {
192 			PHPWRITE(buf, bufl);
193 		}
194 	}
195 
196 	pclose_return = php_stream_close(stream);
197 	efree(buf);
198 
199 done:
200 #if PHP_SIGCHILD
201 	if (sig_handler) {
202 		signal(SIGCHLD, sig_handler);
203 	}
204 #endif
205 	if (d) {
206 		efree(d);
207 	}
208 	return pclose_return;
209 err:
210 	pclose_return = -1;
211 	goto done;
212 }
213 /* }}} */
214 
php_exec_ex(INTERNAL_FUNCTION_PARAMETERS,int mode)215 static void php_exec_ex(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */
216 {
217 	char *cmd;
218 	size_t cmd_len;
219 	zval *ret_code=NULL, *ret_array=NULL;
220 	int ret;
221 
222 	ZEND_PARSE_PARAMETERS_START(1, (mode ? 2 : 3))
223 		Z_PARAM_STRING(cmd, cmd_len)
224 		Z_PARAM_OPTIONAL
225 		if (!mode) {
226 			Z_PARAM_ZVAL_DEREF(ret_array)
227 		}
228 		Z_PARAM_ZVAL_DEREF(ret_code)
229 	ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
230 
231 	if (!cmd_len) {
232 		php_error_docref(NULL, E_WARNING, "Cannot execute a blank command");
233 		RETURN_FALSE;
234 	}
235 	if (strlen(cmd) != cmd_len) {
236 		php_error_docref(NULL, E_WARNING, "NULL byte detected. Possible attack");
237 		RETURN_FALSE;
238 	}
239 
240 	if (!ret_array) {
241 		ret = php_exec(mode, cmd, NULL, return_value);
242 	} else {
243 		if (Z_TYPE_P(ret_array) != IS_ARRAY) {
244 			zval_ptr_dtor(ret_array);
245 			array_init(ret_array);
246 		} else if (Z_REFCOUNT_P(ret_array) > 1) {
247 			zval_ptr_dtor(ret_array);
248 			ZVAL_ARR(ret_array, zend_array_dup(Z_ARR_P(ret_array)));
249 		}
250 		ret = php_exec(2, cmd, ret_array, return_value);
251 	}
252 	if (ret_code) {
253 		zval_ptr_dtor(ret_code);
254 		ZVAL_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 		php_error_docref(NULL, E_WARNING, "%s", php_win_err());
584 #else
585 		php_error_docref(NULL, E_WARNING, "Only a super user may attempt to increase the priority of a process");
586 #endif
587 		RETURN_FALSE;
588 	}
589 
590 	RETURN_TRUE;
591 }
592 /* }}} */
593 #endif
594 
595 /*
596  * Local variables:
597  * tab-width: 4
598  * c-basic-offset: 4
599  * End:
600  * vim600: sw=4 ts=4 fdm=marker
601  * vim<600: sw=4 ts=4
602  */
603