Issues (4122)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

includes/debug/logger/LegacyLogger.php (2 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * This program is free software; you can redistribute it and/or modify
4
 * it under the terms of the GNU General Public License as published by
5
 * the Free Software Foundation; either version 2 of the License, or
6
 * (at your option) any later version.
7
 *
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
 * GNU General Public License for more details.
12
 *
13
 * You should have received a copy of the GNU General Public License along
14
 * with this program; if not, write to the Free Software Foundation, Inc.,
15
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16
 * http://www.gnu.org/copyleft/gpl.html
17
 *
18
 * @file
19
 */
20
21
namespace MediaWiki\Logger;
22
23
use DateTimeZone;
24
use Exception;
25
use MWDebug;
26
use MWExceptionHandler;
27
use Psr\Log\AbstractLogger;
28
use Psr\Log\LogLevel;
29
use UDPTransport;
30
31
/**
32
 * PSR-3 logger that mimics the historic implementation of MediaWiki's
33
 * wfErrorLog logging implementation.
34
 *
35
 * This logger is configured by the following global configuration variables:
36
 * - `$wgDebugLogFile`
37
 * - `$wgDebugLogGroups`
38
 * - `$wgDBerrorLog`
39
 * - `$wgDBerrorLogTZ`
40
 *
41
 * See documentation in DefaultSettings.php for detailed explanations of each
42
 * variable.
43
 *
44
 * @see \MediaWiki\Logger\LoggerFactory
45
 * @since 1.25
46
 * @author Bryan Davis <[email protected]>
47
 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
48
 */
49
class LegacyLogger extends AbstractLogger {
50
51
	/**
52
	 * @var string $channel
53
	 */
54
	protected $channel;
55
56
	/**
57
	 * Convert \Psr\Log\LogLevel constants into int for sane comparisons
58
	 * These are the same values that Monlog uses
59
	 *
60
	 * @var array $levelMapping
61
	 */
62
	protected static $levelMapping = [
63
		LogLevel::DEBUG => 100,
64
		LogLevel::INFO => 200,
65
		LogLevel::NOTICE => 250,
66
		LogLevel::WARNING => 300,
67
		LogLevel::ERROR => 400,
68
		LogLevel::CRITICAL => 500,
69
		LogLevel::ALERT => 550,
70
		LogLevel::EMERGENCY => 600,
71
	];
72
73
	/**
74
	 * @var array
75
	 */
76
	protected static $dbChannels = [
77
		'DBQuery' => true,
78
		'DBConnection' => true
79
	];
80
81
	/**
82
	 * @param string $channel
83
	 */
84
	public function __construct( $channel ) {
85
		$this->channel = $channel;
86
	}
87
88
	/**
89
	 * Logs with an arbitrary level.
90
	 *
91
	 * @param string|int $level
92
	 * @param string $message
93
	 * @param array $context
94
	 * @return null
95
	 */
96
	public function log( $level, $message, array $context = [] ) {
97
		if ( is_string( $level ) ) {
98
			$level = self::$levelMapping[$level];
99
		}
100
		if ( $this->channel === 'DBQuery' && isset( $context['method'] )
101
			&& isset( $context['master'] ) && isset( $context['runtime'] )
102
		) {
103
			MWDebug::query( $message, $context['method'], $context['master'], $context['runtime'] );
104
			return; // only send profiling data to MWDebug profiling
105
		}
106
107
		if ( isset( self::$dbChannels[$this->channel] )
108
			&& $level >= self::$levelMapping[LogLevel::ERROR]
109
		) {
110
			// Format and write DB errors to the legacy locations
111
			$effectiveChannel = 'wfLogDBError';
112
		} else {
113
			$effectiveChannel = $this->channel;
114
		}
115
116
		if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
117
			$text = self::format( $effectiveChannel, $message, $context );
118
			$destination = self::destination( $effectiveChannel, $message, $context );
119
			self::emit( $text, $destination );
120
		}
121
		if ( !isset( $context['private'] ) || !$context['private'] ) {
122
			// Add to debug toolbar if not marked as "private"
123
			MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
124
		}
125
	}
126
127
	/**
128
	 * Determine if the given message should be emitted or not.
129
	 *
130
	 * @param string $channel
131
	 * @param string $message
132
	 * @param string|int $level \Psr\Log\LogEvent constant or Monolog level int
133
	 * @param array $context
134
	 * @return bool True if message should be sent to disk/network, false
135
	 * otherwise
136
	 */
137
	public static function shouldEmit( $channel, $message, $level, $context ) {
138
		global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
139
140
		if ( is_string( $level ) ) {
141
			$level = self::$levelMapping[$level];
142
		}
143
144
		if ( $channel === 'wfLogDBError' ) {
145
			// wfLogDBError messages are emitted if a database log location is
146
			// specfied.
147
			$shouldEmit = (bool)$wgDBerrorLog;
148
149
		} elseif ( $channel === 'wfErrorLog' ) {
150
			// All messages on the wfErrorLog channel should be emitted.
151
			$shouldEmit = true;
152
153
		} elseif ( $channel === 'wfDebug' ) {
154
			// wfDebug messages are emitted if a catch all logging file has
155
			// been specified. Checked explicitly so that 'private' flagged
156
			// messages are not discarded by unset $wgDebugLogGroups channel
157
			// handling below.
158
			$shouldEmit = $wgDebugLogFile != '';
159
160
		} elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
161
			$logConfig = $wgDebugLogGroups[$channel];
162
163
			if ( is_array( $logConfig ) ) {
164
				$shouldEmit = true;
165
				if ( isset( $logConfig['sample'] ) ) {
166
					// Emit randomly with a 1 in 'sample' chance for each message.
167
					$shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
168
				}
169
170
				if ( isset( $logConfig['level'] ) ) {
171
					$shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
172
				}
173
			} else {
174
				// Emit unless the config value is explictly false.
175
				$shouldEmit = $logConfig !== false;
176
			}
177
178
		} elseif ( isset( $context['private'] ) && $context['private'] ) {
179
			// Don't emit if the message didn't match previous checks based on
180
			// the channel and the event is marked as private. This check
181
			// discards messages sent via wfDebugLog() with dest == 'private'
182
			// and no explicit wgDebugLogGroups configuration.
183
			$shouldEmit = false;
184
		} else {
185
			// Default return value is the same as the historic wfDebug
186
			// method: emit if $wgDebugLogFile has been set.
187
			$shouldEmit = $wgDebugLogFile != '';
188
		}
189
190
		return $shouldEmit;
191
	}
