Debian Codegraph @

includes/auth/AbstractTemporaryPasswordPrimaryAuthenticationProvider.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\MainConfigNames;
25 use MediaWiki\Password\InvalidPassword;
26 use MediaWiki\Password\Password;
27 use MediaWiki\Password\PasswordFactory;
28 use MediaWiki\SpecialPage\SpecialPage;
29 use MediaWiki\Title\Title;
30 use MediaWiki\User\Options\UserOptionsLookup;
31 use MediaWiki\User\User;
32 use MediaWiki\User\UserRigorOptions;
33 use Wikimedia\IPUtils;
34 use Wikimedia\Rdbms\IConnectionProvider;
35 use Wikimedia\Rdbms\IDBAccessObject;
36
37 /**
38 * A primary authentication provider that uses a temporary password.
39 *
40 * A successful login will force a password reset.
41 *
42 * @note For proper operation, this should generally come before any other
43 * password-based authentication providers.
44 * @stable to extend
45 * @ingroup Auth
46 * @since 1.43
47 */
48 abstract class AbstractTemporaryPasswordPrimaryAuthenticationProvider
49 extends AbstractPasswordPrimaryAuthenticationProvider
50 {
51 /** @var bool */
52 protected $emailEnabled = null;
53
54 /** @var int */
55 protected $newPasswordExpiry = null;
56
57 /** @var int */
58 protected $passwordReminderResendTime = null;
59
60 protected IConnectionProvider $dbProvider;
61 protected UserOptionsLookup $userOptionsLookup;
62
63 /**
64 * @param IConnectionProvider $dbProvider
65 * @param UserOptionsLookup $userOptionsLookup
66 * @param array $params
67 * - emailEnabled: (bool) must be true for the option to email passwords to be present
68 * - newPasswordExpiry: (int) expiration time of temporary passwords, in seconds
69 * - passwordReminderResendTime: (int) cooldown period in hours until a password reminder can
70 * be sent to the same user again
71 */
72 public function __construct(
73 IConnectionProvider $dbProvider,
74 UserOptionsLookup $userOptionsLookup,
75 $params = []
76 ) {
77 parent::__construct( $params );
78
79 if ( isset( $params['emailEnabled'] ) ) {
80 $this->emailEnabled = (bool)$params['emailEnabled'];
81 }
82 if ( isset( $params['newPasswordExpiry'] ) ) {
83 $this->newPasswordExpiry = (int)$params['newPasswordExpiry'];
84 }
85 if ( isset( $params['passwordReminderResendTime'] ) ) {
86 $this->passwordReminderResendTime = $params['passwordReminderResendTime'];
87 }
88 $this->dbProvider = $dbProvider;
89 $this->userOptionsLookup = $userOptionsLookup;
90 }
91
92 protected function postInitSetup() {
93 $this->emailEnabled ??= $this->config->get( MainConfigNames::EnableEmail );
94 $this->newPasswordExpiry ??= $this->config->get( MainConfigNames::NewPasswordExpiry );
95 $this->passwordReminderResendTime ??=
96 $this->config->get( MainConfigNames::PasswordReminderResendTime );
97 }
98
99 protected function getPasswordResetData( $username, $data ) {
100 // Always reset
101 return (object)[
102 'msg' => wfMessage( 'resetpass-temp-emailed' ),
103 'hard' => true,
104 ];
105 }
106
107 public function getAuthenticationRequests( $action, array $options ) {
108 switch ( $action ) {
109 case AuthManager::ACTION_LOGIN:
110 return [ new PasswordAuthenticationRequest() ];
111
112 case AuthManager::ACTION_CHANGE:
113 return [ TemporaryPasswordAuthenticationRequest::newRandom() ];
114
115 case AuthManager::ACTION_CREATE:
116 // Allow named users creating a new account to email a temporary password to a given address
117 // in case they are creating an account for somebody else.
118 // This isn't a likely scenario for account creations by anonymous or temporary users
119 // and is therefore disabled for them (T328718).
120 if (
121 isset( $options['username'] ) &&
122 !$this->userNameUtils->isTemp( $options['username'] ) &&
123 $this->emailEnabled
124 ) {
125 return [ TemporaryPasswordAuthenticationRequest::newRandom() ];
126 } else {
127 return [];
128 }
129
130 case AuthManager::ACTION_REMOVE:
131 return [ new TemporaryPasswordAuthenticationRequest ];
132
133 default:
134 return [];
135 }
136 }
137
138 public function beginPrimaryAuthentication( array $reqs ) {
139 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
140 if ( !$req || $req->username === null || $req->password === null ) {
141 return AuthenticationResponse::newAbstain();
142 }
143
144 $username = $this->userNameUtils->getCanonical(
145 $req->username, UserRigorOptions::RIGOR_USABLE );
146 if ( $username === false ) {
147 return AuthenticationResponse::newAbstain();
148 }
149
150 [ $tempPassHash, $tempPassTime ] = $this->getTemporaryPassword( $username, IDBAccessObject::READ_LATEST );
151 if ( !$tempPassHash ) {
152 return AuthenticationResponse::newAbstain();
153 }
154
155 $status = $this->checkPasswordValidity( $username, $req->password );
156 if ( !$status->isOK() ) {
157 return $this->getFatalPasswordErrorResponse( $username, $status );
158 }
159
160 if ( !$tempPassHash->verify( $req->password ) ||
161 !$this->isTimestampValid( $tempPassTime )
162 ) {
163 return $this->failResponse( $req );
164 }
165
166 // Add an extra log entry since a temporary password is
167 // an unusual way to log in, so its important to keep track
168 // of in case of abuse.
169 $this->logger->info( "{user} successfully logged in using temp password",
170 [
171 'provider' => static::class,
172 'user' => $username,
173 'requestIP' => $this->manager->getRequest()->getIP()
174 ]
175 );
176
177 $this->setPasswordResetFlag( $username, $status );
178
179 return AuthenticationResponse::newPass( $username );
180 }
181
182 public function testUserCanAuthenticate( $username ) {
183 $username = $this->userNameUtils->getCanonical( $username, UserRigorOptions::RIGOR_USABLE );
184 if ( $username === false ) {
185 return false;
186 }
187
188 [ $tempPassHash, $tempPassTime ] = $this->getTemporaryPassword( $username );
189 return $tempPassHash &&
190 !( $tempPassHash instanceof InvalidPassword ) &&
191 $this->isTimestampValid( $tempPassTime );
192 }
193
194 public function providerAllowsAuthenticationDataChange(
195 AuthenticationRequest $req, $checkData = true
196 ) {
197 if ( get_class( $req ) !== TemporaryPasswordAuthenticationRequest::class ) {
198 // We don't really ignore it, but this is what the caller expects.
199 return \StatusValue::newGood( 'ignored' );
200 }
201
202 if ( !$checkData ) {
203 return \StatusValue::newGood();
204 }
205
206 $username = $this->userNameUtils->getCanonical(
207 $req->username, UserRigorOptions::RIGOR_USABLE );
208 if ( $username === false ) {
209 return \StatusValue::newGood( 'ignored' );
210 }
211
212 [ $tempPassHash, $tempPassTime ] = $this->getTemporaryPassword( $username, IDBAccessObject::READ_LATEST );
213 if ( !$tempPassHash ) {
214 return \StatusValue::newGood( 'ignored' );
215 }
216
217 $sv = \StatusValue::newGood();
218 if ( $req->password !== null ) {
219 $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
220
221 if ( $req->mailpassword ) {
222 if ( !$this->emailEnabled ) {
223 return \StatusValue::newFatal( 'passwordreset-emaildisabled' );
224 }
225
226 // We don't check whether the user has an email address;
227 // that information should not be exposed to the caller.
228
229 // do not allow temporary password creation within
230 // $wgPasswordReminderResendTime from the last attempt
231 if (
232 $this->passwordReminderResendTime
233 && $tempPassTime
234 && time() < (int)wfTimestamp( TS_UNIX, $tempPassTime )
235 + $this->passwordReminderResendTime * 3600
236 ) {
237 // Round the time in hours to 3 d.p., in case someone is specifying
238 // minutes or seconds.
239 return \StatusValue::newFatal( 'throttled-mailpassword',
240 round( $this->passwordReminderResendTime, 3 ) );
241 }
242
243 if ( !$req->caller ) {
244 return \StatusValue::newFatal( 'passwordreset-nocaller' );
245 }
246 if ( !IPUtils::isValid( $req->caller ) ) {
247 $caller = User::newFromName( $req->caller );
248 if ( !$caller ) {
249 return \StatusValue::newFatal( 'passwordreset-nosuchcaller', $req->caller );
250 }
251 }
252 }
253 }
254 return $sv;
255 }
256
257 public function providerChangeAuthenticationData( AuthenticationRequest $req ) {
258 $username = $req->username !== null ?
259 $this->userNameUtils->getCanonical( $req->username, UserRigorOptions::RIGOR_USABLE ) : false;
260 if ( $username === false ) {
261 return;
262 }
263
264 $sendMail = false;
265 if ( $req->action !== AuthManager::ACTION_REMOVE &&
266 get_class( $req ) === TemporaryPasswordAuthenticationRequest::class
267 ) {
268 $tempPassHash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
269 $tempPassTime = wfTimestampNow();
270 $sendMail = $req->mailpassword;
271 // Prevent other temp password providers from sending duplicate emails
272 $req->mailpassword = false;
273 } else {
274 // Invalidate the temporary password when any other auth is reset, or when removing
275 $tempPassHash = PasswordFactory::newInvalidPassword();
276 $tempPassTime = null;
277 }
278
279 $this->setTemporaryPassword( $username, $tempPassHash, $tempPassTime );
280
281 if ( $sendMail ) {
282 $this->maybeSendPasswordResetEmail( $req );
283 }
284 }
285
286 public function accountCreationType() {
287 return self::TYPE_CREATE;
288 }
289
290 public function testForAccountCreation( $user, $creator, array $reqs ) {
291 /** @var TemporaryPasswordAuthenticationRequest $req */
292 $req = AuthenticationRequest::getRequestByClass(
293 $reqs, TemporaryPasswordAuthenticationRequest::class
294 );
295
296 $ret = \StatusValue::newGood();
297 if ( $req ) {
298 if ( $req->mailpassword ) {
299 if ( !$this->emailEnabled ) {
300 $ret->merge( \StatusValue::newFatal( 'emaildisabled' ) );
301 } elseif ( !$user->getEmail() ) {
302 $ret->merge( \StatusValue::newFatal( 'noemailcreate' ) );
303 }
304 }
305
306 $ret->merge(
307 $this->checkPasswordValidity( $user->getName(), $req->password )
308 );
309 }
310 return $ret;
311 }
312
313 public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
314 /** @var TemporaryPasswordAuthenticationRequest $req */
315 $req = AuthenticationRequest::getRequestByClass(
316 $reqs, TemporaryPasswordAuthenticationRequest::class
317 );
318 if ( $req && $req->username !== null && $req->password !== null ) {
319 // Nothing we can do yet, because the user isn't in the DB yet
320 if ( $req->username !== $user->getName() ) {
321 $req = clone $req;
322 $req->username = $user->getName();
323 }
324
325 if ( $req->mailpassword ) {
326 // prevent EmailNotificationSecondaryAuthenticationProvider from sending another mail
327 $this->manager->setAuthenticationSessionData( 'no-email', true );
328 }
329
330 $ret = AuthenticationResponse::newPass( $req->username );
331 $ret->createRequest = $req;
332 return $ret;
333 }
334 return AuthenticationResponse::newAbstain();
335 }
336
337 public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
338 /** @var TemporaryPasswordAuthenticationRequest $req */
339 $req = $res->createRequest;
340 $mailpassword = $req->mailpassword;
341 // Prevent providerChangeAuthenticationData() from sending the wrong email
342 $req->mailpassword = false;
343
344 // Now that the user is in the DB, set the password on it.
345 $this->providerChangeAuthenticationData( $req );
346
347 if ( $mailpassword ) {
348 $this->maybeSendNewAccountEmail( $user, $creator, $req->password );
349 }
350
351 return $mailpassword ? 'byemail' : null;
352 }
353
354 /**
355 * Check that a temporary password is still valid (hasn't expired).
356 * @param string|int|null $timestamp Timestamp in the database's format; null means it doesn't
357 * expire
358 * @return bool
359 */
360 protected function isTimestampValid( $timestamp ) {
361 $time = wfTimestampOrNull( TS_MW, $timestamp );
362 if ( $time !== null ) {
363 $expiry = (int)wfTimestamp( TS_UNIX, $time ) + $this->newPasswordExpiry;
364 if ( time() >= $expiry ) {
365 return false;
366 }
367 }
368 return true;
369 }
370
371 /**
372 * Wait for the new account to be recorded, and if successful, send an email about the new
373 * account creation and the temporary password.
374 *
375 * If overridden, the override must call sendNewAccountEmail().
376 *
377 * @stable to override
378 * @param User $user The new user account
379 * @param User $creatingUser The user who created the account (can be anonymous)
380 * @param string $password The temporary password
381 */
382 protected function maybeSendNewAccountEmail( User $user, User $creatingUser, $password ): void {
383 // Send email after DB commit (the callback does not run in case of DB rollback)
384 $this->dbProvider->getPrimaryDatabase()->onTransactionCommitOrIdle(
385 function () use ( $user, $creatingUser, $password ) {
386 $this->sendNewAccountEmail( $user, $creatingUser, $password );
387 },
388 __METHOD__
389 );
390 }
391
392 /**
393 * Send an email about the new account creation and the temporary password.
394 *
395 * @stable to override
396 * @param User $user The new user account
397 * @param User $creatingUser The user who created the account (can be anonymous)
398 * @param string $password The temporary password
399 */
400 protected function sendNewAccountEmail( User $user, User $creatingUser, $password ): void {
401 $ip = $creatingUser->getRequest()->getIP();
402 // @codeCoverageIgnoreStart
403 if ( !$ip ) {
404 return;
405 }
406 // @codeCoverageIgnoreEnd
407
408 $this->getHookRunner()->onUser__mailPasswordInternal( $creatingUser, $ip, $user );
409
410 $mainPageUrl = Title::newMainPage()->getCanonicalURL();
411 $userLanguage = $this->userOptionsLookup->getOption( $user, 'language' );
412 $subjectMessage = wfMessage( 'createaccount-title' )->inLanguage( $userLanguage );
413 $bodyMessage = wfMessage( 'createaccount-text', $ip, $user->getName(), $password,
414 '<' . $mainPageUrl . '>', round( $this->newPasswordExpiry / 86400 ) )
415 ->inLanguage( $userLanguage );
416
417 $status = $user->sendMail( $subjectMessage->text(), $bodyMessage->text() );
418
419 // @codeCoverageIgnoreStart
420 if ( !$status->isGood() ) {
421 $this->logger->warning( 'Could not send account creation email: ' .
422 $status->getWikiText( false, false, 'en' ) );
423 }
424 // @codeCoverageIgnoreEnd
425 }
426
427 /**
428 * Wait for the new temporary password to be recorded, and if successful, send an email about it.
429 *
430 * If overridden, the override must call sendPasswordResetEmail().
431 *
432 * @stable to override
433 * @param TemporaryPasswordAuthenticationRequest $req
434 */
435 protected function maybeSendPasswordResetEmail( TemporaryPasswordAuthenticationRequest $req ): void {
436 // Send email after DB commit (the callback does not run in case of DB rollback)
437 $this->dbProvider->getPrimaryDatabase()->onTransactionCommitOrIdle(
438 function () use ( $req ) {
439 $this->sendPasswordResetEmail( $req );
440 },
441 __METHOD__
442 );
443 }
444
445 /**
446 * Send an email about the new temporary password.
447 *
448 * @stable to override
449 * @param TemporaryPasswordAuthenticationRequest $req
450 */
451 protected function sendPasswordResetEmail( TemporaryPasswordAuthenticationRequest $req ): void {
452 $user = User::newFromName( $req->username );
453 if ( !$user ) {
454 return;
455 }
456 $userLanguage = $this->userOptionsLookup->getOption( $user, 'language' );
457 $callerIsAnon = IPUtils::isValid( $req->caller );
458 $callerName = $callerIsAnon ? $req->caller : User::newFromName( $req->caller )->getName();
459 $passwordMessage = wfMessage( 'passwordreset-emailelement', $user->getName(),
460 $req->password )->inLanguage( $userLanguage );
461 $emailMessage = wfMessage( $callerIsAnon ? 'passwordreset-emailtext-ip'
462 : 'passwordreset-emailtext-user' )->inLanguage( $userLanguage );
463 $body = $emailMessage->params( $callerName, $passwordMessage->text(), 1,
464 '<' . Title::newMainPage()->getCanonicalURL() . '>',
465 round( $this->newPasswordExpiry / 86400 ) )->text();
466
467 // Hint that the user can choose to require email address to request a temporary password
468 if (
469 !$this->userOptionsLookup->getBoolOption( $user, 'requireemail' )
470 ) {
471 $url = SpecialPage::getTitleFor( 'Preferences', false, 'mw-prefsection-personal-email' )
472 ->getCanonicalURL();
473 $body .= "\n\n" . wfMessage( 'passwordreset-emailtext-require-email' )
474 ->inLanguage( $userLanguage )
475 ->params( "<$url>" )
476 ->text();
477 }
478
479 $emailTitle = wfMessage( 'passwordreset-emailtitle' )->inLanguage( $userLanguage );
480 $user->sendMail( $emailTitle->text(), $body );
481 }
482
483 /**
484 * Return a tuple of temporary password and the time when it was generated.
485 *
486 * The password may be an InvalidPassword to represent that it was unset, or null if the user
487 * can't authenticate for other reasons.
488 *
489 * The time is a a timestamp in the database's format or null (use wfTimestampOrNull() to parse
490 * it). If it's null, the password doesn't expire. Otherwise, the password should be considered
491 * expired after $wgNewPasswordExpiry seconds since that time.
492 *
493 * @stable to override
494 * @param string $username Canonical username
495 * @param int $flags Bitfield of IDBAccessObject::READ_* constants
496 * @return array
497 * @phan-return array{0:?Password, 1:?string|int}
498 */
499 abstract protected function getTemporaryPassword( string $username, $flags = IDBAccessObject::READ_NORMAL ): array;
500
501 /**
502 * Set a temporary password and the time when it was generated.
503 *
504 * @param string $username Canonical username
505 * @param Password $tempPassHash Password, or an InvalidPassword to unset
506 * @param string|int|null $tempPassTime Timestamp in a format accepted by wfTimestampOrNull();
507 * null means it doesn't expire
508 */
509 abstract protected function setTemporaryPassword( string $username, Password $tempPassHash, $tempPassTime ): void;
510 }