3 * Class used for executing shell commands
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace MediaWiki\Shell
;
26 use MediaWiki\MediaWikiServices
;
29 * Executes shell commands
33 * Use call chaining with this class for expressiveness:
34 * $result = Shell::command( 'some command' )
36 * ->environment( [ 'ENVIRONMENT_VARIABLE' => 'VALUE' ] )
37 * ->limits( [ 'time' => 300 ] )
40 * ... = $result->getExitCode();
41 * ... = $result->getStdout();
42 * ... = $result->getStderr();
47 * Disallow any root access. Any setuid binaries
48 * will be run without elevated access.
55 * Use seccomp to block dangerous syscalls
56 * @see <https://en.wikipedia.org/wiki/seccomp>
63 * Create a private /dev
67 const PRIVATE_DEV
= 4;
70 * Restrict the request to have no
78 * Deny execve syscall with seccomp
79 * @see <https://en.wikipedia.org/wiki/exec_(system_call)>
86 * Deny access to LocalSettings.php (MW_CONFIG_FILE)
90 const NO_LOCALSETTINGS
= 32;
93 * Apply a default set of restrictions for improved
94 * security out of the box.
96 * @note This value will change over time to provide increased security
97 * by default, and is not guaranteed to be backwards-compatible.
100 const RESTRICT_DEFAULT
= self
::NO_ROOT | self
::SECCOMP | self
::PRIVATE_DEV |
101 self
::NO_LOCALSETTINGS
;
104 * Don't apply any restrictions
108 const RESTRICT_NONE
= 0;
111 * Returns a new instance of Command class
113 * @note You should check Shell::isDisabled() before calling this
114 * @param string|string[] ...$commands String or array of strings representing the command to
115 * be executed, each value will be escaped.
116 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
119 public static function command( ...$commands ): Command
{
120 if ( count( $commands ) === 1 && is_array( reset( $commands ) ) ) {
121 // If only one argument has been passed, and that argument is an array,
122 // treat it as a list of arguments
123 $commands = reset( $commands );
125 $command = MediaWikiServices
::getInstance()
126 ->getShellCommandFactory()
129 return $command->params( $commands );
133 * Check if this class is effectively disabled via php.ini config
137 public static function isDisabled() {
138 static $disabled = null;
140 if ( is_null( $disabled ) ) {
141 if ( !function_exists( 'proc_open' ) ) {
142 wfDebug( "proc_open() is disabled\n" );
153 * Version of escapeshellarg() that works better on Windows.
155 * Originally, this fixed the incorrect use of single quotes on Windows
156 * (https://bugs.php.net/bug.php?id=26285) and the locale problems on Linux in
157 * PHP 5.2.6+ (bug backported to earlier distro releases of PHP).
159 * @param string|string[] ...$args strings to escape and glue together, or a single
160 * array of strings parameter. Null values are ignored.
163 public static function escape( ...$args ) {
164 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
165 // If only one argument has been passed, and that argument is an array,
166 // treat it as a list of arguments
167 $args = reset( $args );
172 foreach ( $args as $arg ) {
173 if ( $arg === null ) {
182 if ( wfIsWindows() ) {
183 // Escaping for an MSVC-style command line parser and CMD.EXE
185 // * https://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
186 // * https://technet.microsoft.com/en-us/library/cc723564.aspx
189 // Double the backslashes before any double quotes. Escape the double quotes.
190 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
193 foreach ( $tokens as $token ) {
194 if ( $iteration %
2 == 1 ) {
195 // Delimiter, a double quote preceded by zero or more slashes
196 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
197 } elseif ( $iteration %
4 == 2 ) {
198 // ^ in $token will be outside quotes, need to be escaped
199 $arg .= str_replace( '^', '^^', $token );
200 } else { // $iteration % 4 == 0
201 // ^ in $token will appear inside double quotes, so leave as is
206 // Double the backslashes before the end of the string, because
207 // we will soon add a quote
209 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
210 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
213 // Add surrounding quotes
214 $retVal .= '"' . $arg . '"';
216 $retVal .= escapeshellarg( $arg );
223 * Generate a Command object to run a MediaWiki CLI script.
224 * Note that $parameters should be a flat array and an option with an argument
225 * should consist of two consecutive items in the array (do not use "--option value").
227 * @note You should check Shell::isDisabled() before calling this
228 * @param string $script MediaWiki CLI script with full path
229 * @param string[] $parameters Arguments and options to the script
230 * @param array $options Associative array of options:
231 * 'php': The path to the php executable
232 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
233 * @phan-param array{php?:string,wrapper?:string} $options
236 public static function makeScriptCommand( $script, $parameters, $options = [] ): Command
{
238 // Give site config file a chance to run the script in a wrapper.
239 // The caller may likely want to call wfBasename() on $script.
240 Hooks
::run( 'wfShellWikiCmd', [ &$script, &$parameters, &$options ] );
241 $cmd = [ $options['php'] ??
$wgPhpCli ];
242 if ( isset( $options['wrapper'] ) ) {
243 $cmd[] = $options['wrapper'];
247 return self
::command( $cmd )
248 ->params( $parameters )
249 ->restrict( self
::RESTRICT_DEFAULT
& ~self
::NO_LOCALSETTINGS
);