Debian Codegraph @

includes/auth/LocalPasswordPrimaryAuthenticationProvider.php

raw symbols SCIP
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 MediaWiki\Deferred\DeferredUpdates;
25 use MediaWiki\MainConfigNames;
26 use MediaWiki\Password\InvalidPassword;
27 use MediaWiki\User\UserRigorOptions;
28 use Wikimedia\Rdbms\DBAccessObjectUtils;
29 use Wikimedia\Rdbms\IConnectionProvider;
30 use Wikimedia\Rdbms\IDBAccessObject;
31
32 /**
33 * A primary authentication provider that uses the password field in the 'user' table.
34 * @ingroup Auth
35 * @since 1.27
36 */
37 class LocalPasswordPrimaryAuthenticationProvider
38 extends AbstractPasswordPrimaryAuthenticationProvider
39 {
40
41 /** @var bool If true, this instance is for legacy logins only. */
42 protected $loginOnly = false;
43
44 /** @var IConnectionProvider */
45 private $dbProvider;
46
47 /**
48 * @param IConnectionProvider $dbProvider
49 * @param array $params Settings
50 * - loginOnly: If true, the local passwords are for legacy logins only:
51 * the local password will be invalidated when authentication is changed
52 * and new users will not have a valid local password set.
53 */
54 public function __construct( IConnectionProvider $dbProvider, $params = [] ) {
55 parent::__construct( $params );
56 $this->loginOnly = !empty( $params['loginOnly'] );
57 $this->dbProvider = $dbProvider;
58 }
59
60 /**
61 * Check if the password has expired and needs a reset
62 *
63 * @param string $username
64 * @param \stdClass $row A row from the user table
65 * @return \stdClass|null
66 */
67 protected function getPasswordResetData( $username, $row ) {
68 $now = (int)wfTimestamp();
69 $expiration = wfTimestampOrNull( TS_UNIX, $row->user_password_expires );
70 if ( $expiration === null || (int)$expiration >= $now ) {
71 return null;
72 }
73
74 $grace = $this->config->get( MainConfigNames::PasswordExpireGrace );
75 if ( (int)$expiration + $grace < $now ) {
76 $data = [
77 'hard' => true,
78 'msg' => \MediaWiki\Status\Status::newFatal( 'resetpass-expired' )->getMessage(),
79 ];
80 } else {
81 $data = [
82 'hard' => false,
83 'msg' => \MediaWiki\Status\Status::newFatal( 'resetpass-expired-soft' )->getMessage(),
84 ];
85 }
86
87 return (object)$data;
88 }
89
90 public function beginPrimaryAuthentication( array $reqs ) {
91 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
92 if ( !$req || $req->username === null || $req->password === null ) {
93 return AuthenticationResponse::newAbstain();
94 }
95
96 $username = $this->userNameUtils->getCanonical(
97 $req->username, UserRigorOptions::RIGOR_USABLE );
98 if ( $username === false ) {
99 return AuthenticationResponse::newAbstain();
100 }
101
102 $row = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
103 ->select( [ 'user_id', 'user_password', 'user_password_expires' ] )
104 ->from( 'user' )
105 ->where( [ 'user_name' => $username ] )
106 ->caller( __METHOD__ )->fetchRow();
107 if ( !$row ) {
108 // Do not reveal whether its bad username or
109 // bad password to prevent username enumeration
110 // on private wikis. (T134100)
111 return $this->failResponse( $req );
112 }
113
114 $oldRow = clone $row;
115 // Check for *really* old password hashes that don't even have a type
116 // The old hash format was just an md5 hex hash, with no type information
117 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
118 $row->user_password = ":B:{$row->user_id}:{$row->user_password}";
119 }
120
121 $status = $this->checkPasswordValidity( $username, $req->password );
122 if ( !$status->isOK() ) {
123 return $this->getFatalPasswordErrorResponse( $username, $status );
124 }
125
126 $pwhash = $this->getPassword( $row->user_password );
127 if ( !$pwhash->verify( $req->password ) ) {
128 if ( $this->config->get( MainConfigNames::LegacyEncoding ) ) {
129 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
130 // Check for this with iconv
131 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $req->password );
132 if ( $cp1252Password === $req->password || !$pwhash->verify( $cp1252Password ) ) {
133 return $this->failResponse( $req );
134 }
135 } else {
136 return $this->failResponse( $req );
137 }
138 }
139
140 // @codeCoverageIgnoreStart
141 if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
142 $newHash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
143 DeferredUpdates::addCallableUpdate( function ( $fname ) use ( $newHash, $oldRow ) {
144 $dbw = $this->dbProvider->getPrimaryDatabase();
145 $dbw->newUpdateQueryBuilder()
146 ->update( 'user' )
147 ->set( [ 'user_password' => $newHash->toString() ] )
148 ->where( [
149 'user_id' => $oldRow->user_id,
150 'user_password' => $oldRow->user_password,
151 ] )
152 ->caller( $fname )
153 ->execute();
154 } );
155 }
156 // @codeCoverageIgnoreEnd
157
158 $this->setPasswordResetFlag( $username, $status, $row );
159
160 return AuthenticationResponse::newPass( $username );
161 }
162
163 public function testUserCanAuthenticate( $username ) {
164 $username = $this->userNameUtils->getCanonical(
165 $username, UserRigorOptions::RIGOR_USABLE );
166 if ( $username === false ) {
167 return false;
168 }
169
170 $row = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
171 ->select( [ 'user_password' ] )
172 ->from( 'user' )
173 ->where( [ 'user_name' => $username ] )
174 ->caller( __METHOD__ )->fetchRow();
175 if ( !$row ) {
176 return false;
177 }
178
179 // Check for *really* old password hashes that don't even have a type
180 // The old hash format was just an md5 hex hash, with no type information
181 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
182 return true;
183 }
184
185 return !$this->getPassword( $row->user_password ) instanceof InvalidPassword;
186 }
187
188 public function testUserExists( $username, $flags = IDBAccessObject::READ_NORMAL ) {
189 $username = $this->userNameUtils->getCanonical(
190 $username, UserRigorOptions::RIGOR_USABLE );
191 if ( $username === false ) {
192 return false;
193 }
194
195 $db = DBAccessObjectUtils::getDBFromRecency( $this->dbProvider, $flags );
196 return (bool)$db->newSelectQueryBuilder()
197 ->select( [ 'user_id' ] )
198 ->from( 'user' )
199 ->where( [ 'user_name' => $username ] )
200 ->recency( $flags )
201 ->caller( __METHOD__ )->fetchField();
202 }
203
204 public function providerAllowsAuthenticationDataChange(
205 AuthenticationRequest $req, $checkData = true
206 ) {
207 // We only want to blank the password if something else will accept the
208 // new authentication data, so return 'ignore' here.
209 if ( $this->loginOnly ) {
210 return \StatusValue::newGood( 'ignored' );
211 }
212
213 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
214 if ( !$checkData ) {
215 return \StatusValue::newGood();
216 }
217
218 $username = $this->userNameUtils->getCanonical( $req->username,
219 UserRigorOptions::RIGOR_USABLE );
220 if ( $username !== false ) {
221 $row = $this->dbProvider->getPrimaryDatabase()->newSelectQueryBuilder()
222 ->select( [ 'user_id' ] )
223 ->from( 'user' )
224 ->where( [ 'user_name' => $username ] )
225 ->caller( __METHOD__ )->fetchRow();
226 if ( $row ) {
227 $sv = \StatusValue::newGood();
228 if ( $req->password !== null ) {
229 if ( $req->password !== $req->retype ) {
230 $sv->fatal( 'badretype' );
231 } else {
232 $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
233 }
234 }
235 return $sv;
236 }
237 }
238 }
239
240 return \StatusValue::newGood( 'ignored' );
241 }
242
243 public function providerChangeAuthenticationData( AuthenticationRequest $req ) {
244 $username = $req->username !== null ?
245 $this->userNameUtils->getCanonical( $req->username, UserRigorOptions::RIGOR_USABLE )
246 : false;
247 if ( $username === false ) {
248 return;
249 }
250
251 $pwhash = null;
252
253 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
254 if ( $this->loginOnly ) {
255 $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
256 $expiry = null;
257 } else {
258 $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
259 $expiry = $this->getNewPasswordExpiry( $username );
260 }
261 }
262
263 if ( $pwhash ) {
264 $dbw = $this->dbProvider->getPrimaryDatabase();
265 $dbw->newUpdateQueryBuilder()
266 ->update( 'user' )
267 ->set( [
268 'user_password' => $pwhash->toString(),
269 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable expiry is set together with pwhash
270 'user_password_expires' => $dbw->timestampOrNull( $expiry ),
271 ] )
272 ->where( [ 'user_name' => $username ] )
273 ->caller( __METHOD__ )->execute();
274 }
275 }
276
277 public function accountCreationType() {
278 return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
279 }
280
281 public function testForAccountCreation( $user, $creator, array $reqs ) {
282 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
283
284 $ret = \StatusValue::newGood();
285 if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
286 if ( $req->password !== $req->retype ) {
287 $ret->fatal( 'badretype' );
288 } else {
289 $ret->merge(
290 $this->checkPasswordValidity( $user->getName(), $req->password )
291 );
292 }
293 }
294 return $ret;
295 }
296
297 public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
298 if ( $this->accountCreationType() === self::TYPE_NONE ) {
299 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
300 }
301
302 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
303 if ( $req && $req->username !== null && $req->password !== null ) {
304 // Nothing we can do besides claim it, because the user isn't in
305 // the DB yet
306 if ( $req->username !== $user->getName() ) {
307 $req = clone $req;
308 $req->username = $user->getName();
309 }
310 $ret = AuthenticationResponse::newPass( $req->username );
311 $ret->createRequest = $req;
312 return $ret;
313 }
314 return AuthenticationResponse::newAbstain();
315 }
316
317 public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
318 if ( $this->accountCreationType() === self::TYPE_NONE ) {
319 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
320 }
321
322 // Now that the user is in the DB, set the password on it.
323 $this->providerChangeAuthenticationData( $res->createRequest );
324
325 return null;
326 }
327 }