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.

LocalPasswordPrimaryAuthenticationProvider.php (17 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
 * 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
 * @ingroup Auth
20
 */
21
22
namespace MediaWiki\Auth;
23
24
use User;
25
26
/**
27
 * A primary authentication provider that uses the password field in the 'user' table.
28
 * @ingroup Auth
29
 * @since 1.27
30
 */
31
class LocalPasswordPrimaryAuthenticationProvider
32
	extends AbstractPasswordPrimaryAuthenticationProvider
0 ignored issues
show
The extends keyword must be on the same line as the class name
Loading history...
33
{
34
35
	/** @var bool If true, this instance is for legacy logins only. */
36
	protected $loginOnly = false;
37
38
	/**
39
	 * @param array $params Settings
40
	 *  - loginOnly: If true, the local passwords are for legacy logins only:
41
	 *    the local password will be invalidated when authentication is changed
42
	 *    and new users will not have a valid local password set.
43
	 */
44
	public function __construct( $params = [] ) {
45
		parent::__construct( $params );
46
		$this->loginOnly = !empty( $params['loginOnly'] );
47
	}
48
49
	protected function getPasswordResetData( $username, $row ) {
50
		$now = wfTimestamp();
51
		$expiration = wfTimestampOrNull( TS_UNIX, $row->user_password_expires );
52
		if ( $expiration === null || $expiration >= $now ) {
53
			return null;
54
		}
55
56
		$grace = $this->config->get( 'PasswordExpireGrace' );
57
		if ( $expiration + $grace < $now ) {
58
			$data = [
59
				'hard' => true,
60
				'msg' => \Status::newFatal( 'resetpass-expired' )->getMessage(),
61
			];
62
		} else {
63
			$data = [
64
				'hard' => false,
65
				'msg' => \Status::newFatal( 'resetpass-expired-soft' )->getMessage(),
66
			];
67
		}
68
69
		return (object)$data;
70
	}
71
72
	public function beginPrimaryAuthentication( array $reqs ) {
73
		$req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
74
		if ( !$req ) {
75
			return AuthenticationResponse::newAbstain();
76
		}
77
78
		if ( $req->username === null || $req->password === null ) {
0 ignored issues
show
The property password does not seem to exist in MediaWiki\Auth\AuthenticationRequest.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
79
			return AuthenticationResponse::newAbstain();
80
		}
81
82
		$username = User::getCanonicalName( $req->username, 'usable' );
83
		if ( $username === false ) {
84
			return AuthenticationResponse::newAbstain();
85
		}
86
87
		$fields = [
88
			'user_id', 'user_password', 'user_password_expires',
89
		];
90
91
		$dbr = wfGetDB( DB_REPLICA );
92
		$row = $dbr->selectRow(
93
			'user',
94
			$fields,
95
			[ 'user_name' => $username ],
96
			__METHOD__
97
		);
98
		if ( !$row ) {
99
			return AuthenticationResponse::newAbstain();
100
		}
101
102
		$oldRow = clone $row;
103
		// Check for *really* old password hashes that don't even have a type
104
		// The old hash format was just an md5 hex hash, with no type information
105
		if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
106
			if ( $this->config->get( 'PasswordSalt' ) ) {
107
				$row->user_password = ":A:{$row->user_id}:{$row->user_password}";
108
			} else {
109
				$row->user_password = ":A:{$row->user_password}";
110
			}
111
		}
112
113
		$status = $this->checkPasswordValidity( $username, $req->password );
0 ignored issues
show
It seems like $username defined by \User::getCanonicalName($req->username, 'usable') on line 82 can also be of type boolean; however, MediaWiki\Auth\AbstractP...checkPasswordValidity() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
114
		if ( !$status->isOK() ) {
115
			// Fatal, can't log in
116
			return AuthenticationResponse::newFail( $status->getMessage() );
117
		}
118
119
		$pwhash = $this->getPassword( $row->user_password );
120
		if ( !$pwhash->equals( $req->password ) ) {
121
			if ( $this->config->get( 'LegacyEncoding' ) ) {
122
				// Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
123
				// Check for this with iconv
124
				$cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $req->password );
125
				if ( $cp1252Password === $req->password || !$pwhash->equals( $cp1252Password ) ) {
126
					return $this->failResponse( $req );
0 ignored issues
show
$req of type object<MediaWiki\Auth\AuthenticationRequest> is not a sub-type of object<MediaWiki\Auth\Pa...dAuthenticationRequest>. It seems like you assume a child class of the class MediaWiki\Auth\AuthenticationRequest to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
127
				}
128
			} else {
129
				return $this->failResponse( $req );
0 ignored issues
show
$req of type object<MediaWiki\Auth\AuthenticationRequest> is not a sub-type of object<MediaWiki\Auth\Pa...dAuthenticationRequest>. It seems like you assume a child class of the class MediaWiki\Auth\AuthenticationRequest to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
130
			}
131
		}
132
133
		// @codeCoverageIgnoreStart
134
		if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
135
			$pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
136
			\DeferredUpdates::addCallableUpdate( function () use ( $pwhash, $oldRow ) {
137
				$dbw = wfGetDB( DB_MASTER );
138
				$dbw->update(
139
					'user',
140
					[ 'user_password' => $pwhash->toString() ],
141
					[
142
						'user_id' => $oldRow->user_id,
143
						'user_password' => $oldRow->user_password
144
					],
145
					__METHOD__
146
				);
147
			} );
148
		}
