3 * Utility class for bot passwords
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\Auth\AuthenticationResponse
;
22 use MediaWiki\Auth\Throttler
;
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Session\BotPasswordSessionProvider
;
25 use MediaWiki\Session\SessionManager
;
26 use Wikimedia\Rdbms\IDatabase
;
29 * Utility class for bot passwords
32 class BotPassword
implements IDBAccessObject
{
34 public const APPID_MAXLENGTH
= 32;
37 * Minimum length for a bot password
39 public const PASSWORD_MINLENGTH
= 32;
42 * Maximum length of the json representation of restrictions
45 public const RESTRICTIONS_MAXLENGTH
= 65535;
48 * Maximum length of the json representation of grants
51 public const GRANTS_MAXLENGTH
= 65535;
65 /** @var MWRestrictions */
66 private $restrictions;
72 private $flags = self
::READ_NORMAL
;
75 * @param stdClass $row bot_passwords database row
76 * @param bool $isSaved Whether the bot password was read from the database
77 * @param int $flags IDBAccessObject read flags
79 private function __construct( $row, $isSaved, $flags = self
::READ_NORMAL
) {
80 $this->isSaved
= $isSaved;
81 $this->flags
= $flags;
83 $this->centralId
= (int)$row->bp_user
;
84 $this->appId
= $row->bp_app_id
;
85 $this->token
= $row->bp_token
;
86 $this->restrictions
= MWRestrictions
::newFromJson( $row->bp_restrictions
);
87 $this->grants
= FormatJson
::decode( $row->bp_grants
);
91 * Get a database connection for the bot passwords database
92 * @param int $db Index of the connection to get, e.g. DB_MASTER or DB_REPLICA.
95 public static function getDB( $db ) {
96 global $wgBotPasswordsCluster, $wgBotPasswordsDatabase;
98 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
99 $lb = $wgBotPasswordsCluster
100 ?
$lbFactory->getExternalLB( $wgBotPasswordsCluster )
101 : $lbFactory->getMainLB( $wgBotPasswordsDatabase );
102 return $lb->getConnectionRef( $db, [], $wgBotPasswordsDatabase );
106 * Load a BotPassword from the database
108 * @param string $appId
109 * @param int $flags IDBAccessObject read flags
110 * @return BotPassword|null
112 public static function newFromUser( User
$user, $appId, $flags = self
::READ_NORMAL
) {
113 $centralId = CentralIdLookup
::factory()->centralIdFromLocalUser(
114 $user, CentralIdLookup
::AUDIENCE_RAW
, $flags
116 return $centralId ? self
::newFromCentralId( $centralId, $appId, $flags ) : null;
120 * Load a BotPassword from the database
121 * @param int $centralId from CentralIdLookup
122 * @param string $appId
123 * @param int $flags IDBAccessObject read flags
124 * @return BotPassword|null
126 public static function newFromCentralId( $centralId, $appId, $flags = self
::READ_NORMAL
) {
127 global $wgEnableBotPasswords;
129 if ( !$wgEnableBotPasswords ) {
133 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
134 $db = self
::getDB( $index );
135 $row = $db->selectRow(
137 [ 'bp_user', 'bp_app_id', 'bp_token', 'bp_restrictions', 'bp_grants' ],
138 [ 'bp_user' => $centralId, 'bp_app_id' => $appId ],
142 return $row ?
new self( $row, true, $flags ) : null;
146 * Create an unsaved BotPassword
147 * @param array $data Data to use to create the bot password. Keys are:
148 * - user: (User) User object to create the password for. Overrides username and centralId.
149 * - username: (string) Username to create the password for. Overrides centralId.
150 * - centralId: (int) User central ID to create the password for.
151 * - appId: (string, required) App ID for the password.
152 * - restrictions: (MWRestrictions, optional) Restrictions.
153 * - grants: (string[], optional) Grants.
154 * @param int $flags IDBAccessObject read flags
155 * @return BotPassword|null
157 public static function newUnsaved( array $data, $flags = self
::READ_NORMAL
) {
158 if ( isset( $data['user'] ) && ( !$data['user'] instanceof User
) ) {
164 'bp_app_id' => isset( $data['appId'] ) ?
trim( $data['appId'] ) : '',
165 'bp_token' => '**unsaved**',
166 'bp_restrictions' => $data['restrictions'] ?? MWRestrictions
::newDefault(),
167 'bp_grants' => $data['grants'] ??
[],
171 $row->bp_app_id
=== '' ||
172 strlen( $row->bp_app_id
) > self
::APPID_MAXLENGTH ||
173 !$row->bp_restrictions
instanceof MWRestrictions ||
174 !is_array( $row->bp_grants
)
179 $row->bp_restrictions
= $row->bp_restrictions
->toJson();
180 $row->bp_grants
= FormatJson
::encode( $row->bp_grants
);
182 if ( isset( $data['user'] ) ) {
183 // Must be a User object, already checked above
184 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromLocalUser(
185 $data['user'], CentralIdLookup
::AUDIENCE_RAW
, $flags
187 } elseif ( isset( $data['username'] ) ) {
188 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromName(
189 $data['username'], CentralIdLookup
::AUDIENCE_RAW
, $flags
191 } elseif ( isset( $data['centralId'] ) ) {
192 $row->bp_user
= $data['centralId'];
194 if ( !$row->bp_user
) {
198 return new self( $row, false, $flags );
202 * Indicate whether this is known to be saved
205 public function isSaved() {
206 return $this->isSaved
;
210 * Get the central user ID
213 public function getUserCentralId() {
214 return $this->centralId
;
220 public function getAppId() {
227 public function getToken() {
232 * @return MWRestrictions
234 public function getRestrictions() {
235 return $this->restrictions
;
241 public function getGrants() {
242 return $this->grants
;
246 * Get the separator for combined user name + app ID
249 public static function getSeparator() {
250 global $wgUserrightsInterwikiDelimiter;
251 return $wgUserrightsInterwikiDelimiter;
257 private function getPassword() {
258 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->flags
);
259 $db = self
::getDB( $index );
260 $password = $db->selectField(
263 [ 'bp_user' => $this->centralId
, 'bp_app_id' => $this->appId
],
267 if ( $password === false ) {
268 return PasswordFactory
::newInvalidPassword();
271 $passwordFactory = MediaWikiServices
::getInstance()->getPasswordFactory();
273 return $passwordFactory->newFromCiphertext( $password );
274 } catch ( PasswordError
$ex ) {
275 return PasswordFactory
::newInvalidPassword();
280 * Whether the password is currently invalid
284 public function isInvalid() {
285 return $this->getPassword() instanceof InvalidPassword
;
289 * Save the BotPassword to the database
290 * @param string $operation 'update' or 'insert'
291 * @param Password|null $password Password to set.
293 * @throws UnexpectedValueException
295 public function save( $operation, Password
$password = null ) {
296 // Ensure operation is valid
297 if ( $operation !== 'insert' && $operation !== 'update' ) {
298 throw new UnexpectedValueException(
299 "Expected 'insert' or 'update'; got '{$operation}'."
304 'bp_user' => $this->centralId
,
305 'bp_app_id' => $this->appId
,
308 $res = Status
::newGood();
310 $restrictions = $this->restrictions
->toJson();
312 if ( strlen( $restrictions ) > self
::RESTRICTIONS_MAXLENGTH
) {
313 $res->fatal( 'botpasswords-toolong-restrictions' );
316 $grants = FormatJson
::encode( $this->grants
);
318 if ( strlen( $grants ) > self
::GRANTS_MAXLENGTH
) {
319 $res->fatal( 'botpasswords-toolong-grants' );
322 if ( !$res->isGood() ) {
327 'bp_token' => MWCryptRand
::generateHex( User
::TOKEN_LENGTH
),
328 'bp_restrictions' => $restrictions,
329 'bp_grants' => $grants,
332 if ( $password !== null ) {
333 $fields['bp_password'] = $password->toString();
334 } elseif ( $operation === 'insert' ) {
335 $fields['bp_password'] = PasswordFactory
::newInvalidPassword()->toString();
338 $dbw = self
::getDB( DB_MASTER
);
340 if ( $operation === 'insert' ) {
341 $dbw->insert( 'bot_passwords', $fields +
$conds, __METHOD__
, [ 'IGNORE' ] );
343 // Must be update, already checked above
344 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__
);
347 $ok = (bool)$dbw->affectedRows();
349 $this->token
= $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__
);
350 $this->isSaved
= true;
355 // Messages: botpasswords-insert-failed, botpasswords-update-failed
356 return Status
::newFatal( "botpasswords-{$operation}-failed", $this->appId
);
360 * Delete the BotPassword from the database
361 * @return bool Success
363 public function delete() {
364 $dbw = self
::getDB( DB_MASTER
);
368 'bp_user' => $this->centralId
,
369 'bp_app_id' => $this->appId
,
373 $ok = (bool)$dbw->affectedRows();
375 $this->token
= '**unsaved**';
376 $this->isSaved
= false;
382 * Invalidate all passwords for a user, by name
383 * @param string $username User name
384 * @return bool Whether any passwords were invalidated
386 public static function invalidateAllPasswordsForUser( $username ) {
387 $centralId = CentralIdLookup
::factory()->centralIdFromName(
388 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
390 return $centralId && self
::invalidateAllPasswordsForCentralId( $centralId );
394 * Invalidate all passwords for a user, by central ID
396 * Currently unused outside of this class, should be combined with invalidateAllPasswordsForUser
398 * @param int $centralId
399 * @return bool Whether any passwords were invalidated
401 public static function invalidateAllPasswordsForCentralId( $centralId ) {
402 global $wgEnableBotPasswords;
404 if ( !$wgEnableBotPasswords ) {
408 $dbw = self
::getDB( DB_MASTER
);
411 [ 'bp_password' => PasswordFactory
::newInvalidPassword()->toString() ],
412 [ 'bp_user' => $centralId ],
415 return (bool)$dbw->affectedRows();
419 * Remove all passwords for a user, by name
420 * @param string $username User name
421 * @return bool Whether any passwords were removed
423 public static function removeAllPasswordsForUser( $username ) {
424 $centralId = CentralIdLookup
::factory()->centralIdFromName(
425 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
427 return $centralId && self
::removeAllPasswordsForCentralId( $centralId );
431 * Remove all passwords for a user, by central ID
433 * Currently unused outside of this class, should be combined with removeAllPasswordsForUser
435 * @param int $centralId
436 * @return bool Whether any passwords were removed
438 public static function removeAllPasswordsForCentralId( $centralId ) {
439 global $wgEnableBotPasswords;
441 if ( !$wgEnableBotPasswords ) {
445 $dbw = self
::getDB( DB_MASTER
);
448 [ 'bp_user' => $centralId ],
451 return (bool)$dbw->affectedRows();
455 * Returns a (raw, unhashed) random password string.
456 * @param Config $config
459 public static function generatePassword( $config ) {
460 return PasswordFactory
::generateRandomPasswordString(
461 max( self
::PASSWORD_MINLENGTH
, $config->get( 'MinimalPasswordLength' ) ) );
465 * There are two ways to login with a bot password: "username@appId", "password" and
466 * "username", "appId@password". Transform it so it is always in the first form.
467 * Returns [bot username, bot password].
468 * If this cannot be a bot password login just return false.
469 * @param string $username
470 * @param string $password
471 * @return string[]|false
473 public static function canonicalizeLoginData( $username, $password ) {
474 $sep = self
::getSeparator();
475 // the strlen check helps minimize the password information obtainable from timing
476 if ( strlen( $password ) >= self
::PASSWORD_MINLENGTH
&& strpos( $username, $sep ) !== false ) {
477 // the separator is not valid in new usernames but might appear in legacy ones
478 if ( preg_match( '/^[0-9a-w]{' . self
::PASSWORD_MINLENGTH
. ',}$/', $password ) ) {
479 return [ $username, $password ];
481 } elseif ( strlen( $password ) > self
::PASSWORD_MINLENGTH
&& strpos( $password, $sep ) !== false ) {
482 $segments = explode( $sep, $password );
483 $password = array_pop( $segments );
484 $appId = implode( $sep, $segments );
485 if ( preg_match( '/^[0-9a-w]{' . self
::PASSWORD_MINLENGTH
. ',}$/', $password ) ) {
486 return [ $username . $sep . $appId, $password ];
493 * Try to log the user in
494 * @param string $username Combined user name and app ID
495 * @param string $password Supplied password
496 * @param WebRequest $request
497 * @return Status On success, the good status's value is the new Session object
499 public static function login( $username, $password, WebRequest
$request ) {
500 global $wgEnableBotPasswords, $wgPasswordAttemptThrottle;
502 if ( !$wgEnableBotPasswords ) {
503 return Status
::newFatal( 'botpasswords-disabled' );
506 $provider = SessionManager
::singleton()->getProvider( BotPasswordSessionProvider
::class );
508 return Status
::newFatal( 'botpasswords-no-provider' );
511 // Split name into name+appId
512 $sep = self
::getSeparator();
513 if ( strpos( $username, $sep ) === false ) {
514 return self
::loginHook( $username, null, Status
::newFatal( 'botpasswords-invalid-name', $sep ) );
516 list( $name, $appId ) = explode( $sep, $username, 2 );
518 // Find the named user
519 $user = User
::newFromName( $name );
520 if ( !$user ||
$user->isAnon() ) {
521 return self
::loginHook( $user ?
: $name, null, Status
::newFatal( 'nosuchuser', $name ) );
524 if ( $user->isLocked() ) {
525 return Status
::newFatal( 'botpasswords-locked' );
529 if ( !empty( $wgPasswordAttemptThrottle ) ) {
530 $throttle = new Throttler( $wgPasswordAttemptThrottle, [
531 'type' => 'botpassword',
532 'cache' => ObjectCache
::getLocalClusterInstance(),
534 $result = $throttle->increase( $user->getName(), $request->getIP(), __METHOD__
);
536 $msg = wfMessage( 'login-throttled' )->durationParams( $result['wait'] );
537 return self
::loginHook( $user, null, Status
::newFatal( $msg ) );
541 // Get the bot password
542 $bp = self
::newFromUser( $user, $appId );
544 return self
::loginHook( $user, $bp,
545 Status
::newFatal( 'botpasswords-not-exist', $name, $appId ) );
548 // Check restrictions
549 $status = $bp->getRestrictions()->check( $request );
550 if ( !$status->isOK() ) {
551 return self
::loginHook( $user, $bp, Status
::newFatal( 'botpasswords-restriction-failed' ) );
554 // Check the password
555 $passwordObj = $bp->getPassword();
556 if ( $passwordObj instanceof InvalidPassword
) {
557 return self
::loginHook( $user, $bp,
558 Status
::newFatal( 'botpasswords-needs-reset', $name, $appId ) );
560 if ( !$passwordObj->verify( $password ) ) {
561 return self
::loginHook( $user, $bp, Status
::newFatal( 'wrongpassword' ) );
564 // Ok! Create the session.
566 $throttle->clear( $user->getName(), $request->getIP() );
568 return self
::loginHook( $user, $bp,
569 // @phan-suppress-next-line PhanUndeclaredMethod
570 Status
::newGood( $provider->newSessionForRequest( $user, $bp, $request ) ) );
574 * Call AuthManagerLoginAuthenticateAudit
576 * To facilitate logging all authentications, even ones not via
577 * AuthManager, call the AuthManagerLoginAuthenticateAudit hook.
579 * @param User|string $user User being logged in
580 * @param BotPassword|null $bp Bot sub-account, if it can be identified
581 * @param Status $status Login status
582 * @return Status The passed-in status
584 private static function loginHook( $user, $bp, Status
$status ) {
586 if ( $user instanceof User
) {
587 $name = $user->getName();
589 $extraData['appId'] = $name . self
::getSeparator() . $bp->getAppId();
596 if ( $status->isGood() ) {
597 $response = AuthenticationResponse
::newPass( $name );
599 $response = AuthenticationResponse
::newFail( $status->getMessage() );
601 Hooks
::runner()->onAuthManagerLoginAuthenticateAudit( $response, $user, $name, $extraData );