192
193
	/**
194
	 * Format a message.
195
	 *
196
	 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
197
	 * receive special fomatting to mimic the historic output of the functions
198
	 * of the same name. All other channel values are formatted based on the
199
	 * historic output of the `wfDebugLog()` global function.
200
	 *
201
	 * @param string $channel
202
	 * @param string $message
203
	 * @param array $context
204
	 * @return string
205
	 */
206
	public static function format( $channel, $message, $context ) {
207
		global $wgDebugLogGroups, $wgLogExceptionBacktrace;
208
209
		if ( $channel === 'wfDebug' ) {
210
			$text = self::formatAsWfDebug( $channel, $message, $context );
211
212
		} elseif ( $channel === 'wfLogDBError' ) {
213
			$text = self::formatAsWfLogDBError( $channel, $message, $context );
214
215
		} elseif ( $channel === 'wfErrorLog' ) {
216
			$text = "{$message}\n";
217
218
		} elseif ( $channel === 'profileoutput' ) {
219
			// Legacy wfLogProfilingData formatitng
220
			$forward = '';
221
			if ( isset( $context['forwarded_for'] ) ) {
222
				$forward = " forwarded for {$context['forwarded_for']}";
223
			}
224
			if ( isset( $context['client_ip'] ) ) {
225
				$forward .= " client IP {$context['client_ip']}";
226
			}
227
			if ( isset( $context['from'] ) ) {
228
				$forward .= " from {$context['from']}";
229
			}
230
			if ( $forward ) {
231
				$forward = "\t(proxied via {$context['proxy']}{$forward})";
232
			}
233
			if ( $context['anon'] ) {
234
				$forward .= ' anon';
235
			}
236
			if ( !isset( $context['url'] ) ) {
237
				$context['url'] = 'n/a';
238
			}
239
240
			$log = sprintf( "%s\t%04.3f\t%s%s\n",
241
				gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
242
243
			$text = self::formatAsWfDebugLog(
0 ignored issues
show
Are you sure the assignment to $text is correct as self::formatAsWfDebugLog...xt['output'], $context) (which targets MediaWiki\Logger\LegacyL...r::formatAsWfDebugLog()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
244
				$channel, $log . $context['output'], $context );
245
246
		} elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
247
			$text = self::formatAsWfDebug(
248
				$channel, "[{$channel}] {$message}", $context );
249
250
		} else {
251
			// Default formatting is wfDebugLog's historic style
252
			$text = self::formatAsWfDebugLog( $channel, $message, $context );
0 ignored issues
show
Are you sure the assignment to $text is correct as self::formatAsWfDebugLog...el, $message, $context) (which targets MediaWiki\Logger\LegacyL...r::formatAsWfDebugLog()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
253
		}
254
255
		// Append stacktrace of exception if available
256
		if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
257
			$e = $context['exception'];
258
			$backtrace = false;
259
260
			if ( $e instanceof Exception ) {
261
				$backtrace = MWExceptionHandler::getRedactedTrace( $e );
262
263
			} elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
264
				// Exception has already been unpacked as structured data
265
				$backtrace = $e['trace'];
266
			}
