Merge "Use {{int:}} on MediaWiki:Blockedtext and MediaWiki:Autoblockedtext"
[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 * Don't apply any restrictions
106 *
107 * @since 1.31
108 */
109 const RESTRICT_NONE = 0;
110
111 /**
112 * Returns a new instance of Command class
113 *
114 * @param string|string[] $command 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'"
117 * @return Command
118 */
119 public static function command( $command ) {
120 $args = func_get_args();
121 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
122 // If only one argument has been passed, and that argument is an array,
123 // treat it as a list of arguments
124 $args = reset( $args );
125 }
126 $command = MediaWikiServices::getInstance()
127 ->getShellCommandFactory()
128 ->create();
129
130 return $command->params( $args );
131 }
132
133 /**
134 * Check if this class is effectively disabled via php.ini config
135 *
136 * @return bool
137 */
138 public static function isDisabled() {
139 static $disabled = null;
140
141 if ( is_null( $disabled ) ) {
142 if ( !function_exists( 'proc_open' ) ) {
143 wfDebug( "proc_open() is disabled\n" );
144 $disabled = true;
145 } else {
146 $disabled = false;
147 }
148 }
149
150 return $disabled;
151 }
152
153 /**
154 * Version of escapeshellarg() that works better on Windows.
155 *
156 * Originally, this fixed the incorrect use of single quotes on Windows
157 * (https://bugs.php.net/bug.php?id=26285) and the locale problems on Linux in
158 * PHP 5.2.6+ (bug backported to earlier distro releases of PHP).
159 *
160 * @param string $args,... strings to escape and glue together, or a single array of
161 * strings parameter. Null values are ignored.
162 * @return string
163 */
164 public static function escape( /* ... */ ) {
165 $args = func_get_args();
166 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
167 // If only one argument has been passed, and that argument is an array,
168 // treat it as a list of arguments
169 $args = reset( $args );
170 }
171
172 $first = true;
173 $retVal = '';
174 foreach ( $args as $arg ) {
175 if ( $arg === null ) {
176 continue;
177 }
178 if ( !$first ) {
179 $retVal .= ' ';
180 } else {
181 $first = false;
182 }
183
184 if ( wfIsWindows() ) {
185 // Escaping for an MSVC-style command line parser and CMD.EXE
186 // Refs:
187 // * https://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
188 // * https://technet.microsoft.com/en-us/library/cc723564.aspx
189 // * T15518
190 // * CR r63214
191 // Double the backslashes before any double quotes. Escape the double quotes.
192 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
193 $arg = '';
194 $iteration = 0;
195 foreach ( $tokens as $token ) {
196 if ( $iteration % 2 == 1 ) {
197 // Delimiter, a double quote preceded by zero or more slashes
198 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
199 } elseif ( $iteration % 4 == 2 ) {
200 // ^ in $token will be outside quotes, need to be escaped
201 $arg .= str_replace( '^', '^^', $token );
202 } else { // $iteration % 4 == 0
203 // ^ in $token will appear inside double quotes, so leave as is
204 $arg .= $token;
205 }
206 $iteration++;
207 }
208 // Double the backslashes before the end of the string, because
209 // we will soon add a quote
210 $m = [];
211 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
212 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
213 }
214
215 // Add surrounding quotes
216 $retVal .= '"' . $arg . '"';
217 } else {
218 $retVal .= escapeshellarg( $arg );
219 }
220 }
221 return $retVal;
222 }
223
224 /**
225 * Generate a Command object to run a MediaWiki CLI script.
226 * Note that $parameters should be a flat array and an option with an argument
227 * should consist of two consecutive items in the array (do not use "--option value").
228 *
229 * @param string $script MediaWiki CLI script with full path
230 * @param string[] $parameters Arguments and options to the script
231 * @param array $options Associative array of options:
232 * 'php': The path to the php executable
233 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
234 * @return Command
235 */
236 public static function makeScriptCommand( $script, $parameters, $options = [] ) {
237 global $wgPhpCli;
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 = isset( $options['php'] ) ? [ $options['php'] ] : [ $wgPhpCli ];
242 if ( isset( $options['wrapper'] ) ) {
243 $cmd[] = $options['wrapper'];
244 }
245 $cmd[] = $script;
246
247 return self::command( $cmd )
248 ->params( $parameters )
249 ->restrict( self::RESTRICT_DEFAULT & ~self::NO_LOCALSETTINGS );
250 }
251 }