| 1 |
<?php |
| 2 |
|
| 3 |
namespace Shellbox\Command; |
| 4 |
|
| 5 |
use Shellbox\Shellbox; |
| 6 |
|
| 7 |
/** |
| 8 |
* A ulimit/cgroup wrapper implemented as a bash script |
| 9 |
*/ |
| 10 |
class BashWrapper extends Wrapper { |
| 11 |
/** @var bool|string */ |
| 12 |
private $cgroup; |
| 13 |
|
| 14 |
/** |
| 15 |
* Needs to be outside of firejail so that it can set up a cgroup. Also, |
| 16 |
* firejail may disable syscalls, breaking the bash wrapper. |
| 17 |
*/ |
| 18 |
public const PRIORITY = 60; |
| 19 |
|
| 20 |
/** |
| 21 |
* @param string|false $cgroup Under Linux: a cgroup directory used to constrain |
| 22 |
* memory usage of shell commands. The directory must be writable by the |
| 23 |
* web server. If this is false, no memory limit will be applied. |
| 24 |
*/ |
| 25 |
public function __construct( $cgroup = false ) { |
| 26 |
parent::__construct(); |
| 27 |
if ( strval( $cgroup ) === '' ) { |
| 28 |
$cgroup = ''; |
| 29 |
} |
| 30 |
$this->cgroup = $cgroup; |
| 31 |
} |
| 32 |
|
| 33 |
public function wrap( Command $command ) { |
| 34 |
$time = intval( $command->getCpuTimeLimit() ); |
| 35 |
$wallTime = intval( $command->getWallTimeLimit() ); |
| 36 |
$mem = intval( $command->getMemoryLimit() ); |
| 37 |
$filesize = intval( $command->getFileSizeLimit() ); |
| 38 |
|
| 39 |
if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) { |
| 40 |
$cmd = '/bin/bash ' . Shellbox::escape( __DIR__ . '/limit.sh' ) . ' ' . |
| 41 |
Shellbox::escape( $command->getCommandString() ) . ' ' . |
| 42 |
Shellbox::escape( |
| 43 |
"SB_INCLUDE_STDERR=" . ( $command->getIncludeStderr() ? '1' : '' ) . ';' . |
| 44 |
"SB_CPU_LIMIT=$time; " . |
| 45 |
'SB_CGROUP=' . Shellbox::escape( $this->cgroup ) . '; ' . |
| 46 |
"SB_MEM_LIMIT=$mem; " . |
| 47 |
"SB_FILE_SIZE_LIMIT=$filesize; " . |
| 48 |
"SB_WALL_CLOCK_LIMIT=$wallTime; " . |
| 49 |
"SB_USE_LOG_PIPE=yes" |
| 50 |
); |
| 51 |
$command->unsafeCommand( $cmd ) |
| 52 |
->useLogPipe(); |
| 53 |
if ( $command->getAllowedPaths() ) { |
| 54 |
// If specific paths have been allowed, make sure we explicitly |
| 55 |
// allow limit.sh. We don't do this unconditionally because it |
| 56 |
// doesn't work as expected in firejail, see T274474, T182486 |
| 57 |
$command->allowPath( __DIR__ . '/limit.sh' ); |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
public function getPriority() { |
| 63 |
return self::PRIORITY; |
| 64 |
} |
| 65 |
} |