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' => isset( $data['restrictions'] )
143 ?
$data['restrictions']
144 : MWRestrictions
::newDefault(),
145 'bp_grants' => isset( $data['grants'] ) ?
$data['grants'] : [],
149 $row->bp_app_id
=== '' ||
strlen( $row->bp_app_id
) > self
::APPID_MAXLENGTH ||
150 !$row->bp_restrictions
instanceof MWRestrictions ||
151 !is_array( $row->bp_grants
)
156 $row->bp_restrictions
= $row->bp_restrictions
->toJson();
157 $row->bp_grants
= FormatJson
::encode( $row->bp_grants
);
159 if ( isset( $data['user'] ) ) {
160 if ( !$data['user'] instanceof User
) {
163 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromLocalUser(
164 $data['user'], CentralIdLookup
::AUDIENCE_RAW
, $flags
166 } elseif ( isset( $data['username'] ) ) {
167 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromName(
168 $data['username'], CentralIdLookup
::AUDIENCE_RAW
, $flags
170 } elseif ( isset( $data['centralId'] ) ) {
171 $row->bp_user
= $data['centralId'];
173 if ( !$row->bp_user
) {
177 return new self( $row, false, $flags );
181 * Indicate whether this is known to be saved
184 public function isSaved() {
185 return $this->isSaved
;
189 * Get the central user ID
192 public function getUserCentralId() {
193 return $this->centralId
;
200 public function getAppId() {
208 public function getToken() {
213 * Get the restrictions
214 * @return MWRestrictions
216 public function getRestrictions() {
217 return $this->restrictions
;
224 public function getGrants() {
225 return $this->grants
;
229 * Get the separator for combined user name + app ID
232 public static function getSeparator() {
233 global $wgUserrightsInterwikiDelimiter;
234 return $wgUserrightsInterwikiDelimiter;
241 protected function getPassword() {
242 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->flags
);
243 $db = self
::getDB( $index );
244 $password = $db->selectField(
247 [ 'bp_user' => $this->centralId
, 'bp_app_id' => $this->appId
],
251 if ( $password === false ) {
252 return PasswordFactory
::newInvalidPassword();
255 $passwordFactory = new \
PasswordFactory();
256 $passwordFactory->init( \RequestContext
::getMain()->getConfig() );
258 return $passwordFactory->newFromCiphertext( $password );
259 } catch ( PasswordError
$ex ) {
260 return PasswordFactory
::newInvalidPassword();
265 * Save the BotPassword to the database
266 * @param string $operation 'update' or 'insert'
267 * @param Password|null $password Password to set.
268 * @return bool Success
270 public function save( $operation, Password
$password = null ) {
272 'bp_user' => $this->centralId
,
273 'bp_app_id' => $this->appId
,
276 'bp_token' => MWCryptRand
::generateHex( User
::TOKEN_LENGTH
),
277 'bp_restrictions' => $this->restrictions
->toJson(),
278 'bp_grants' => FormatJson
::encode( $this->grants
),
281 if ( $password !== null ) {
282 $fields['bp_password'] = $password->toString();
283 } elseif ( $operation === 'insert' ) {
284 $fields['bp_password'] = PasswordFactory
::newInvalidPassword()->toString();
287 $dbw = self
::getDB( DB_MASTER
);
288 switch ( $operation ) {
290 $dbw->insert( 'bot_passwords', $fields +
$conds, __METHOD__
, [ 'IGNORE' ] );
294 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__
);
300 $ok = (bool)$dbw->affectedRows();
302 $this->token
= $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__
);
303 $this->isSaved
= true;
309 * Delete the BotPassword from the database
310 * @return bool Success
312 public function delete() {
314 'bp_user' => $this->centralId
,
315 'bp_app_id' => $this->appId
,
317 $dbw = self
::getDB( DB_MASTER
);
318 $dbw->delete( 'bot_passwords', $conds, __METHOD__
);
319 $ok = (bool)$dbw->affectedRows();
321 $this->token
= '**unsaved**';
322 $this->isSaved
= false;
328 * Invalidate all passwords for a user, by name
329 * @param string $username User name
330 * @return bool Whether any passwords were invalidated
332 public static function invalidateAllPasswordsForUser( $username ) {
333 $centralId = CentralIdLookup
::factory()->centralIdFromName(
334 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
336 return $centralId && self
::invalidateAllPasswordsForCentralId( $centralId );
340 * Invalidate all passwords for a user, by central ID
341 * @param int $centralId
342 * @return bool Whether any passwords were invalidated
344 public static function invalidateAllPasswordsForCentralId( $centralId ) {
345 global $wgEnableBotPasswords;
347 if ( !$wgEnableBotPasswords ) {
351 $dbw = self
::getDB( DB_MASTER
);
354 [ 'bp_password' => PasswordFactory
::newInvalidPassword()->toString() ],
355 [ 'bp_user' => $centralId ],
358 return (bool)$dbw->affectedRows();
362 * Remove all passwords for a user, by name
363 * @param string $username User name
364 * @return bool Whether any passwords were removed
366 public static function removeAllPasswordsForUser( $username ) {
367 $centralId = CentralIdLookup
::factory()->centralIdFromName(
368 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
370 return $centralId && self
::removeAllPasswordsForCentralId( $centralId );
374 * Remove all passwords for a user, by central ID
375 * @param int $centralId
376 * @return bool Whether any passwords were removed
378 public static function removeAllPasswordsForCentralId( $centralId ) {
379 global $wgEnableBotPasswords;
381 if ( !$wgEnableBotPasswords ) {
385 $dbw = self
::getDB( DB_MASTER
);
388 [ 'bp_user' => $centralId ],
391 return (bool)$dbw->affectedRows();
395 * Returns a (raw, unhashed) random password string.
396 * @param Config $config
399 public static function generatePassword( $config ) {
400 return PasswordFactory
::generateRandomPasswordString(
401 max( 32, $config->get( 'MinimalPasswordLength' ) ) );
405 * There are two ways to login with a bot password: "username@appId", "password" and
406 * "username", "appId@password". Transform it so it is always in the first form.
407 * Returns [bot username, bot password, could be normal password?] where the last one is a flag
408 * meaning this could either be a bot password or a normal password, it cannot be decided for
409 * certain (although in such cases it almost always will be a bot password).
410 * If this cannot be a bot password login just return false.
411 * @param string $username
412 * @param string $password
413 * @return array|false
415 public static function canonicalizeLoginData( $username, $password ) {
416 $sep = self
::getSeparator();
417 // the strlen check helps minimize the password information obtainable from timing
418 if ( strlen( $password ) >= 32 && strpos( $username, $sep ) !== false ) {
419 // the separator is not valid in new usernames but might appear in legacy ones
420 if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
421 return [ $username, $password, true ];
423 } elseif ( strlen( $password ) > 32 && strpos( $password, $sep ) !== false ) {
424 $segments = explode( $sep, $password );
425 $password = array_pop( $segments );
426 $appId = implode( $sep, $segments );
427 if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
428 return [ $username . $sep . $appId, $password, true ];
435 * Try to log the user in
436 * @param string $username Combined user name and app ID
437 * @param string $password Supplied password
438 * @param WebRequest $request
439 * @return Status On success, the good status's value is the new Session object
441 public static function login( $username, $password, WebRequest
$request ) {
442 global $wgEnableBotPasswords, $wgPasswordAttemptThrottle;
444 if ( !$wgEnableBotPasswords ) {
445 return Status
::newFatal( 'botpasswords-disabled' );
448 $manager = MediaWiki\Session\SessionManager
::singleton();
449 $provider = $manager->getProvider( BotPasswordSessionProvider
::class );
451 return Status
::newFatal( 'botpasswords-no-provider' );
454 // Split name into name+appId
455 $sep = self
::getSeparator();
456 if ( strpos( $username, $sep ) === false ) {
457 return Status
::newFatal( 'botpasswords-invalid-name', $sep );
459 list( $name, $appId ) = explode( $sep, $username, 2 );
461 // Find the named user
462 $user = User
::newFromName( $name );
463 if ( !$user ||
$user->isAnon() ) {
464 return Status
::newFatal( 'nosuchuser', $name );
469 if ( !empty( $wgPasswordAttemptThrottle ) ) {
470 $throttle = new MediaWiki\Auth\
Throttler( $wgPasswordAttemptThrottle, [
471 'type' => 'botpassword',
472 'cache' => ObjectCache
::getLocalClusterInstance(),
474 $result = $throttle->increase( $user->getName(), $request->getIP(), __METHOD__
);
476 $msg = wfMessage( 'login-throttled' )->durationParams( $result['wait'] );
477 return Status
::newFatal( $msg );
481 // Get the bot password
482 $bp = self
::newFromUser( $user, $appId );
484 return Status
::newFatal( 'botpasswords-not-exist', $name, $appId );
487 // Check restrictions
488 $status = $bp->getRestrictions()->check( $request );
489 if ( !$status->isOK() ) {
490 return Status
::newFatal( 'botpasswords-restriction-failed' );
493 // Check the password
494 if ( !$bp->getPassword()->equals( $password ) ) {
495 return Status
::newFatal( 'wrongpassword' );
498 // Ok! Create the session.
500 $throttle->clear( $user->getName(), $request->getIP() );
502 return Status
::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );