Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / auth / LocalPasswordPrimaryAuthenticationProvider.php
blobc37313376a44fb64682d7c120a5e3bce9148892d
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.
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.
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
18 * @file
19 * @ingroup Auth
22 namespace MediaWiki\Auth;
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;
32 /**
33 * A primary authentication provider that uses the password field in the 'user' table.
34 * @ingroup Auth
35 * @since 1.27
37 class LocalPasswordPrimaryAuthenticationProvider
38 extends AbstractPasswordPrimaryAuthenticationProvider
41 /** @var bool If true, this instance is for legacy logins only. */
42 protected $loginOnly = false;
44 private IConnectionProvider $dbProvider;
46 /**
47 * @param IConnectionProvider $dbProvider
48 * @param array $params Settings
49 * - loginOnly: If true, the local passwords are for legacy logins only:
50 * the local password will be invalidated when authentication is changed
51 * and new users will not have a valid local password set.
53 public function __construct( IConnectionProvider $dbProvider, $params = [] ) {
54 parent::__construct( $params );
55 $this->loginOnly = !empty( $params['loginOnly'] );
56 $this->dbProvider = $dbProvider;
59 /**
60 * Check if the password has expired and needs a reset
62 * @param string $username
63 * @param \stdClass $row A row from the user table
64 * @return \stdClass|null
66 protected function getPasswordResetData( $username, $row ) {
67 $now = (int)wfTimestamp();
68 $expiration = wfTimestampOrNull( TS_UNIX, $row->user_password_expires );
69 if ( $expiration === null || (int)$expiration >= $now ) {
70 return null;
73 $grace = $this->config->get( MainConfigNames::PasswordExpireGrace );
74 if ( (int)$expiration + $grace < $now ) {
75 $data = [
76 'hard' => true,
77 'msg' => \MediaWiki\Status\Status::newFatal( 'resetpass-expired' )->getMessage(),
79 } else {
80 $data = [
81 'hard' => false,
82 'msg' => \MediaWiki\Status\Status::newFatal( 'resetpass-expired-soft' )->getMessage(),
86 return (object)$data;
89 public function beginPrimaryAuthentication( array $reqs ) {
90 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
91 if ( !$req || $req->username === null || $req->password === null ) {
92 return AuthenticationResponse::newAbstain();
95 $username = $this->userNameUtils->getCanonical(
96 $req->username, UserRigorOptions::RIGOR_USABLE );
97 if ( $username === false ) {
98 return AuthenticationResponse::newAbstain();
101 $row = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
102 ->select( [ 'user_id', 'user_password', 'user_password_expires' ] )
103 ->from( 'user' )
104 ->where( [ 'user_name' => $username ] )
105 ->caller( __METHOD__ )->fetchRow();
106 if ( !$row ) {
107 // Do not reveal whether its bad username or
108 // bad password to prevent username enumeration
109 // on private wikis. (T134100)
110 return $this->failResponse( $req );
113 $oldRow = clone $row;
114 // Check for *really* old password hashes that don't even have a type
115 // The old hash format was just an md5 hex hash, with no type information
116 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
117 $row->user_password = ":B:{$row->user_id}:{$row->user_password}";
120 $status = $this->checkPasswordValidity( $username, $req->password );
121 if ( !$status->isOK() ) {
122 return $this->getFatalPasswordErrorResponse( $username, $status );
125 $pwhash = $this->getPassword( $row->user_password );
126 if ( !$pwhash->verify( $req->password ) ) {
127 if ( $this->config->get( MainConfigNames::LegacyEncoding ) ) {
128 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
129 // Check for this with iconv
130 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $req->password );
131 if ( $cp1252Password === $req->password || !$pwhash->verify( $cp1252Password ) ) {
132 return $this->failResponse( $req );
134 } else {
135 return $this->failResponse( $req );
139 // @codeCoverageIgnoreStart
140 if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
141 $newHash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
142 DeferredUpdates::addCallableUpdate( function ( $fname ) use ( $newHash, $oldRow ) {
143 $dbw = $this->dbProvider->getPrimaryDatabase();
144 $dbw->newUpdateQueryBuilder()
145 ->update( 'user' )
146 ->set( [ 'user_password' => $newHash->toString() ] )
147 ->where( [
148 'user_id' => $oldRow->user_id,
149 'user_password' => $oldRow->user_password,
151 ->caller( $fname )
152 ->execute();
153 } );
155 // @codeCoverageIgnoreEnd
157 $this->setPasswordResetFlag( $username, $status, $row );
159 return AuthenticationResponse::newPass( $username );
162 public function testUserCanAuthenticate( $username ) {
163 $username = $this->userNameUtils->getCanonical(
164 $username, UserRigorOptions::RIGOR_USABLE );
165 if ( $username === false ) {
166 return false;
169 $row = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
170 ->select( [ 'user_password' ] )
171 ->from( 'user' )
172 ->where( [ 'user_name' => $username ] )
173 ->caller( __METHOD__ )->fetchRow();
174 if ( !$row ) {
175 return false;
178 // Check for *really* old password hashes that don't even have a type
179 // The old hash format was just an md5 hex hash, with no type information
180 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
181 return true;
184 return !$this->getPassword( $row->user_password ) instanceof InvalidPassword;
187 public function testUserExists( $username, $flags = IDBAccessObject::READ_NORMAL ) {
188 $username = $this->userNameUtils->getCanonical(
189 $username, UserRigorOptions::RIGOR_USABLE );
190 if ( $username === false ) {
191 return false;
194 $db = DBAccessObjectUtils::getDBFromRecency( $this->dbProvider, $flags );
195 return (bool)$db->newSelectQueryBuilder()
196 ->select( [ 'user_id' ] )
197 ->from( 'user' )
198 ->where( [ 'user_name' => $username ] )
199 ->caller( __METHOD__ )->fetchField();
202 public function providerAllowsAuthenticationDataChange(
203 AuthenticationRequest $req, $checkData = true
205 // We only want to blank the password if something else will accept the
206 // new authentication data, so return 'ignore' here.
207 if ( $this->loginOnly ) {
208 return \StatusValue::newGood( 'ignored' );
211 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
212 if ( !$checkData ) {
213 return \StatusValue::newGood();
216 $username = $this->userNameUtils->getCanonical( $req->username,
217 UserRigorOptions::RIGOR_USABLE );
218 if ( $username !== false ) {
219 $row = $this->dbProvider->getPrimaryDatabase()->newSelectQueryBuilder()
220 ->select( [ 'user_id' ] )
221 ->from( 'user' )
222 ->where( [ 'user_name' => $username ] )
223 ->caller( __METHOD__ )->fetchRow();
224 if ( $row ) {
225 $sv = \StatusValue::newGood();
226 if ( $req->password !== null ) {
227 if ( $req->password !== $req->retype ) {
228 $sv->fatal( 'badretype' );
229 } else {
230 $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
233 return $sv;
238 return \StatusValue::newGood( 'ignored' );
241 public function providerChangeAuthenticationData( AuthenticationRequest $req ) {
242 $username = $req->username !== null ?
243 $this->userNameUtils->getCanonical( $req->username, UserRigorOptions::RIGOR_USABLE )
244 : false;
245 if ( $username === false ) {
246 return;
249 $pwhash = null;
251 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
252 if ( $this->loginOnly ) {
253 $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
254 $expiry = null;
255 } else {
256 $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
257 $expiry = $this->getNewPasswordExpiry( $username );
261 if ( $pwhash ) {
262 $dbw = $this->dbProvider->getPrimaryDatabase();
263 $dbw->newUpdateQueryBuilder()
264 ->update( 'user' )
265 ->set( [
266 'user_password' => $pwhash->toString(),
267 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable expiry is set together with pwhash
268 'user_password_expires' => $dbw->timestampOrNull( $expiry ),
270 ->where( [ 'user_name' => $username ] )
271 ->caller( __METHOD__ )->execute();
275 public function accountCreationType() {
276 return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
279 public function testForAccountCreation( $user, $creator, array $reqs ) {
280 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
282 $ret = \StatusValue::newGood();
283 if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
284 if ( $req->password !== $req->retype ) {
285 $ret->fatal( 'badretype' );
286 } else {
287 $ret->merge(
288 $this->checkPasswordValidity( $user->getName(), $req->password )
292 return $ret;
295 public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
296 if ( $this->accountCreationType() === self::TYPE_NONE ) {
297 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
300 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
301 if ( $req && $req->username !== null && $req->password !== null ) {
302 // Nothing we can do besides claim it, because the user isn't in
303 // the DB yet
304 if ( $req->username !== $user->getName() ) {
305 $req = clone $req;
306 $req->username = $user->getName();
308 $ret = AuthenticationResponse::newPass( $req->username );
309 $ret->createRequest = $req;
310 return $ret;
312 return AuthenticationResponse::newAbstain();
315 public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
316 if ( $this->accountCreationType() === self::TYPE_NONE ) {
317 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
320 // Now that the user is in the DB, set the password on it.
321 $this->providerChangeAuthenticationData( $res->createRequest );
323 return null;