Deprecate wfShellWikiCmd()
[lhc/web/wiklou.git] / includes / shell / Shell.php
1 <?php
2 /**
3 * Class used for executing shell commands
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 namespace MediaWiki\Shell;
24
25 use Hooks;
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * Executes shell commands
30 *
31 * @since 1.30
32 *
33 * Use call chaining with this class for expressiveness:
34 * $result = Shell::command( 'some command' )
35 * ->input( 'foo' )
36 * ->environment( [ 'ENVIRONMENT_VARIABLE' => 'VALUE' ] )
37 * ->limits( [ 'time' => 300 ] )
38 * ->execute();
39 *
40 * ... = $result->getExitCode();
41 * ... = $result->getStdout();
42 * ... = $result->getStderr();
43 */
44 class Shell {
45
46 /**
47 * Apply a default set of restrictions for improved
48 * security out of the box.
49 *
50 * Equal to NO_ROOT | SECCOMP | PRIVATE_DEV | NO_LOCALSETTINGS
51 *
52 * @note This value will change over time to provide increased security
53 * by default, and is not guaranteed to be backwards-compatible.
54 * @since 1.31
55 */
56 const RESTRICT_DEFAULT = 39;
57
58 /**
59 * Disallow any root access. Any setuid binaries
60 * will be run without elevated access.
61 *
62 * @since 1.31
63 */
64 const NO_ROOT = 1;
65
66 /**
67 * Use seccomp to block dangerous syscalls
68 * @see <https://en.wikipedia.org/wiki/seccomp>
69 *
70 * @since 1.31
71 */
72 const SECCOMP = 2;
73
74 /**
75 * Create a private /dev
76 *
77 * @since 1.31
78 */
79 const PRIVATE_DEV = 4;
80
81 /**
82 * Restrict the request to have no
83 * network access
84 *
85 * @since 1.31
86 */
87 const NO_NETWORK = 8;
88
89 /**
90 * Deny execve syscall with seccomp
91 * @see <https://en.wikipedia.org/wiki/exec_(system_call)>
92 *
93 * @since 1.31
94 */
95 const NO_EXECVE = 16;
96
97 /**
98 * Deny access to LocalSettings.php (MW_CONFIG_FILE)
99 *
100 * @since 1.31
101 */
102 const NO_LOCALSETTINGS = 32;
103
104 /**
105 * Returns a new instance of Command class
106 *
107 * @param string|string[] $command String or array of strings representing the command to
108 * be executed, each value will be escaped.
109 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
110 * @return Command
111 */
112 public static function command( $command ) {
113 $args = func_get_args();
114 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
115 // If only one argument has been passed, and that argument is an array,
116 // treat it as a list of arguments
117 $args = reset( $args );
118 }
119 $command = MediaWikiServices::getInstance()
120 ->getShellCommandFactory()
121 ->create();
122
123 return $command->params( $args );
124 }
125
126 /**
127 * Check if this class is effectively disabled via php.ini config
128 *
129 * @return bool
130 */
131 public static function isDisabled() {
132 static $disabled = null;
133
134 if ( is_null( $disabled ) ) {
135 if ( !function_exists( 'proc_open' ) ) {
136 wfDebug( "proc_open() is disabled\n" );
137 $disabled = true;
138 } else {
139 $disabled = false;
140 }
141 }
142
143 return $disabled;
144 }
145
146 /**
147 * Version of escapeshellarg() that works better on Windows.
148 *
149 * Originally, this fixed the incorrect use of single quotes on Windows
150 * (https://bugs.php.net/bug.php?id=26285) and the locale problems on Linux in
151 * PHP 5.2.6+ (bug backported to earlier distro releases of PHP).
152 *
153 * @param string $args,... strings to escape and glue together, or a single array of
154 * strings parameter. Null values are ignored.
155 * @return string
156 */
157 public static function escape( /* ... */ ) {
158 $args = func_get_args();
159 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
160 // If only one argument has been passed, and that argument is an array,
161 // treat it as a list of arguments
162 $args = reset( $args );
163 }
164
165 $first = true;
166 $retVal = '';
167 foreach ( $args as $arg ) {
168 if ( $arg === null ) {
169 continue;
170 }
171 if ( !$first ) {
172 $retVal .= ' ';
173 } else {
174 $first = false;
175 }
176
177 if ( wfIsWindows() ) {
178 // Escaping for an MSVC-style command line parser and CMD.EXE
179 // Refs:
180 // * https://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
181 // * https://technet.microsoft.com/en-us/library/cc723564.aspx
182 // * T15518
183 // * CR r63214
184 // Double the backslashes before any double quotes. Escape the double quotes.
185 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
186 $arg = '';
187 $iteration = 0;
188 foreach ( $tokens as $token ) {
189 if ( $iteration % 2 == 1 ) {
190 // Delimiter, a double quote preceded by zero or more slashes
191 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
192 } elseif ( $iteration % 4 == 2 ) {
193 // ^ in $token will be outside quotes, need to be escaped
194 $arg .= str_replace( '^', '^^', $token );
195 } else { // $iteration % 4 == 0
196 // ^ in $token will appear inside double quotes, so leave as is
197 $arg .= $token;
198 }
199 $iteration++;
200 }
201 // Double the backslashes before the end of the string, because
202 // we will soon add a quote
203 $m = [];
204 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
205 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
206 }
207
208 // Add surrounding quotes
209 $retVal .= '"' . $arg . '"';
210 } else {
211 $retVal .= escapeshellarg( $arg );
212 }
213 }
214 return $retVal;
215 }
216
217 /**
218 * Generate a Command object to run a MediaWiki CLI script.
219 * Note that $parameters should be a flat array and an option with an argument
220 * should consist of two consecutive items in the array (do not use "--option value").
221 *
222 * @param string $script MediaWiki CLI script with full path
223 * @param string[] $parameters Arguments and options to the script
224 * @param array $options Associative array of options:
225 * 'php': The path to the php executable
226 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
227 * @return Command
228 */
229 public static function makeScriptCommand( $script, $parameters, $options = [] ) {
230 global $wgPhpCli;
231 // Give site config file a chance to run the script in a wrapper.
232 // The caller may likely want to call wfBasename() on $script.
233 Hooks::run( 'wfShellWikiCmd', [ &$script, &$parameters, &$options ] );
234 $cmd = isset( $options['php'] ) ? [ $options['php'] ] : [ $wgPhpCli ];
235 if ( isset( $options['wrapper'] ) ) {
236 $cmd[] = $options['wrapper'];
237 }
238 $cmd[] = $script;
239
240 return self::command( $cmd )
241 ->params( $parameters )
242 ->restrict( self::RESTRICT_DEFAULT & ~self::NO_LOCALSETTINGS );
243 }
244 }