267
268
			if ( $backtrace ) {
269
				$text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
270
					"\n";
271
			}
272
		}
273
274
		return self::interpolate( $text, $context );
275
	}
276
277
	/**
278
	 * Format a message as `wfDebug()` would have formatted it.
279
	 *
280
	 * @param string $channel
281
	 * @param string $message
282
	 * @param array $context
283
	 * @return string
284
	 */
285
	protected static function formatAsWfDebug( $channel, $message, $context ) {
286
		$text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
287
		if ( isset( $context['seconds_elapsed'] ) ) {
288
			// Prepend elapsed request time and real memory usage with two
289
			// trailing spaces.
290
			$text = "{$context['seconds_elapsed']} {$context['memory_used']}  {$text}";
291
		}
292
		if ( isset( $context['prefix'] ) ) {
293
			$text = "{$context['prefix']}{$text}";
294
		}
295
		return "{$text}\n";
296
	}
297
298
	/**
299
	 * Format a message as `wfLogDBError()` would have formatted it.
300
	 *
301
	 * @param string $channel
302
	 * @param string $message
303
	 * @param array $context
304
	 * @return string
305
	 */
306
	protected static function formatAsWfLogDBError( $channel, $message, $context ) {
307
		global $wgDBerrorLogTZ;
308
		static $cachedTimezone = null;
309
310
		if ( !$cachedTimezone ) {
311
			$cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
312
		}
313
314
		$d = date_create( 'now', $cachedTimezone );
315
		$date = $d->format( 'D M j G:i:s T Y' );
316
317
		$host = wfHostname();
318
		$wiki = wfWikiID();
319
320
		$text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
321
		return $text;
322
	}
323
324
	/**
325
	 * Format a message as `wfDebugLog() would have formatted it.
326
	 *
327
	 * @param string $channel
328
	 * @param string $message
329
	 * @param array $context
330
	 * @return null
331
	 */
332
	protected static function formatAsWfDebugLog( $channel, $message, $context ) {
333
		$time = wfTimestamp( TS_DB );
334
		$wiki = wfWikiID();
335
		$host = wfHostname();
336
		$text = "{$time} {$host} {$wiki}: {$message}\n";
337
		return $text;
338
	}
339
340
	/**
341
	 * Interpolate placeholders in logging message.
342
	 *
343
	 * @param string $message
344
	 * @param array $context
345
	 * @return string Interpolated message
346
	 */
347
	public static function interpolate( $message, array $context ) {
348
		if ( strpos( $message, '{' ) !== false ) {
349
			$replace = [];
350
			foreach ( $context as $key => $val ) {
351
				$replace['{' . $key . '}'] = self::flatten( $val );
352
			}
353
			$message = strtr( $message, $replace );
354
		}
355
		return $message;
356
	}