149
		// @codeCoverageIgnoreEnd
150
151
		$this->setPasswordResetFlag( $username, $status, $row );
0 ignored issues
show
It seems like $username defined by \User::getCanonicalName($req->username, 'usable') on line 82 can also be of type boolean; however, MediaWiki\Auth\AbstractP...:setPasswordResetFlag() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
152
153
		return AuthenticationResponse::newPass( $username );
0 ignored issues
show
It seems like $username defined by \User::getCanonicalName($req->username, 'usable') on line 82 can also be of type boolean; however, MediaWiki\Auth\AuthenticationResponse::newPass() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
154
	}
155
156
	public function testUserCanAuthenticate( $username ) {
157
		$username = User::getCanonicalName( $username, 'usable' );
158
		if ( $username === false ) {
159
			return false;
160
		}
161
162
		$dbr = wfGetDB( DB_REPLICA );
163
		$row = $dbr->selectRow(
164
			'user',
165
			[ 'user_password' ],
166
			[ 'user_name' => $username ],
167
			__METHOD__
168
		);
169
		if ( !$row ) {
170
			return false;
171
		}
172
173
		// Check for *really* old password hashes that don't even have a type
174
		// The old hash format was just an md5 hex hash, with no type information
175
		if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
176
			return true;
177
		}
178
179
		return !$this->getPassword( $row->user_password ) instanceof \InvalidPassword;
180
	}
181
182 View Code Duplication
	public function testUserExists( $username, $flags = User::READ_NORMAL ) {
183
		$username = User::getCanonicalName( $username, 'usable' );
184
		if ( $username === false ) {
185
			return false;
186
		}
187
188
		list( $db, $options ) = \DBAccessObjectUtils::getDBOptions( $flags );
189
		return (bool)wfGetDB( $db )->selectField(
190
			[ 'user' ],
191
			[ 'user_id' ],
192
			[ 'user_name' => $username ],
193
			__METHOD__,
194
			$options
195
		);
196
	}
197
198
	public function providerAllowsAuthenticationDataChange(
199
		AuthenticationRequest $req, $checkData = true
200
	) {
201
		// We only want to blank the password if something else will accept the
202
		// new authentication data, so return 'ignore' here.
203
		if ( $this->loginOnly ) {
204
			return \StatusValue::newGood( 'ignored' );
205
		}
206
207
		if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
208
			if ( !$checkData ) {
209
				return \StatusValue::newGood();
210
			}
211
212
			$username = User::getCanonicalName( $req->username, 'usable' );
213
			if ( $username !== false ) {
214
				$row = wfGetDB( DB_MASTER )->selectRow(
215
					'user',
216
					[ 'user_id' ],
217
					[ 'user_name' => $username ],
218
					__METHOD__
219
				);
220
				if ( $row ) {
221
					$sv = \StatusValue::newGood();
222 View Code Duplication
					if ( $req->password !== null ) {
223
						if ( $req->password !== $req->retype ) {
0 ignored issues
show
The property retype does not seem to exist in MediaWiki\Auth\AuthenticationRequest.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
224
							$sv->fatal( 'badretype' );
225
						} else {
226
							$sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
0 ignored issues
show
The property password does not seem to exist in MediaWiki\Auth\AuthenticationRequest.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
It seems like $username defined by \User::getCanonicalName($req->username, 'usable') on line 212 can also be of type boolean; however, MediaWiki\Auth\AbstractP...checkPasswordValidity() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
227
						}
228
					}
229
					return $sv;
230
				}
231
			}
232
		}
