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