shell: Optionally restrict commands' access with firejail
[lhc/web/wiklou.git] / includes / shell / Command.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Shell;
22
23 use Exception;
24 use MediaWiki\ProcOpenError;
25 use MediaWiki\ShellDisabledError;
26 use Profiler;
27 use Psr\Log\LoggerAwareTrait;
28 use Psr\Log\NullLogger;
29
30 /**
31 * Class used for executing shell commands
32 *
33 * @since 1.30
34 */
35 class Command {
36 use LoggerAwareTrait;
37
38 /** @var string */
39 private $command = '';
40
41 /** @var array */
42 private $limits = [
43 // seconds
44 'time' => 180,
45 // seconds
46 'walltime' => 180,
47 // KB
48 'memory' => 307200,
49 // KB
50 'filesize' => 102400,
51 ];
52
53 /** @var string[] */
54 private $env = [];
55
56 /** @var string */
57 private $method;
58
59 /** @var bool */
60 private $doIncludeStderr = false;
61
62 /** @var bool */
63 private $doLogStderr = false;
64
65 /** @var bool */
66 private $everExecuted = false;
67
68 /** @var string|false */
69 private $cgroup = false;
70
71 /**
72 * bitfield with restrictions
73 *
74 * @var int
75 */
76 protected $restrictions = 0;
77
78 /**
79 * Constructor. Don't call directly, instead use Shell::command()
80 *
81 * @throws ShellDisabledError
82 */
83 public function __construct() {
84 if ( Shell::isDisabled() ) {
85 throw new ShellDisabledError();
86 }
87
88 $this->setLogger( new NullLogger() );
89 }
90
91 /**
92 * Destructor. Makes sure programmer didn't forget to execute the command after all
93 */
94 public function __destruct() {
95 if ( !$this->everExecuted ) {
96 $context = [ 'command' => $this->command ];
97 $message = __CLASS__ . " was instantiated, but execute() was never called.";
98 if ( $this->method ) {
99 $message .= ' Calling method: {method}.';
100 $context['method'] = $this->method;
101 }
102 $message .= ' Command: {command}';
103 $this->logger->warning( $message, $context );
104 }
105 }
106
107 /**
108 * Adds parameters to the command. All parameters are sanitized via Shell::escape().
109 *
110 * @param string|string[] $args,...
111 * @return $this
112 */
113 public function params( /* ... */ ) {
114 $args = func_get_args();
115 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
116 // If only one argument has been passed, and that argument is an array,
117 // treat it as a list of arguments
118 $args = reset( $args );
119 }
120 $this->command .= ' ' . Shell::escape( $args );
121
122 return $this;
123 }
124
125 /**
126 * Adds unsafe parameters to the command. These parameters are NOT sanitized in any way.
127 *
128 * @param string|string[] $args,...
129 * @return $this
130 */
131 public function unsafeParams( /* ... */ ) {
132 $args = func_get_args();
133 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
134 // If only one argument has been passed, and that argument is an array,
135 // treat it as a list of arguments
136 $args = reset( $args );
137 }
138 $this->command .= implode( ' ', $args );
139
140 return $this;
141 }
142
143 /**
144 * Sets execution limits
145 *
146 * @param array $limits Associative array of limits. Keys (all optional):
147 * filesize (for ulimit -f), memory, time, walltime.
148 * @return $this
149 */
150 public function limits( array $limits ) {
151 if ( !isset( $limits['walltime'] ) && isset( $limits['time'] ) ) {
152 // Emulate the behavior of old wfShellExec() where walltime fell back on time
153 // if the latter was overridden and the former wasn't
154 $limits['walltime'] = $limits['time'];
155 }
156 $this->limits = $limits + $this->limits;
157
158 return $this;
159 }
160
161 /**
162 * Sets environment variables which should be added to the executed command environment
163 *
164 * @param string[] $env array of variable name => value
165 * @return $this
166 */
167 public function environment( array $env ) {
168 $this->env = $env;
169
170 return $this;
171 }
172
173 /**
174 * Sets calling function for profiler. By default, the caller for execute() will be used.
175 *
176 * @param string $method
177 * @return $this
178 */
179 public function profileMethod( $method ) {
180 $this->method = $method;
181
182 return $this;
183 }
184
185 /**
186 * Controls whether stderr should be included in stdout, including errors from limit.sh.
187 * Default: don't include.
188 *
189 * @param bool $yesno
190 * @return $this
191 */
192 public function includeStderr( $yesno = true ) {
193 $this->doIncludeStderr = $yesno;
194
195 return $this;
196 }
197
198 /**
199 * When enabled, text sent to stderr will be logged with a level of 'error'.
200 *
201 * @param bool $yesno
202 * @return $this
203 */
204 public function logStderr( $yesno = true ) {
205 $this->doLogStderr = $yesno;
206
207 return $this;
208 }
209
210 /**
211 * Sets cgroup for this command
212 *
213 * @param string|false $cgroup Absolute file path to the cgroup, or false to not use a cgroup
214 * @return $this
215 */
216 public function cgroup( $cgroup ) {
217 $this->cgroup = $cgroup;
218
219 return $this;
220 }
221
222 /**
223 * Set additional restrictions for this request
224 *
225 * @since 1.31
226 * @param int $restrictions
227 * @return $this
228 */
229 public function restrict( $restrictions ) {
230 $this->restrictions |= $restrictions;
231
232 return $this;
233 }
234
235 /**
236 * Bitfield helper on whether a specific restriction is enabled
237 *
238 * @param int $restriction
239 *
240 * @return bool
241 */
242 protected function hasRestriction( $restriction ) {
243 return ( $this->restrictions & $restriction ) === $restriction;
244 }
245
246 /**
247 * If called, only the files/directories that are
248 * whitelisted will be available to the shell command.
249 *
250 * limit.sh will always be whitelisted
251 *
252 * @param string[] $paths
253 *
254 * @return $this
255 */
256 public function whitelistPaths( array $paths ) {
257 // Default implementation is a no-op
258 return $this;
259 }
260
261 /**
262 * String together all the options and build the final command
263 * to execute
264 *
265 * @return array [ command, whether to use log pipe ]
266 */
267 protected function buildFinalCommand() {
268 $envcmd = '';
269 foreach ( $this->env as $k => $v ) {
270 if ( wfIsWindows() ) {
271 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
272 * appear in the environment variable, so we must use carat escaping as documented in
273 * https://technet.microsoft.com/en-us/library/cc723564.aspx
274 * Note however that the quote isn't listed there, but is needed, and the parentheses
275 * are listed there but doesn't appear to need it.
276 */
277 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
278 } else {
279 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
280 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
281 */
282 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
283 }
284 }
285
286 $useLogPipe = false;
287 $cmd = $envcmd . trim( $this->command );
288
289 if ( is_executable( '/bin/bash' ) ) {
290 $time = intval( $this->limits['time'] );
291 $wallTime = intval( $this->limits['walltime'] );
292 $mem = intval( $this->limits['memory'] );
293 $filesize = intval( $this->limits['filesize'] );
294
295 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
296 $cmd = '/bin/bash ' . escapeshellarg( __DIR__ . '/limit.sh' ) . ' ' .
297 escapeshellarg( $cmd ) . ' ' .
298 escapeshellarg(
299 "MW_INCLUDE_STDERR=" . ( $this->doIncludeStderr ? '1' : '' ) . ';' .
300 "MW_CPU_LIMIT=$time; " .
301 'MW_CGROUP=' . escapeshellarg( $this->cgroup ) . '; ' .
302 "MW_MEM_LIMIT=$mem; " .
303 "MW_FILE_SIZE_LIMIT=$filesize; " .
304 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
305 "MW_USE_LOG_PIPE=yes"
306 );
307 $useLogPipe = true;
308 }
309 }
310 if ( !$useLogPipe && $this->doIncludeStderr ) {
311 $cmd .= ' 2>&1';
312 }
313
314 return [ $cmd, $useLogPipe ];
315 }
316
317 /**
318 * Executes command. Afterwards, getExitCode() and getOutput() can be used to access execution
319 * results.
320 *
321 * @return Result
322 * @throws Exception
323 * @throws ProcOpenError
324 * @throws ShellDisabledError
325 */
326 public function execute() {
327 $this->everExecuted = true;
328
329 $profileMethod = $this->method ?: wfGetCaller();
330
331 list( $cmd, $useLogPipe ) = $this->buildFinalCommand();
332
333 $this->logger->debug( __METHOD__ . ": $cmd" );
334
335 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
336 // Other platforms may be more accomodating, but we don't want to be
337 // accomodating, because very long commands probably include user
338 // input. See T129506.
339 if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN ) {
340 throw new Exception( __METHOD__ .
341 '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
342 }
343
344 $desc = [
345 0 => [ 'file', 'php://stdin', 'r' ],
346 1 => [ 'pipe', 'w' ],
347 2 => [ 'pipe', 'w' ],
348 ];
349 if ( $useLogPipe ) {
350 $desc[3] = [ 'pipe', 'w' ];
351 }
352 $pipes = null;
353 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
354 $proc = proc_open( $cmd, $desc, $pipes );
355 if ( !$proc ) {
356 $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
357 throw new ProcOpenError();
358 }
359 $outBuffer = $logBuffer = '';
360 $errBuffer = null;
361 $emptyArray = [];
362 $status = false;
363 $logMsg = false;
364
365 /* According to the documentation, it is possible for stream_select()
366 * to fail due to EINTR. I haven't managed to induce this in testing
367 * despite sending various signals. If it did happen, the error
368 * message would take the form:
369 *
370 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
371 *
372 * where [4] is the value of the macro EINTR and "Interrupted system
373 * call" is string which according to the Linux manual is "possibly"
374 * localised according to LC_MESSAGES.
375 */
376 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
377 $eintrMessage = "stream_select(): unable to select [$eintr]";
378
379 $running = true;
380 $timeout = null;
381 $numReadyPipes = 0;
382
383 while ( $running === true || $numReadyPipes !== 0 ) {
384 if ( $running ) {
385 $status = proc_get_status( $proc );
386 // If the process has terminated, switch to nonblocking selects
387 // for getting any data still waiting to be read.
388 if ( !$status['running'] ) {
389 $running = false;
390 $timeout = 0;
391 }
392 }
393
394 $readyPipes = $pipes;
395
396 // clear get_last_error without actually raising an error
397 // from http://php.net/manual/en/function.error-get-last.php#113518
398 // TODO replace with clear_last_error when requirements are bumped to PHP7
399 set_error_handler( function () {
400 }, 0 );
401 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
402 @trigger_error( '' );
403 // @codingStandardsIgnoreEnd
404 restore_error_handler();
405
406 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
407 $numReadyPipes = @stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
408 // @codingStandardsIgnoreEnd
409 if ( $numReadyPipes === false ) {
410 $error = error_get_last();
411 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
412 continue;
413 } else {
414 trigger_error( $error['message'], E_USER_WARNING );
415 $logMsg = $error['message'];
416 break;
417 }
418 }
419 foreach ( $readyPipes as $fd => $pipe ) {
420 $block = fread( $pipe, 65536 );
421 if ( $block === '' ) {
422 // End of file
423 fclose( $pipes[$fd] );
424 unset( $pipes[$fd] );
425 if ( !$pipes ) {
426 break 2;
427 }
428 } elseif ( $block === false ) {
429 // Read error
430 $logMsg = "Error reading from pipe";
431 break 2;
432 } elseif ( $fd == 1 ) {
433 // From stdout
434 $outBuffer .= $block;
435 } elseif ( $fd == 2 ) {
436 // From stderr
437 $errBuffer .= $block;
438 } elseif ( $fd == 3 ) {
439 // From log FD
440 $logBuffer .= $block;
441 if ( strpos( $block, "\n" ) !== false ) {
442 $lines = explode( "\n", $logBuffer );
443 $logBuffer = array_pop( $lines );
444 foreach ( $lines as $line ) {
445 $this->logger->info( $line );
446 }
447 }
448 }
449 }
450 }
451
452 foreach ( $pipes as $pipe ) {
453 fclose( $pipe );
454 }
455
456 // Use the status previously collected if possible, since proc_get_status()
457 // just calls waitpid() which will not return anything useful the second time.
458 if ( $running ) {
459 $status = proc_get_status( $proc );
460 }
461
462 if ( $logMsg !== false ) {
463 // Read/select error
464 $retval = -1;
465 proc_close( $proc );
466 } elseif ( $status['signaled'] ) {
467 $logMsg = "Exited with signal {$status['termsig']}";
468 $retval = 128 + $status['termsig'];
469 proc_close( $proc );
470 } else {
471 if ( $status['running'] ) {
472 $retval = proc_close( $proc );
473 } else {
474 $retval = $status['exitcode'];
475 proc_close( $proc );
476 }
477 if ( $retval == 127 ) {
478 $logMsg = "Possibly missing executable file";
479 } elseif ( $retval >= 129 && $retval <= 192 ) {
480 $logMsg = "Probably exited with signal " . ( $retval - 128 );
481 }
482 }
483
484 if ( $logMsg !== false ) {
485 $this->logger->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
486 }
487
488 if ( $errBuffer && $this->doLogStderr ) {
489 $this->logger->error( "Error running {command}: {error}", [
490 'command' => $cmd,
491 'error' => $errBuffer,
492 'exitcode' => $retval,
493 'exception' => new Exception( 'Shell error' ),
494 ] );
495 }
496
497 return new Result( $retval, $outBuffer, $errBuffer );
498 }
499 }