357
358
	/**
359
	 * Convert a logging context element to a string suitable for
360
	 * interpolation.
361
	 *
362
	 * @param mixed $item
363
	 * @return string
364
	 */
365
	protected static function flatten( $item ) {
366
		if ( null === $item ) {
367
			return '[Null]';
368
		}
369
370
		if ( is_bool( $item ) ) {
371
			return $item ? 'true' : 'false';
372
		}
373
374
		if ( is_float( $item ) ) {
375
			if ( is_infinite( $item ) ) {
376
				return ( $item > 0 ? '' : '-' ) . 'INF';
377
			}
378
			if ( is_nan( $item ) ) {
379
				return 'NaN';
380
			}
381
			return $item;
382
		}
383
384
		if ( is_scalar( $item ) ) {
385
			return (string)$item;
386
		}
387
388
		if ( is_array( $item ) ) {
389
			return '[Array(' . count( $item ) . ')]';
390
		}
391
392
		if ( $item instanceof \DateTime ) {
393
			return $item->format( 'c' );
394
		}
395
396
		if ( $item instanceof Exception ) {
397
			return '[Exception ' . get_class( $item ) . '( ' .
398
				$item->getFile() . ':' . $item->getLine() . ') ' .
399
				$item->getMessage() . ']';
400
		}
401
402
		if ( is_object( $item ) ) {
403
			if ( method_exists( $item, '__toString' ) ) {
404
				return (string)$item;
405
			}
406
407
			return '[Object ' . get_class( $item ) . ']';
408
		}
409
410
		if ( is_resource( $item ) ) {
411
			return '[Resource ' . get_resource_type( $item ) . ']';
412
		}
413
414
		return '[Unknown ' . gettype( $item ) . ']';
415
	}
416
417
	/**
418
	 * Select the appropriate log output destination for the given log event.
419
	 *
420
	 * If the event context contains 'destination'
421
	 *
422
	 * @param string $channel
423
	 * @param string $message
424
	 * @param array $context
425
	 * @return string
426
	 */
427
	protected static function destination( $channel, $message, $context ) {
428
		global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
429
430
		// Default destination is the debug log file as historically used by
431
		// the wfDebug function.
432
		$destination = $wgDebugLogFile;
433
434
		if ( isset( $context['destination'] ) ) {
435
			// Use destination explicitly provided in context
436
			$destination = $context['destination'];
437
438
		} elseif ( $channel === 'wfDebug' ) {
439
			$destination = $wgDebugLogFile;
440
441
		} elseif ( $channel === 'wfLogDBError' ) {
442
			$destination = $wgDBerrorLog;
443
444
		} elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
445
			$logConfig = $wgDebugLogGroups[$channel];
446
447
			if ( is_array( $logConfig ) ) {
448
				$destination = $logConfig['destination'];
449
			} else {
450
				$destination = strval( $logConfig );
451
			}
452
		}
453
454
		return $destination;
455
	}
456
457
	/**
458
	* Log to a file without getting "file size exceeded" signals.
459
	*
460
	* Can also log to UDP with the syntax udp://host:port/prefix. This will send
461
	* lines to the specified port, prefixed by the specified prefix and a space.
462
	*
463
	* @param string $text
464
	* @param string $file Filename
465
	*/
466
	public static function emit( $text, $file ) {
467
		if ( substr( $file, 0, 4 ) == 'udp:' ) {
468
			$transport = UDPTransport::newFromString( $file );
469
			$transport->emit( $text );
470
		} else {
471
			\MediaWiki\suppressWarnings();
472
			$exists = file_exists( $file );
473
			$size = $exists ? filesize( $file ) : false;
474
			if ( !$exists ||
475
				( $size !== false && $size + strlen( $text ) < 0x7fffffff )
476
			) {
477
				file_put_contents( $file, $text, FILE_APPEND );
478
			}
479
			\MediaWiki\restoreWarnings();
480
		}
481
	}
482
483
}
484