Completed
Branch master (1b8556)
by
unknown
26:56
created

getPasswordResetData()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
eloc 15
c 1
b 0
f 1
nc 3
nop 2
dl 0
loc 22
rs 8.9197
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
Coding Style introduced by
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
Bug introduced by
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
		$dbw = wfGetDB( DB_MASTER );
92
		$row = $dbw->selectRow(
93
			'user',
94
			$fields,
95
			[ 'user_name' => $username ],
96
			__METHOD__
97
		);
98
		if ( !$row ) {
99
			return AuthenticationResponse::newAbstain();
100
		}
101
102
		// Check for *really* old password hashes that don't even have a type
103
		// The old hash format was just an md5 hex hash, with no type information
104
		if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
105
			if ( $this->config->get( 'PasswordSalt' ) ) {
106
				$row->user_password = ":A:{$row->user_id}:{$row->user_password}";
107
			} else {
108
				$row->user_password = ":A:{$row->user_password}";
109
			}
110
		}
111
112
		$status = $this->checkPasswordValidity( $username, $req->password );
0 ignored issues
show
Bug introduced by
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...
113
		if ( !$status->isOk() ) {
114
			// Fatal, can't log in
115
			return AuthenticationResponse::newFail( $status->getMessage() );
116
		}
117
118
		$pwhash = $this->getPassword( $row->user_password );
119
		if ( !$pwhash->equals( $req->password ) ) {
120
			if ( $this->config->get( 'LegacyEncoding' ) ) {
121
				// Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
122
				// Check for this with iconv
123
				$cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $req->password );
124
				if ( $cp1252Password === $req->password || !$pwhash->equals( $cp1252Password ) ) {
125
					return $this->failResponse( $req );
0 ignored issues
show
Compatibility introduced by
$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...
126
				}
127
			} else {
128
				return $this->failResponse( $req );
0 ignored issues
show
Compatibility introduced by
$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...
129
			}
130
		}
131
132
		// @codeCoverageIgnoreStart
133
		if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
134
			$pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
135
			$dbw->update(
136
				'user',
137
				[ 'user_password' => $pwhash->toString() ],
138
				[ 'user_id' => $row->user_id ],
139
				__METHOD__
140
			);
141
		}
142
		// @codeCoverageIgnoreEnd
143
144
		$this->setPasswordResetFlag( $username, $status, $row );
0 ignored issues
show
Bug introduced by
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...
145
146
		return AuthenticationResponse::newPass( $username );
0 ignored issues
show
Bug introduced by
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...
147
	}
148
149
	public function testUserCanAuthenticate( $username ) {
150
		$username = User::getCanonicalName( $username, 'usable' );
151
		if ( $username === false ) {
152
			return false;
153
		}
154
155
		$dbw = wfGetDB( DB_MASTER );
156
		$row = $dbw->selectRow(
157
			'user',
158
			[ 'user_password' ],
159
			[ 'user_name' => $username ],
160
			__METHOD__
161
		);
162
		if ( !$row ) {
163
			return false;
164
		}
165
166
		// Check for *really* old password hashes that don't even have a type
167
		// The old hash format was just an md5 hex hash, with no type information
168
		if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
169
			return true;
170
		}
171
172
		return !$this->getPassword( $row->user_password ) instanceof \InvalidPassword;
173
	}
174
175 View Code Duplication
	public function testUserExists( $username, $flags = User::READ_NORMAL ) {
176
		$username = User::getCanonicalName( $username, 'usable' );
177
		if ( $username === false ) {
178
			return false;
179
		}
180
181
		list( $db, $options ) = \DBAccessObjectUtils::getDBOptions( $flags );
182
		return (bool)wfGetDB( $db )->selectField(
183
			[ 'user' ],
184
			[ 'user_id' ],
185
			[ 'user_name' => $username ],
186
			__METHOD__,
187
			$options
188
		);
189
	}