233
234
		return \StatusValue::newGood( 'ignored' );
235
	}
236
237
	public function providerChangeAuthenticationData( AuthenticationRequest $req ) {
238
		$username = $req->username !== null ? User::getCanonicalName( $req->username, 'usable' ) : false;
239
		if ( $username === false ) {
240
			return;
241
		}
242
243
		$pwhash = null;
244
245
		if ( $this->loginOnly ) {
246
			$pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
247
			$expiry = null;
248
			// @codeCoverageIgnoreStart
249
		} elseif ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
250
			// @codeCoverageIgnoreEnd
251
			$pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
0 ignored issues
show
The property password does not seem to exist in MediaWiki\Auth\AuthenticationRequest.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
252
			$expiry = $this->getNewPasswordExpiry( $username );
0 ignored issues
show
It seems like $username defined by $req->username !== null ...name, 'usable') : false on line 238 can also be of type boolean; however, MediaWiki\Auth\AbstractP...:getNewPasswordExpiry() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
253
		}
254
255
		if ( $pwhash ) {
256
			$dbw = wfGetDB( DB_MASTER );
257
			$dbw->update(
258
				'user',
259
				[
260
					'user_password' => $pwhash->toString(),
261
					'user_password_expires' => $dbw->timestampOrNull( $expiry ),
0 ignored issues
show
The variable $expiry does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
262
				],
263
				[ 'user_name' => $username ],
264
				__METHOD__
265
			);
266
		}
267
	}
268
269
	public function accountCreationType() {
270
		return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
271
	}
272
273
	public function testForAccountCreation( $user, $creator, array $reqs ) {
274
		$req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
275
276
		$ret = \StatusValue::newGood();
277
		if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
278 View Code Duplication
			if ( $req->password !== $req->retype ) {
0 ignored issues
show
The property retype does not seem to exist in MediaWiki\Auth\AuthenticationRequest.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
279
				$ret->fatal( 'badretype' );
280
			} else {
281
				$ret->merge(
282
					$this->checkPasswordValidity( $user->getName(), $req->password )
0 ignored issues
show
The property password does not seem to exist in MediaWiki\Auth\AuthenticationRequest.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
283
				);
284
			}
285
		}
286
		return $ret;
287
	}
288
289
	public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
290
		if ( $this->accountCreationType() === self::TYPE_NONE ) {
291
			throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
292
		}
293
294
		$req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
295 View Code Duplication
		if ( $req ) {
296
			if ( $req->username !== null && $req->password !== null ) {
0 ignored issues
show
The property password does not seem to exist in MediaWiki\Auth\AuthenticationRequest.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
297
				// Nothing we can do besides claim it, because the user isn't in
298
				// the DB yet
299
				if ( $req->username !== $user->getName() ) {
300
					$req = clone( $req );
301
					$req->username = $user->getName();
302
				}
303
				$ret = AuthenticationResponse::newPass( $req->username );
304
				$ret->createRequest = $req;
305
				return $ret;
306
			}
307
		}
308
		return AuthenticationResponse::newAbstain();
309
	}
310
311
	public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
312
		if ( $this->accountCreationType() === self::TYPE_NONE ) {
313
			throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
314
		}
315
316
		// Now that the user is in the DB, set the password on it.
317
		$this->providerChangeAuthenticationData( $res->createRequest );
0 ignored issues
show
It seems like $res->createRequest can be null; however, providerChangeAuthenticationData() 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...
318
319
		return null;
320
	}
321
}
322