MediaWiki master
LocalPasswordPrimaryAuthenticationProvider.php
Go to the documentation of this file.
1<?php
22namespace MediaWiki\Auth;
23
30
38{
39
41 protected $loginOnly = false;
42
44 private $dbProvider;
45
53 public function __construct( IConnectionProvider $dbProvider, $params = [] ) {
54 parent::__construct( $params );
55 $this->loginOnly = !empty( $params['loginOnly'] );
56 $this->dbProvider = $dbProvider;
57 }
58
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;
71 }
72
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(),
78 ];
79 } else {
80 $data = [
81 'hard' => false,
82 'msg' => \MediaWiki\Status\Status::newFatal( 'resetpass-expired-soft' )->getMessage(),
83 ];
84 }
85
86 return (object)$data;
87 }
88
89 public function beginPrimaryAuthentication( array $reqs ) {
90 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
91 if ( !$req || $req->username === null || $req->password === null ) {
93 }
94
95 $username = $this->userNameUtils->getCanonical(
96 $req->username, UserRigorOptions::RIGOR_USABLE );
97 if ( $username === false ) {
99 }
100
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 );
111 }
112
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}";
118 }
119
120 $status = $this->checkPasswordValidity( $username, $req->password );
121 if ( !$status->isOK() ) {
122 return $this->getFatalPasswordErrorResponse( $username, $status );
123 }
124
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 );
133 }
134 } else {
135 return $this->failResponse( $req );
136 }
137 }
138
139 // @codeCoverageIgnoreStart
140 if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
141 $newHash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
142 $fname = __METHOD__;
143 DeferredUpdates::addCallableUpdate( function () use ( $newHash, $oldRow, $fname ) {
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 )->execute();
153 } );
154 }
155 // @codeCoverageIgnoreEnd
156
157 $this->setPasswordResetFlag( $username, $status, $row );
158
159 return AuthenticationResponse::newPass( $username );
160 }
161
162 public function testUserCanAuthenticate( $username ) {
163 $username = $this->userNameUtils->getCanonical(
164 $username, UserRigorOptions::RIGOR_USABLE );
165 if ( $username === false ) {
166 return false;
167 }
168
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;
176 }
177
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;
182 }
183
184 return !$this->getPassword( $row->user_password ) instanceof InvalidPassword;
185 }
186
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;
192 }
193
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 ->recency( $flags )
200 ->caller( __METHOD__ )->fetchField();
201 }
202
204 AuthenticationRequest $req, $checkData = true
205 ) {
206 // We only want to blank the password if something else will accept the
207 // new authentication data, so return 'ignore' here.
208 if ( $this->loginOnly ) {
209 return \StatusValue::newGood( 'ignored' );
210 }
211
212 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
213 if ( !$checkData ) {
214 return \StatusValue::newGood();
215 }
216
217 $username = $this->userNameUtils->getCanonical( $req->username,
218 UserRigorOptions::RIGOR_USABLE );
219 if ( $username !== false ) {
220 $row = $this->dbProvider->getPrimaryDatabase()->newSelectQueryBuilder()
221 ->select( [ 'user_id' ] )
222 ->from( 'user' )
223 ->where( [ 'user_name' => $username ] )
224 ->caller( __METHOD__ )->fetchRow();
225 if ( $row ) {
226 $sv = \StatusValue::newGood();
227 if ( $req->password !== null ) {
228 if ( $req->password !== $req->retype ) {
229 $sv->fatal( 'badretype' );
230 } else {
231 $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
232 }
233 }
234 return $sv;
235 }
236 }
237 }
238
239 return \StatusValue::newGood( 'ignored' );
240 }
241
243 $username = $req->username !== null ?
244 $this->userNameUtils->getCanonical( $req->username, UserRigorOptions::RIGOR_USABLE )
245 : false;
246 if ( $username === false ) {
247 return;
248 }
249
250 $pwhash = null;
251
252 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
253 if ( $this->loginOnly ) {
254 $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
255 $expiry = null;
256 } else {
257 $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
258 $expiry = $this->getNewPasswordExpiry( $username );
259 }
260 }
261
262 if ( $pwhash ) {
263 $dbw = $this->dbProvider->getPrimaryDatabase();
264 $dbw->newUpdateQueryBuilder()
265 ->update( 'user' )
266 ->set( [
267 'user_password' => $pwhash->toString(),
268 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable expiry is set together with pwhash
269 'user_password_expires' => $dbw->timestampOrNull( $expiry ),
270 ] )
271 ->where( [ 'user_name' => $username ] )
272 ->caller( __METHOD__ )->execute();
273 }
274 }
275
276 public function accountCreationType() {
277 return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
278 }
279
280 public function testForAccountCreation( $user, $creator, array $reqs ) {
281 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
282
283 $ret = \StatusValue::newGood();
284 if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
285 if ( $req->password !== $req->retype ) {
286 $ret->fatal( 'badretype' );
287 } else {
288 $ret->merge(
289 $this->checkPasswordValidity( $user->getName(), $req->password )
290 );
291 }
292 }
293 return $ret;
294 }
295
296 public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
297 if ( $this->accountCreationType() === self::TYPE_NONE ) {
298 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
299 }
300
301 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
302 if ( $req && $req->username !== null && $req->password !== null ) {
303 // Nothing we can do besides claim it, because the user isn't in
304 // the DB yet
305 if ( $req->username !== $user->getName() ) {
306 $req = clone $req;
307 $req->username = $user->getName();
308 }
309 $ret = AuthenticationResponse::newPass( $req->username );
310 $ret->createRequest = $req;
311 return $ret;
312 }
314 }
315
316 public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
317 if ( $this->accountCreationType() === self::TYPE_NONE ) {
318 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
319 }
320
321 // Now that the user is in the DB, set the password on it.
322 $this->providerChangeAuthenticationData( $res->createRequest );
323
324 return null;
325 }
326}
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
array $params
The job parameters.
Basic framework for a primary authentication provider that uses passwords.
failResponse(PasswordAuthenticationRequest $req)
Return the appropriate response for failure.
setPasswordResetFlag( $username, Status $status, $data=null)
Check if the password should be reset.
getNewPasswordExpiry( $username)
Get expiration date for a new password, if any.
getFatalPasswordErrorResponse(string $username, Status $status)
Adds user-friendly description to a fatal password validity check error.
This is a value object for authentication requests.
static getRequestByClass(array $reqs, $class, $allowSubclasses=false)
Select a request by class name.
This is a value object to hold authentication response data.
A primary authentication provider that uses the password field in the 'user' table.
testUserExists( $username, $flags=IDBAccessObject::READ_NORMAL)
Test whether the named user exists.
beginPrimaryAccountCreation( $user, $creator, array $reqs)
Start an account creation flow.
testUserCanAuthenticate( $username)
Test whether the named user can authenticate with this provider.Should return true if the provider ha...
providerAllowsAuthenticationDataChange(AuthenticationRequest $req, $checkData=true)
Validate a change of authentication data (e.g.
providerChangeAuthenticationData(AuthenticationRequest $req)
Change or remove authentication data (e.g.
finishAccountCreation( $user, $creator, AuthenticationResponse $res)
Post-creation callback.Called after the user is added to the database, before secondary authenticatio...
testForAccountCreation( $user, $creator, array $reqs)
Determine whether an account creation may begin.Called from AuthManager::beginAccountCreation()No nee...
getPasswordResetData( $username, $row)
Check if the password has expired and needs a reset.
Defer callable updates to run later in the PHP process.
A class containing constants representing the names of configuration variables.
const LegacyEncoding
Name constant for the LegacyEncoding setting, for use with Config::get()
const PasswordExpireGrace
Name constant for the PasswordExpireGrace setting, for use with Config::get()
Represents an invalid password hash.
Interface for database access objects.
const TYPE_NONE
Provider cannot create or link to accounts.
Shared interface for rigor levels when dealing with User methods.
Provide primary and replica IDatabase connections.