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