123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554 |
- <?php
- /**
- * Utility class for bot passwords
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- * http://www.gnu.org/copyleft/gpl.html
- */
- use MediaWiki\Auth\AuthenticationResponse;
- use MediaWiki\MediaWikiServices;
- use MediaWiki\Session\BotPasswordSessionProvider;
- use Wikimedia\Rdbms\IDatabase;
- /**
- * Utility class for bot passwords
- * @since 1.27
- */
- class BotPassword implements IDBAccessObject {
- const APPID_MAXLENGTH = 32;
- /** @var bool */
- private $isSaved;
- /** @var int */
- private $centralId;
- /** @var string */
- private $appId;
- /** @var string */
- private $token;
- /** @var MWRestrictions */
- private $restrictions;
- /** @var string[] */
- private $grants;
- /** @var int */
- private $flags = self::READ_NORMAL;
- /**
- * @param object $row bot_passwords database row
- * @param bool $isSaved Whether the bot password was read from the database
- * @param int $flags IDBAccessObject read flags
- */
- protected function __construct( $row, $isSaved, $flags = self::READ_NORMAL ) {
- $this->isSaved = $isSaved;
- $this->flags = $flags;
- $this->centralId = (int)$row->bp_user;
- $this->appId = $row->bp_app_id;
- $this->token = $row->bp_token;
- $this->restrictions = MWRestrictions::newFromJson( $row->bp_restrictions );
- $this->grants = FormatJson::decode( $row->bp_grants );
- }
- /**
- * Get a database connection for the bot passwords database
- * @param int $db Index of the connection to get, e.g. DB_MASTER or DB_REPLICA.
- * @return IDatabase
- */
- public static function getDB( $db ) {
- global $wgBotPasswordsCluster, $wgBotPasswordsDatabase;
- $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
- $lb = $wgBotPasswordsCluster
- ? $lbFactory->getExternalLB( $wgBotPasswordsCluster )
- : $lbFactory->getMainLB( $wgBotPasswordsDatabase );
- return $lb->getConnectionRef( $db, [], $wgBotPasswordsDatabase );
- }
- /**
- * Load a BotPassword from the database
- * @param User $user
- * @param string $appId
- * @param int $flags IDBAccessObject read flags
- * @return BotPassword|null
- */
- public static function newFromUser( User $user, $appId, $flags = self::READ_NORMAL ) {
- $centralId = CentralIdLookup::factory()->centralIdFromLocalUser(
- $user, CentralIdLookup::AUDIENCE_RAW, $flags
- );
- return $centralId ? self::newFromCentralId( $centralId, $appId, $flags ) : null;
- }
- /**
- * Load a BotPassword from the database
- * @param int $centralId from CentralIdLookup
- * @param string $appId
- * @param int $flags IDBAccessObject read flags
- * @return BotPassword|null
- */
- public static function newFromCentralId( $centralId, $appId, $flags = self::READ_NORMAL ) {
- global $wgEnableBotPasswords;
- if ( !$wgEnableBotPasswords ) {
- return null;
- }
- list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
- $db = self::getDB( $index );
- $row = $db->selectRow(
- 'bot_passwords',
- [ 'bp_user', 'bp_app_id', 'bp_token', 'bp_restrictions', 'bp_grants' ],
- [ 'bp_user' => $centralId, 'bp_app_id' => $appId ],
- __METHOD__,
- $options
- );
- return $row ? new self( $row, true, $flags ) : null;
- }
- /**
- * Create an unsaved BotPassword
- * @param array $data Data to use to create the bot password. Keys are:
- * - user: (User) User object to create the password for. Overrides username and centralId.
- * - username: (string) Username to create the password for. Overrides centralId.
- * - centralId: (int) User central ID to create the password for.
- * - appId: (string) App ID for the password.
- * - restrictions: (MWRestrictions, optional) Restrictions.
- * - grants: (string[], optional) Grants.
- * @param int $flags IDBAccessObject read flags
- * @return BotPassword|null
- */
- public static function newUnsaved( array $data, $flags = self::READ_NORMAL ) {
- $row = (object)[
- 'bp_user' => 0,
- 'bp_app_id' => isset( $data['appId'] ) ? trim( $data['appId'] ) : '',
- 'bp_token' => '**unsaved**',
- 'bp_restrictions' => $data['restrictions'] ?? MWRestrictions::newDefault(),
- 'bp_grants' => $data['grants'] ?? [],
- ];
- if (
- $row->bp_app_id === '' || strlen( $row->bp_app_id ) > self::APPID_MAXLENGTH ||
- !$row->bp_restrictions instanceof MWRestrictions ||
- !is_array( $row->bp_grants )
- ) {
- return null;
- }
- $row->bp_restrictions = $row->bp_restrictions->toJson();
- $row->bp_grants = FormatJson::encode( $row->bp_grants );
- if ( isset( $data['user'] ) ) {
- if ( !$data['user'] instanceof User ) {
- return null;
- }
- $row->bp_user = CentralIdLookup::factory()->centralIdFromLocalUser(
- $data['user'], CentralIdLookup::AUDIENCE_RAW, $flags
- );
- } elseif ( isset( $data['username'] ) ) {
- $row->bp_user = CentralIdLookup::factory()->centralIdFromName(
- $data['username'], CentralIdLookup::AUDIENCE_RAW, $flags
- );
- } elseif ( isset( $data['centralId'] ) ) {
- $row->bp_user = $data['centralId'];
- }
- if ( !$row->bp_user ) {
- return null;
- }
- return new self( $row, false, $flags );
- }
- /**
- * Indicate whether this is known to be saved
- * @return bool
- */
- public function isSaved() {
- return $this->isSaved;
- }
- /**
- * Get the central user ID
- * @return int
- */
- public function getUserCentralId() {
- return $this->centralId;
- }
- /**
- * Get the app ID
- * @return string
- */
- public function getAppId() {
- return $this->appId;
- }
- /**
- * Get the token
- * @return string
- */
- public function getToken() {
- return $this->token;
- }
- /**
- * Get the restrictions
- * @return MWRestrictions
- */
- public function getRestrictions() {
- return $this->restrictions;
- }
- /**
- * Get the grants
- * @return string[]
- */
- public function getGrants() {
- return $this->grants;
- }
- /**
- * Get the separator for combined user name + app ID
- * @return string
- */
- public static function getSeparator() {
- global $wgUserrightsInterwikiDelimiter;
- return $wgUserrightsInterwikiDelimiter;
- }
- /**
- * Get the password
- * @return Password
- */
- protected function getPassword() {
- list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $this->flags );
- $db = self::getDB( $index );
- $password = $db->selectField(
- 'bot_passwords',
- 'bp_password',
- [ 'bp_user' => $this->centralId, 'bp_app_id' => $this->appId ],
- __METHOD__,
- $options
- );
- if ( $password === false ) {
- return PasswordFactory::newInvalidPassword();
- }
- $passwordFactory = MediaWikiServices::getInstance()->getPasswordFactory();
- try {
- return $passwordFactory->newFromCiphertext( $password );
- } catch ( PasswordError $ex ) {
- return PasswordFactory::newInvalidPassword();
- }
- }
- /**
- * Whether the password is currently invalid
- * @since 1.32
- * @return bool
- */
- public function isInvalid() {
- return $this->getPassword() instanceof InvalidPassword;
- }
- /**
- * Save the BotPassword to the database
- * @param string $operation 'update' or 'insert'
- * @param Password|null $password Password to set.
- * @return bool Success
- */
- public function save( $operation, Password $password = null ) {
- $conds = [
- 'bp_user' => $this->centralId,
- 'bp_app_id' => $this->appId,
- ];
- $fields = [
- 'bp_token' => MWCryptRand::generateHex( User::TOKEN_LENGTH ),
- 'bp_restrictions' => $this->restrictions->toJson(),
- 'bp_grants' => FormatJson::encode( $this->grants ),
- ];
- if ( $password !== null ) {
- $fields['bp_password'] = $password->toString();
- } elseif ( $operation === 'insert' ) {
- $fields['bp_password'] = PasswordFactory::newInvalidPassword()->toString();
- }
- $dbw = self::getDB( DB_MASTER );
- switch ( $operation ) {
- case 'insert':
- $dbw->insert( 'bot_passwords', $fields + $conds, __METHOD__, [ 'IGNORE' ] );
- break;
- case 'update':
- $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__ );
- break;
- default:
- return false;
- }
- $ok = (bool)$dbw->affectedRows();
- if ( $ok ) {
- $this->token = $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__ );
- $this->isSaved = true;
- }
- return $ok;
- }
- /**
- * Delete the BotPassword from the database
- * @return bool Success
- */
- public function delete() {
- $conds = [
- 'bp_user' => $this->centralId,
- 'bp_app_id' => $this->appId,
- ];
- $dbw = self::getDB( DB_MASTER );
- $dbw->delete( 'bot_passwords', $conds, __METHOD__ );
- $ok = (bool)$dbw->affectedRows();
- if ( $ok ) {
- $this->token = '**unsaved**';
- $this->isSaved = false;
- }
- return $ok;
- }
- /**
- * Invalidate all passwords for a user, by name
- * @param string $username User name
- * @return bool Whether any passwords were invalidated
- */
- public static function invalidateAllPasswordsForUser( $username ) {
- $centralId = CentralIdLookup::factory()->centralIdFromName(
- $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
- );
- return $centralId && self::invalidateAllPasswordsForCentralId( $centralId );
- }
- /**
- * Invalidate all passwords for a user, by central ID
- * @param int $centralId
- * @return bool Whether any passwords were invalidated
- */
- public static function invalidateAllPasswordsForCentralId( $centralId ) {
- global $wgEnableBotPasswords;
- if ( !$wgEnableBotPasswords ) {
- return false;
- }
- $dbw = self::getDB( DB_MASTER );
- $dbw->update(
- 'bot_passwords',
- [ 'bp_password' => PasswordFactory::newInvalidPassword()->toString() ],
- [ 'bp_user' => $centralId ],
- __METHOD__
- );
- return (bool)$dbw->affectedRows();
- }
- /**
- * Remove all passwords for a user, by name
- * @param string $username User name
- * @return bool Whether any passwords were removed
- */
- public static function removeAllPasswordsForUser( $username ) {
- $centralId = CentralIdLookup::factory()->centralIdFromName(
- $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
- );
- return $centralId && self::removeAllPasswordsForCentralId( $centralId );
- }
- /**
- * Remove all passwords for a user, by central ID
- * @param int $centralId
- * @return bool Whether any passwords were removed
- */
- public static function removeAllPasswordsForCentralId( $centralId ) {
- global $wgEnableBotPasswords;
- if ( !$wgEnableBotPasswords ) {
- return false;
- }
- $dbw = self::getDB( DB_MASTER );
- $dbw->delete(
- 'bot_passwords',
- [ 'bp_user' => $centralId ],
- __METHOD__
- );
- return (bool)$dbw->affectedRows();
- }
- /**
- * Returns a (raw, unhashed) random password string.
- * @param Config $config
- * @return string
- */
- public static function generatePassword( $config ) {
- return PasswordFactory::generateRandomPasswordString(
- max( 32, $config->get( 'MinimalPasswordLength' ) ) );
- }
- /**
- * There are two ways to login with a bot password: "username@appId", "password" and
- * "username", "appId@password". Transform it so it is always in the first form.
- * Returns [bot username, bot password].
- * If this cannot be a bot password login just return false.
- * @param string $username
- * @param string $password
- * @return array|false
- */
- public static function canonicalizeLoginData( $username, $password ) {
- $sep = self::getSeparator();
- // the strlen check helps minimize the password information obtainable from timing
- if ( strlen( $password ) >= 32 && strpos( $username, $sep ) !== false ) {
- // the separator is not valid in new usernames but might appear in legacy ones
- if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
- return [ $username, $password ];
- }
- } elseif ( strlen( $password ) > 32 && strpos( $password, $sep ) !== false ) {
- $segments = explode( $sep, $password );
- $password = array_pop( $segments );
- $appId = implode( $sep, $segments );
- if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
- return [ $username . $sep . $appId, $password ];
- }
- }
- return false;
- }
- /**
- * Try to log the user in
- * @param string $username Combined user name and app ID
- * @param string $password Supplied password
- * @param WebRequest $request
- * @return Status On success, the good status's value is the new Session object
- */
- public static function login( $username, $password, WebRequest $request ) {
- global $wgEnableBotPasswords, $wgPasswordAttemptThrottle;
- if ( !$wgEnableBotPasswords ) {
- return Status::newFatal( 'botpasswords-disabled' );
- }
- $manager = MediaWiki\Session\SessionManager::singleton();
- $provider = $manager->getProvider( BotPasswordSessionProvider::class );
- if ( !$provider ) {
- return Status::newFatal( 'botpasswords-no-provider' );
- }
- // Split name into name+appId
- $sep = self::getSeparator();
- if ( strpos( $username, $sep ) === false ) {
- return self::loginHook( $username, null, Status::newFatal( 'botpasswords-invalid-name', $sep ) );
- }
- list( $name, $appId ) = explode( $sep, $username, 2 );
- // Find the named user
- $user = User::newFromName( $name );
- if ( !$user || $user->isAnon() ) {
- return self::loginHook( $user ?: $name, null, Status::newFatal( 'nosuchuser', $name ) );
- }
- if ( $user->isLocked() ) {
- return Status::newFatal( 'botpasswords-locked' );
- }
- $throttle = null;
- if ( !empty( $wgPasswordAttemptThrottle ) ) {
- $throttle = new MediaWiki\Auth\Throttler( $wgPasswordAttemptThrottle, [
- 'type' => 'botpassword',
- 'cache' => ObjectCache::getLocalClusterInstance(),
- ] );
- $result = $throttle->increase( $user->getName(), $request->getIP(), __METHOD__ );
- if ( $result ) {
- $msg = wfMessage( 'login-throttled' )->durationParams( $result['wait'] );
- return self::loginHook( $user, null, Status::newFatal( $msg ) );
- }
- }
- // Get the bot password
- $bp = self::newFromUser( $user, $appId );
- if ( !$bp ) {
- return self::loginHook( $user, $bp,
- Status::newFatal( 'botpasswords-not-exist', $name, $appId ) );
- }
- // Check restrictions
- $status = $bp->getRestrictions()->check( $request );
- if ( !$status->isOK() ) {
- return self::loginHook( $user, $bp, Status::newFatal( 'botpasswords-restriction-failed' ) );
- }
- // Check the password
- $passwordObj = $bp->getPassword();
- if ( $passwordObj instanceof InvalidPassword ) {
- return self::loginHook( $user, $bp,
- Status::newFatal( 'botpasswords-needs-reset', $name, $appId ) );
- }
- if ( !$passwordObj->verify( $password ) ) {
- return self::loginHook( $user, $bp, Status::newFatal( 'wrongpassword' ) );
- }
- // Ok! Create the session.
- if ( $throttle ) {
- $throttle->clear( $user->getName(), $request->getIP() );
- }
- return self::loginHook( $user, $bp,
- // @phan-suppress-next-line PhanUndeclaredMethod
- Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) ) );
- }
- /**
- * Call AuthManagerLoginAuthenticateAudit
- *
- * To facilitate logging all authentications, even ones not via
- * AuthManager, call the AuthManagerLoginAuthenticateAudit hook.
- *
- * @param User|string $user User being logged in
- * @param BotPassword|null $bp Bot sub-account, if it can be identified
- * @param Status $status Login status
- * @return Status The passed-in status
- */
- private static function loginHook( $user, $bp, Status $status ) {
- $extraData = [];
- if ( $user instanceof User ) {
- $name = $user->getName();
- if ( $bp ) {
- $extraData['appId'] = $name . self::getSeparator() . $bp->getAppId();
- }
- } else {
- $name = $user;
- $user = null;
- }
- if ( $status->isGood() ) {
- $response = AuthenticationResponse::newPass( $name );
- } else {
- $response = AuthenticationResponse::newFail( $status->getMessage() );
- }
- Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $response, $user, $name, $extraData ] );
- return $status;
- }
- }
|