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\MediaWikiServices
;
22 use MediaWiki\Session\BotPasswordSessionProvider
;
23 use Wikimedia\Rdbms\IMaintainableDatabase
;
26 * Utility class for bot passwords
29 class BotPassword
implements IDBAccessObject
{
31 const APPID_MAXLENGTH
= 32;
45 /** @var MWRestrictions */
46 private $restrictions;
52 private $flags = self
::READ_NORMAL
;
55 * @param object $row bot_passwords database row
56 * @param bool $isSaved Whether the bot password was read from the database
57 * @param int $flags IDBAccessObject read flags
59 protected function __construct( $row, $isSaved, $flags = self
::READ_NORMAL
) {
60 $this->isSaved
= $isSaved;
61 $this->flags
= $flags;
63 $this->centralId
= (int)$row->bp_user
;
64 $this->appId
= $row->bp_app_id
;
65 $this->token
= $row->bp_token
;
66 $this->restrictions
= MWRestrictions
::newFromJson( $row->bp_restrictions
);
67 $this->grants
= FormatJson
::decode( $row->bp_grants
);
71 * Get a database connection for the bot passwords database
72 * @param int $db Index of the connection to get, e.g. DB_MASTER or DB_REPLICA.
73 * @return IMaintainableDatabase
75 public static function getDB( $db ) {
76 global $wgBotPasswordsCluster, $wgBotPasswordsDatabase;
78 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
79 $lb = $wgBotPasswordsCluster
80 ?
$lbFactory->getExternalLB( $wgBotPasswordsCluster )
81 : $lbFactory->getMainLB( $wgBotPasswordsDatabase );
82 return $lb->getConnectionRef( $db, [], $wgBotPasswordsDatabase );
86 * Load a BotPassword from the database
88 * @param string $appId
89 * @param int $flags IDBAccessObject read flags
90 * @return BotPassword|null
92 public static function newFromUser( User
$user, $appId, $flags = self
::READ_NORMAL
) {
93 $centralId = CentralIdLookup
::factory()->centralIdFromLocalUser(
94 $user, CentralIdLookup
::AUDIENCE_RAW
, $flags
96 return $centralId ? self
::newFromCentralId( $centralId, $appId, $flags ) : null;
100 * Load a BotPassword from the database
101 * @param int $centralId from CentralIdLookup
102 * @param string $appId
103 * @param int $flags IDBAccessObject read flags
104 * @return BotPassword|null
106 public static function newFromCentralId( $centralId, $appId, $flags = self
::READ_NORMAL
) {
107 global $wgEnableBotPasswords;
109 if ( !$wgEnableBotPasswords ) {
113 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
114 $db = self
::getDB( $index );
115 $row = $db->selectRow(
117 [ 'bp_user', 'bp_app_id', 'bp_token', 'bp_restrictions', 'bp_grants' ],
118 [ 'bp_user' => $centralId, 'bp_app_id' => $appId ],
122 return $row ?
new self( $row, true, $flags ) : null;
126 * Create an unsaved BotPassword
127 * @param array $data Data to use to create the bot password. Keys are:
128 * - user: (User) User object to create the password for. Overrides username and centralId.
129 * - username: (string) Username to create the password for. Overrides centralId.
130 * - centralId: (int) User central ID to create the password for.
131 * - appId: (string) App ID for the password.
132 * - restrictions: (MWRestrictions, optional) Restrictions.
133 * - grants: (string[], optional) Grants.
134 * @param int $flags IDBAccessObject read flags
135 * @return BotPassword|null
137 public static function newUnsaved( array $data, $flags = self
::READ_NORMAL
) {
140 'bp_app_id' => isset( $data['appId'] ) ?
trim( $data['appId'] ) : '',
141 'bp_token' => '**unsaved**',
142 'bp_restrictions' => $data['restrictions'] ?? MWRestrictions
::newDefault(),
143 'bp_grants' => $data['grants'] ??
[],
147 $row->bp_app_id
=== '' ||
strlen( $row->bp_app_id
) > self
::APPID_MAXLENGTH ||
148 !$row->bp_restrictions
instanceof MWRestrictions ||
149 !is_array( $row->bp_grants
)
154 $row->bp_restrictions
= $row->bp_restrictions
->toJson();
155 $row->bp_grants
= FormatJson
::encode( $row->bp_grants
);
157 if ( isset( $data['user'] ) ) {
158 if ( !$data['user'] instanceof User
) {
161 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromLocalUser(
162 $data['user'], CentralIdLookup
::AUDIENCE_RAW
, $flags
164 } elseif ( isset( $data['username'] ) ) {
165 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromName(
166 $data['username'], CentralIdLookup
::AUDIENCE_RAW
, $flags
168 } elseif ( isset( $data['centralId'] ) ) {
169 $row->bp_user
= $data['centralId'];
171 if ( !$row->bp_user
) {
175 return new self( $row, false, $flags );
179 * Indicate whether this is known to be saved
182 public function isSaved() {
183 return $this->isSaved
;
187 * Get the central user ID
190 public function getUserCentralId() {
191 return $this->centralId
;
198 public function getAppId() {
206 public function getToken() {
211 * Get the restrictions
212 * @return MWRestrictions
214 public function getRestrictions() {
215 return $this->restrictions
;
222 public function getGrants() {
223 return $this->grants
;
227 * Get the separator for combined user name + app ID
230 public static function getSeparator() {
231 global $wgUserrightsInterwikiDelimiter;
232 return $wgUserrightsInterwikiDelimiter;
239 protected function getPassword() {
240 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->flags
);
241 $db = self
::getDB( $index );
242 $password = $db->selectField(
245 [ 'bp_user' => $this->centralId
, 'bp_app_id' => $this->appId
],
249 if ( $password === false ) {
250 return PasswordFactory
::newInvalidPassword();
253 $passwordFactory = MediaWikiServices
::getInstance()->getPasswordFactory();
255 return $passwordFactory->newFromCiphertext( $password );
256 } catch ( PasswordError
$ex ) {
257 return PasswordFactory
::newInvalidPassword();
262 * Whether the password is currently invalid
266 public function isInvalid() {
267 return $this->getPassword() instanceof InvalidPassword
;
271 * Save the BotPassword to the database
272 * @param string $operation 'update' or 'insert'
273 * @param Password|null $password Password to set.
274 * @return bool Success
276 public function save( $operation, Password
$password = null ) {
278 'bp_user' => $this->centralId
,
279 'bp_app_id' => $this->appId
,
282 'bp_token' => MWCryptRand
::generateHex( User
::TOKEN_LENGTH
),
283 'bp_restrictions' => $this->restrictions
->toJson(),
284 'bp_grants' => FormatJson
::encode( $this->grants
),
287 if ( $password !== null ) {
288 $fields['bp_password'] = $password->toString();
289 } elseif ( $operation === 'insert' ) {
290 $fields['bp_password'] = PasswordFactory
::newInvalidPassword()->toString();
293 $dbw = self
::getDB( DB_MASTER
);
294 switch ( $operation ) {
296 $dbw->insert( 'bot_passwords', $fields +
$conds, __METHOD__
, [ 'IGNORE' ] );
300 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__
);
306 $ok = (bool)$dbw->affectedRows();
308 $this->token
= $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__
);
309 $this->isSaved
= true;
315 * Delete the BotPassword from the database
316 * @return bool Success
318 public function delete() {
320 'bp_user' => $this->centralId
,
321 'bp_app_id' => $this->appId
,
323 $dbw = self
::getDB( DB_MASTER
);
324 $dbw->delete( 'bot_passwords', $conds, __METHOD__
);
325 $ok = (bool)$dbw->affectedRows();
327 $this->token
= '**unsaved**';
328 $this->isSaved
= false;
334 * Invalidate all passwords for a user, by name
335 * @param string $username User name
336 * @return bool Whether any passwords were invalidated
338 public static function invalidateAllPasswordsForUser( $username ) {
339 $centralId = CentralIdLookup
::factory()->centralIdFromName(
340 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
342 return $centralId && self
::invalidateAllPasswordsForCentralId( $centralId );
346 * Invalidate all passwords for a user, by central ID
347 * @param int $centralId
348 * @return bool Whether any passwords were invalidated
350 public static function invalidateAllPasswordsForCentralId( $centralId ) {
351 global $wgEnableBotPasswords;
353 if ( !$wgEnableBotPasswords ) {
357 $dbw = self
::getDB( DB_MASTER
);
360 [ 'bp_password' => PasswordFactory
::newInvalidPassword()->toString() ],
361 [ 'bp_user' => $centralId ],
364 return (bool)$dbw->affectedRows();
368 * Remove all passwords for a user, by name
369 * @param string $username User name
370 * @return bool Whether any passwords were removed
372 public static function removeAllPasswordsForUser( $username ) {
373 $centralId = CentralIdLookup
::factory()->centralIdFromName(
374 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
376 return $centralId && self
::removeAllPasswordsForCentralId( $centralId );
380 * Remove all passwords for a user, by central ID
381 * @param int $centralId
382 * @return bool Whether any passwords were removed
384 public static function removeAllPasswordsForCentralId( $centralId ) {
385 global $wgEnableBotPasswords;
387 if ( !$wgEnableBotPasswords ) {
391 $dbw = self
::getDB( DB_MASTER
);
394 [ 'bp_user' => $centralId ],
397 return (bool)$dbw->affectedRows();
401 * Returns a (raw, unhashed) random password string.
402 * @param Config $config
405 public static function generatePassword( $config ) {
406 return PasswordFactory
::generateRandomPasswordString(
407 max( 32, $config->get( 'MinimalPasswordLength' ) ) );
411 * There are two ways to login with a bot password: "username@appId", "password" and
412 * "username", "appId@password". Transform it so it is always in the first form.
413 * Returns [bot username, bot password, could be normal password?] where the last one is a flag
414 * meaning this could either be a bot password or a normal password, it cannot be decided for
415 * certain (although in such cases it almost always will be a bot password).
416 * If this cannot be a bot password login just return false.
417 * @param string $username
418 * @param string $password
419 * @return array|false
421 public static function canonicalizeLoginData( $username, $password ) {
422 $sep = self
::getSeparator();
423 // the strlen check helps minimize the password information obtainable from timing
424 if ( strlen( $password ) >= 32 && strpos( $username, $sep ) !== false ) {
425 // the separator is not valid in new usernames but might appear in legacy ones
426 if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
427 return [ $username, $password, true ];
429 } elseif ( strlen( $password ) > 32 && strpos( $password, $sep ) !== false ) {
430 $segments = explode( $sep, $password );
431 $password = array_pop( $segments );
432 $appId = implode( $sep, $segments );
433 if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
434 return [ $username . $sep . $appId, $password, true ];
441 * Try to log the user in
442 * @param string $username Combined user name and app ID
443 * @param string $password Supplied password
444 * @param WebRequest $request
445 * @return Status On success, the good status's value is the new Session object
447 public static function login( $username, $password, WebRequest
$request ) {
448 global $wgEnableBotPasswords, $wgPasswordAttemptThrottle;
450 if ( !$wgEnableBotPasswords ) {
451 return Status
::newFatal( 'botpasswords-disabled' );
454 $manager = MediaWiki\Session\SessionManager
::singleton();
455 $provider = $manager->getProvider( BotPasswordSessionProvider
::class );
457 return Status
::newFatal( 'botpasswords-no-provider' );
460 // Split name into name+appId
461 $sep = self
::getSeparator();
462 if ( strpos( $username, $sep ) === false ) {
463 return Status
::newFatal( 'botpasswords-invalid-name', $sep );
465 list( $name, $appId ) = explode( $sep, $username, 2 );
467 // Find the named user
468 $user = User
::newFromName( $name );
469 if ( !$user ||
$user->isAnon() ) {
470 return Status
::newFatal( 'nosuchuser', $name );
475 if ( !empty( $wgPasswordAttemptThrottle ) ) {
476 $throttle = new MediaWiki\Auth\
Throttler( $wgPasswordAttemptThrottle, [
477 'type' => 'botpassword',
478 'cache' => ObjectCache
::getLocalClusterInstance(),
480 $result = $throttle->increase( $user->getName(), $request->getIP(), __METHOD__
);
482 $msg = wfMessage( 'login-throttled' )->durationParams( $result['wait'] );
483 return Status
::newFatal( $msg );
487 // Get the bot password
488 $bp = self
::newFromUser( $user, $appId );
490 return Status
::newFatal( 'botpasswords-not-exist', $name, $appId );
493 // Check restrictions
494 $status = $bp->getRestrictions()->check( $request );
495 if ( !$status->isOK() ) {
496 return Status
::newFatal( 'botpasswords-restriction-failed' );
499 // Check the password
500 $passwordObj = $bp->getPassword();
501 if ( $passwordObj instanceof InvalidPassword
) {
502 return Status
::newFatal( 'botpasswords-needs-reset', $name, $appId );
504 if ( !$passwordObj->equals( $password ) ) {
505 return Status
::newFatal( 'wrongpassword' );
508 // Ok! Create the session.
510 $throttle->clear( $user->getName(), $request->getIP() );
512 return Status
::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );