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/api/ApiAuthManagerHelper.php (5 issues)

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
 * Copyright © 2016 Brad Jorsch <[email protected]>
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
 * @since 1.27
22
 */
23
24
use MediaWiki\Auth\AuthManager;
25
use MediaWiki\Auth\AuthenticationRequest;
26
use MediaWiki\Auth\AuthenticationResponse;
27
use MediaWiki\Auth\CreateFromLoginAuthenticationRequest;
28
use MediaWiki\Logger\LoggerFactory;
29
30
/**
31
 * Helper class for AuthManager-using API modules. Intended for use via
32
 * composition.
33
 *
34
 * @ingroup API
35
 */
36
class ApiAuthManagerHelper {
37
38
	/** @var ApiBase API module, for context and parameters */
39
	private $module;
40
41
	/** @var string Message output format */
42
	private $messageFormat;
43
44
	/**
45
	 * @param ApiBase $module API module, for context and parameters
46
	 */
47
	public function __construct( ApiBase $module ) {
48
		$this->module = $module;
49
50
		$params = $module->extractRequestParams();
51
		$this->messageFormat = isset( $params['messageformat'] ) ? $params['messageformat'] : 'wikitext';
52
	}
53
54
	/**
55
	 * Static version of the constructor, for chaining
56
	 * @param ApiBase $module API module, for context and parameters
57
	 * @return ApiAuthManagerHelper
58
	 */
59
	public static function newForModule( ApiBase $module ) {
60
		return new self( $module );
61
	}
62
63
	/**
64
	 * Format a message for output
65
	 * @param array &$res Result array
66
	 * @param string $key Result key
67
	 * @param Message $message
68
	 */
69
	private function formatMessage( array &$res, $key, Message $message ) {
70
		switch ( $this->messageFormat ) {
71
			case 'none':
72
				break;
73
74
			case 'wikitext':
75
				$res[$key] = $message->setContext( $this->module )->text();
76
				break;
77
78
			case 'html':
79
				$res[$key] = $message->setContext( $this->module )->parseAsBlock();
80
				$res[$key] = Parser::stripOuterParagraph( $res[$key] );
81
				break;
82
83
			case 'raw':
84
				$res[$key] = [
85
					'key' => $message->getKey(),
86
					'params' => $message->getParams(),
87
				];
88
				ApiResult::setIndexedTagName( $res[$key]['params'], 'param' );
89
				break;
90
		}
91
	}
92
93
	/**
94
	 * Call $manager->securitySensitiveOperationStatus()
95
	 * @param string $operation Operation being checked.
96
	 * @throws UsageException
97
	 */
98
	public function securitySensitiveOperation( $operation ) {
99
		$status = AuthManager::singleton()->securitySensitiveOperationStatus( $operation );
100
		switch ( $status ) {
101
			case AuthManager::SEC_OK:
102
				return;
103
104
			case AuthManager::SEC_REAUTH:
0 ignored issues
show
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
105
				$this->module->dieUsage(
106
					'You have not authenticated recently in this session, please reauthenticate.', 'reauthenticate'
107
				);
108
109
			case AuthManager::SEC_FAIL:
0 ignored issues
show
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
110
				$this->module->dieUsage(
111
					'This action is not available as your identify cannot be verified.', 'cannotreauthenticate'
112
				);
113
114
			default:
115
				throw new UnexpectedValueException( "Unknown status \"$status\"" );
116
		}
117
	}
118
119
	/**
120
	 * Filter out authentication requests by class name
121
	 * @param AuthenticationRequest[] $reqs Requests to filter
122
	 * @param string[] $blacklist Class names to remove
123
	 * @return AuthenticationRequest[]
124
	 */
125
	public static function blacklistAuthenticationRequests( array $reqs, array $blacklist ) {
126
		if ( $blacklist ) {
127
			$blacklist = array_flip( $blacklist );
128
			$reqs = array_filter( $reqs, function ( $req ) use ( $blacklist ) {
129
				return !isset( $blacklist[get_class( $req )] );
130
			} );
131
		}
132
		return $reqs;
133
	}
134
135
	/**
136
	 * Fetch and load the AuthenticationRequests for an action
137
	 * @param string $action One of the AuthManager::ACTION_* constants
138
	 * @return AuthenticationRequest[]
139
	 */
140
	public function loadAuthenticationRequests( $action ) {
141
		$params = $this->module->extractRequestParams();
142
143
		$manager = AuthManager::singleton();
144
		$reqs = $manager->getAuthenticationRequests( $action, $this->module->getUser() );
145
146
		// Filter requests, if requested to do so
147
		$wantedRequests = null;
148
		if ( isset( $params['requests'] ) ) {
149
			$wantedRequests = array_flip( $params['requests'] );
150
		} elseif ( isset( $params['request'] ) ) {
151
			$wantedRequests = [ $params['request'] => true ];
152
		}
153
		if ( $wantedRequests !== null ) {
154
			$reqs = array_filter( $reqs, function ( $req ) use ( $wantedRequests ) {
155
				return isset( $wantedRequests[$req->getUniqueId()] );
156
			} );
157
		}
158
159
		// Collect the fields for all the requests
160
		$fields = [];
161
		$sensitive = [];
162
		foreach ( $reqs as $req ) {
163
			$info = (array)$req->getFieldInfo();
164
			$fields += $info;
165
			$sensitive += array_filter( $info, function ( $opts ) {
166
				return !empty( $opts['sensitive'] );
167
			} );
168
		}
169
170
		// Extract the request data for the fields and mark those request
171
		// parameters as used
172
		$data = array_intersect_key( $this->module->getRequest()->getValues(), $fields );
173
		$this->module->getMain()->markParamsUsed( array_keys( $data ) );
174
175
		if ( $sensitive ) {
176
			$this->module->requirePostedParameters( array_keys( $sensitive ), 'noprefix' );
177
		}
178
179
		return AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
180
	}
181
182
	/**
183
	 * Format an AuthenticationResponse for return
184
	 * @param AuthenticationResponse $res
185
	 * @return array
186
	 */
187
	public function formatAuthenticationResponse( AuthenticationResponse $res ) {
188
		$ret = [
189
			'status' => $res->status,
190
		];
191
192
		if ( $res->status === AuthenticationResponse::PASS && $res->username !== null ) {
193
			$ret['username'] = $res->username;
194
		}
195
196
		if ( $res->status === AuthenticationResponse::REDIRECT ) {
197
			$ret['redirecttarget'] = $res->redirectTarget;
198
			if ( $res->redirectApiData !== null ) {
199
				$ret['redirectdata'] = $res->redirectApiData;
200
			}
201
		}
202
203
		if ( $res->status === AuthenticationResponse::REDIRECT ||
204
			$res->status === AuthenticationResponse::UI ||
205
			$res->status === AuthenticationResponse::RESTART
206
		) {
207
			$ret += $this->formatRequests( $res->neededRequests );
208
		}
209
210
		if ( $res->status === AuthenticationResponse::FAIL ||
211
			$res->status === AuthenticationResponse::UI ||
212
			$res->status === AuthenticationResponse::RESTART
213
		) {
214
			$this->formatMessage( $ret, 'message', $res->message );
0 ignored issues
show
It seems like $res->message can be null; however, formatMessage() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
215
		}
216
217
		if ( $res->status === AuthenticationResponse::FAIL ||
218
			$res->status === AuthenticationResponse::RESTART
219
		) {
220
			$this->module->getRequest()->getSession()->set(
221
				'ApiAuthManagerHelper::createRequest',
222
				$res->createRequest
223
			);
224
			$ret['canpreservestate'] = $res->createRequest !== null;
225
		} else {
226
			$this->module->getRequest()->getSession()->remove( 'ApiAuthManagerHelper::createRequest' );
227
		}
228
229
		return $ret;
230
	}
231
232
	/**
233
	 * Logs successful or failed authentication.
234
	 * @param string|AuthenticationResponse $result Response or error message
235
	 * @param string $event Event type (e.g. 'accountcreation')
236
	 */
237
	public function logAuthenticationResult( $event, $result ) {
238
		if ( is_string( $result ) ) {
239
			$status = Status::newFatal( $result );
240
		} elseif ( $result->status === AuthenticationResponse::PASS ) {
241
			$status = Status::newGood();
242
		} elseif ( $result->status === AuthenticationResponse::FAIL ) {
243
			$status = Status::newFatal( $result->message );
244
		} else {
245
			return;
246
		}
247
248
		$module = $this->module->getModuleName();
249
		LoggerFactory::getInstance( 'authevents' )->info( "$module API attempt", [
250
			'event' => $event,
251
			'status' => $status,
252
			'module' => $module,
253
		] );
254
	}
255
256
	/**
257
	 * Fetch the preserved CreateFromLoginAuthenticationRequest, if any
258
	 * @return CreateFromLoginAuthenticationRequest|null
259
	 */
260
	public function getPreservedRequest() {
261
		$ret = $this->module->getRequest()->getSession()->get( 'ApiAuthManagerHelper::createRequest' );
262
		return $ret instanceof CreateFromLoginAuthenticationRequest ? $ret : null;
263
	}
264
265
	/**
266
	 * Format an array of AuthenticationRequests for return
267
	 * @param AuthenticationRequest[] $reqs
268
	 * @return array Will have a 'requests' key, and also 'fields' if $module's
269
	 *  params include 'mergerequestfields'.
270
	 */
271
	public function formatRequests( array $reqs ) {
272
		$params = $this->module->extractRequestParams();
273
		$mergeFields = !empty( $params['mergerequestfields'] );
274
275
		$ret = [ 'requests' => [] ];
276
		foreach ( $reqs as $req ) {
277
			$describe = $req->describeCredentials();
278
			$reqInfo = [
279
				'id' => $req->getUniqueId(),
280
				'metadata' => $req->getMetadata() + [ ApiResult::META_TYPE => 'assoc' ],
281
			];
282
			switch ( $req->required ) {
283
				case AuthenticationRequest::OPTIONAL:
284
					$reqInfo['required'] = 'optional';
285
					break;
286
				case AuthenticationRequest::REQUIRED:
287
					$reqInfo['required'] = 'required';
288
					break;
289
				case AuthenticationRequest::PRIMARY_REQUIRED:
290
					$reqInfo['required'] = 'primary-required';
291
					break;
292
			}
293
			$this->formatMessage( $reqInfo, 'provider', $describe['provider'] );
294
			$this->formatMessage( $reqInfo, 'account', $describe['account'] );
295
			if ( !$mergeFields ) {
296
				$reqInfo['fields'] = $this->formatFields( (array)$req->getFieldInfo() );
297
			}
298
			$ret['requests'][] = $reqInfo;
299
		}
300
301
		if ( $mergeFields ) {
302
			$fields = AuthenticationRequest::mergeFieldInfo( $reqs );
303
			$ret['fields'] = $this->formatFields( $fields );
304
		}
305
306
		return $ret;
307
	}
308
309
	/**
310
	 * Clean up a field array for output
311
	 * @param ApiBase $module For context and parameters 'mergerequestfields'
0 ignored issues
show
There is no parameter named $module. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
312
	 *  and 'messageformat'
313
	 * @param array $fields
314
	 * @return array
315
	 */
316
	private function formatFields( array $fields ) {
317
		static $copy = [
318
			'type' => true,
319
			'value' => true,
320
		];
321
322
		$module = $this->module;
323
		$retFields = [];
324
325
		foreach ( $fields as $name => $field ) {
326
			$ret = array_intersect_key( $field, $copy );
327
328
			if ( isset( $field['options'] ) ) {
329
				$ret['options'] = array_map( function ( $msg ) use ( $module ) {
330
					return $msg->setContext( $module )->plain();
331
				}, $field['options'] );
332
				ApiResult::setArrayType( $ret['options'], 'assoc' );
333
			}
334
			$this->formatMessage( $ret, 'label', $field['label'] );
335
			$this->formatMessage( $ret, 'help', $field['help'] );
336
			$ret['optional'] = !empty( $field['optional'] );
337
			$ret['sensitive'] = !empty( $field['sensitive'] );
338
339
			$retFields[$name] = $ret;
340
		}
341
342
		ApiResult::setArrayType( $retFields, 'assoc' );
343
344
		return $retFields;
345
	}
346
347
	/**
348
	 * Fetch the standard parameters this helper recognizes
349
	 * @param string $action AuthManager action
350
	 * @param string $param... Parameters to use
0 ignored issues
show
There is no parameter named $param.... Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
351
	 * @return array
352
	 */
353
	public static function getStandardParams( $action, $param /* ... */ ) {
354
		$params = [
355
			'requests' => [
356
				ApiBase::PARAM_TYPE => 'string',
357
				ApiBase::PARAM_ISMULTI => true,
358
				ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-requests', $action ],
359
			],
360
			'request' => [
361
				ApiBase::PARAM_TYPE => 'string',
362
				ApiBase::PARAM_REQUIRED => true,
363
				ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-request', $action ],
364
			],
365
			'messageformat' => [
366
				ApiBase::PARAM_DFLT => 'wikitext',
367
				ApiBase::PARAM_TYPE => [ 'html', 'wikitext', 'raw', 'none' ],
368
				ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-messageformat',
369
			],
370
			'mergerequestfields' => [
371
				ApiBase::PARAM_DFLT => false,
372
				ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-mergerequestfields',
373
			],
374
			'preservestate' => [
375
				ApiBase::PARAM_DFLT => false,
376
				ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-preservestate',
377
			],
378
			'returnurl' => [
379
				ApiBase::PARAM_TYPE => 'string',
380
				ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-returnurl',
381
			],
382
			'continue' => [
383
				ApiBase::PARAM_DFLT => false,
384
				ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-continue',
385
			],
386
		];
387
388
		$ret = [];
389
		$wantedParams = func_get_args();
390
		array_shift( $wantedParams );
391
		foreach ( $wantedParams as $name ) {
392
			if ( isset( $params[$name] ) ) {
393
				$ret[$name] = $params[$name];
394
			}
395
		}
396
		return $ret;
397
	}
398
}
399