190
191
	public function providerAllowsAuthenticationDataChange(
192
		AuthenticationRequest $req, $checkData = true
193
	) {
194
		// We only want to blank the password if something else will accept the
195
		// new authentication data, so return 'ignore' here.
196
		if ( $this->loginOnly ) {
197
			return \StatusValue::newGood( 'ignored' );
198
		}
199
200
		if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
201
			if ( !$checkData ) {
202
				return \StatusValue::newGood();
203
			}
204
205
			$username = User::getCanonicalName( $req->username, 'usable' );
206
			if ( $username !== false ) {
207
				$row = wfGetDB( DB_MASTER )->selectRow(
208
					'user',
209
					[ 'user_id' ],
210
					[ 'user_name' => $username ],
211
					__METHOD__
212
				);
213
				if ( $row ) {
214
					$sv = \StatusValue::newGood();
215 View Code Duplication
					if ( $req->password !== null ) {
216
						if ( $req->password !== $req->retype ) {
0 ignored issues
show
Bug introduced by
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...
217
							$sv->fatal( 'badretype' );
218
						} else {
219
							$sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
0 ignored issues
show
Bug introduced by
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...
Bug introduced by
It seems like $username defined by \User::getCanonicalName($req->username, 'usable') on line 205 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...
220
						}
221
					}
222
					return $sv;
223
				}
224
			}
225
		}
226
227
		return \StatusValue::newGood( 'ignored' );
228
	}
229
230
	public function providerChangeAuthenticationData( AuthenticationRequest $req ) {
231
		$username = $req->username !== null ? User::getCanonicalName( $req->username, 'usable' ) : false;
232
		if ( $username === false ) {
233
			return;
234
		}
235
236
		$pwhash = null;
237
238
		if ( $this->loginOnly ) {
239
			$pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
240
			$expiry = null;
241
			// @codeCoverageIgnoreStart
242
		} elseif ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
243
			// @codeCoverageIgnoreEnd
244
			$pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
0 ignored issues
show
Bug introduced by
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...
245
			$expiry = $this->getNewPasswordExpiry( $username );
0 ignored issues
show
Bug introduced by
It seems like $username defined by $req->username !== null ...name, 'usable') : false on line 231 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...
246
		}
247
248
		if ( $pwhash ) {
249
			$dbw = wfGetDB( DB_MASTER );
250
			$dbw->update(
251
				'user',
252
				[
253
					'user_password' => $pwhash->toString(),
254
					'user_password_expires' => $dbw->timestampOrNull( $expiry ),
0 ignored issues
show
Bug introduced by
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...
255
				],
256
				[ 'user_name' => $username ],
257
				__METHOD__
258
			);
259
		}
260
	}
261
262
	public function accountCreationType() {
263
		return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
264
	}
265
266
	public function testForAccountCreation( $user, $creator, array $reqs ) {
267
		$req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
268
269
		$ret = \StatusValue::newGood();
270
		if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
271 View Code Duplication
			if ( $req->password !== $req->retype ) {
0 ignored issues
show
Bug introduced by
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...
272
				$ret->fatal( 'badretype' );
273
			} else {
274
				$ret->merge(
275
					$this->checkPasswordValidity( $user->getName(), $req->password )
0 ignored issues
show
Bug introduced by
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...
276
				);
277
			}
278
		}
279
		return $ret;
280
	}
281
282
	public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
283
		if ( $this->accountCreationType() === self::TYPE_NONE ) {
284
			throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
285
		}
286
287
		$req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
288 View Code Duplication
		if ( $req ) {
289
			if ( $req->username !== null && $req->password !== null ) {
0 ignored issues
show
Bug introduced by
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...
290
				// Nothing we can do besides claim it, because the user isn't in
291
				// the DB yet
292
				if ( $req->username !== $user->getName() ) {
293
					$req = clone( $req );
294
					$req->username = $user->getName();
295
				}
296
				$ret = AuthenticationResponse::newPass( $req->username );
297
				$ret->createRequest = $req;
298
				return $ret;
299
			}
300
		}
301
		return AuthenticationResponse::newAbstain();
302
	}
303
304
	public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
305
		if ( $this->accountCreationType() === self::TYPE_NONE ) {
306
			throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
307
		}
308
309
		// Now that the user is in the DB, set the password on it.
310
		$this->providerChangeAuthenticationData( $res->createRequest );
0 ignored issues
show
Bug introduced by
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...
311
312
		return null;
313
	}
314
}
315