6b8153cde44e1f31a8aa12a13ae453a436810611
[lhc/web/wiklou.git] / includes / user / BotPassword.php
1 <?php
2 /**
3 * Utility class for bot passwords
4 *
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.
9 *
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.
14 *
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
19 */
20
21 use MediaWiki\MediaWikiServices;
22 use MediaWiki\Session\BotPasswordSessionProvider;
23 use Wikimedia\Rdbms\IMaintainableDatabase;
24
25 /**
26 * Utility class for bot passwords
27 * @since 1.27
28 */
29 class BotPassword implements IDBAccessObject {
30
31 const APPID_MAXLENGTH = 32;
32
33 /** @var bool */
34 private $isSaved;
35
36 /** @var int */
37 private $centralId;
38
39 /** @var string */
40 private $appId;
41
42 /** @var string */
43 private $token;
44
45 /** @var MWRestrictions */
46 private $restrictions;
47
48 /** @var string[] */
49 private $grants;
50
51 /** @var int */
52 private $flags = self::READ_NORMAL;
53
54 /**
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
58 */
59 protected function __construct( $row, $isSaved, $flags = self::READ_NORMAL ) {
60 $this->isSaved = $isSaved;
61 $this->flags = $flags;
62
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 );
68 }
69
70 /**
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
74 */
75 public static function getDB( $db ) {
76 global $wgBotPasswordsCluster, $wgBotPasswordsDatabase;
77
78 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
79 $lb = $wgBotPasswordsCluster
80 ? $lbFactory->getExternalLB( $wgBotPasswordsCluster )
81 : $lbFactory->getMainLB( $wgBotPasswordsDatabase );
82 return $lb->getConnectionRef( $db, [], $wgBotPasswordsDatabase );
83 }
84
85 /**
86 * Load a BotPassword from the database
87 * @param User $user
88 * @param string $appId
89 * @param int $flags IDBAccessObject read flags
90 * @return BotPassword|null
91 */
92 public static function newFromUser( User $user, $appId, $flags = self::READ_NORMAL ) {
93 $centralId = CentralIdLookup::factory()->centralIdFromLocalUser(
94 $user, CentralIdLookup::AUDIENCE_RAW, $flags
95 );
96 return $centralId ? self::newFromCentralId( $centralId, $appId, $flags ) : null;
97 }
98
99 /**
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
105 */
106 public static function newFromCentralId( $centralId, $appId, $flags = self::READ_NORMAL ) {
107 global $wgEnableBotPasswords;
108
109 if ( !$wgEnableBotPasswords ) {
110 return null;
111 }
112
113 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
114 $db = self::getDB( $index );
115 $row = $db->selectRow(
116 'bot_passwords',
117 [ 'bp_user', 'bp_app_id', 'bp_token', 'bp_restrictions', 'bp_grants' ],
118 [ 'bp_user' => $centralId, 'bp_app_id' => $appId ],
119 __METHOD__,
120 $options
121 );
122 return $row ? new self( $row, true, $flags ) : null;
123 }
124
125 /**
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
136 */
137 public static function newUnsaved( array $data, $flags = self::READ_NORMAL ) {
138 $row = (object)[
139 'bp_user' => 0,
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'] : [],
146 ];
147
148 if (
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 )
152 ) {
153 return null;
154 }
155
156 $row->bp_restrictions = $row->bp_restrictions->toJson();
157 $row->bp_grants = FormatJson::encode( $row->bp_grants );
158
159 if ( isset( $data['user'] ) ) {
160 if ( !$data['user'] instanceof User ) {
161 return null;
162 }
163 $row->bp_user = CentralIdLookup::factory()->centralIdFromLocalUser(
164 $data['user'], CentralIdLookup::AUDIENCE_RAW, $flags
165 );
166 } elseif ( isset( $data['username'] ) ) {
167 $row->bp_user = CentralIdLookup::factory()->centralIdFromName(
168 $data['username'], CentralIdLookup::AUDIENCE_RAW, $flags
169 );
170 } elseif ( isset( $data['centralId'] ) ) {
171 $row->bp_user = $data['centralId'];
172 }
173 if ( !$row->bp_user ) {
174 return null;
175 }
176
177 return new self( $row, false, $flags );
178 }
179
180 /**
181 * Indicate whether this is known to be saved
182 * @return bool
183 */
184 public function isSaved() {
185 return $this->isSaved;
186 }
187
188 /**
189 * Get the central user ID
190 * @return int
191 */
192 public function getUserCentralId() {
193 return $this->centralId;
194 }
195
196 /**
197 * Get the app ID
198 * @return string
199 */
200 public function getAppId() {
201 return $this->appId;
202 }
203
204 /**
205 * Get the token
206 * @return string
207 */
208 public function getToken() {
209 return $this->token;
210 }
211
212 /**
213 * Get the restrictions
214 * @return MWRestrictions
215 */
216 public function getRestrictions() {
217 return $this->restrictions;
218 }
219
220 /**
221 * Get the grants
222 * @return string[]
223 */
224 public function getGrants() {
225 return $this->grants;
226 }
227
228 /**
229 * Get the separator for combined user name + app ID
230 * @return string
231 */
232 public static function getSeparator() {
233 global $wgUserrightsInterwikiDelimiter;
234 return $wgUserrightsInterwikiDelimiter;
235 }
236
237 /**
238 * Get the password
239 * @return Password
240 */
241 protected function getPassword() {
242 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $this->flags );
243 $db = self::getDB( $index );
244 $password = $db->selectField(
245 'bot_passwords',
246 'bp_password',
247 [ 'bp_user' => $this->centralId, 'bp_app_id' => $this->appId ],
248 __METHOD__,
249 $options
250 );
251 if ( $password === false ) {
252 return PasswordFactory::newInvalidPassword();
253 }
254
255 $passwordFactory = new \PasswordFactory();
256 $passwordFactory->init( \RequestContext::getMain()->getConfig() );
257 try {
258 return $passwordFactory->newFromCiphertext( $password );
259 } catch ( PasswordError $ex ) {
260 return PasswordFactory::newInvalidPassword();
261 }
262 }
263
264 /**
265 * Whether the password is currently invalid
266 * @since 1.32
267 * @return bool
268 */
269 public function isInvalid() {
270 return $this->getPassword() instanceof InvalidPassword;
271 }
272
273 /**
274 * Save the BotPassword to the database
275 * @param string $operation 'update' or 'insert'
276 * @param Password|null $password Password to set.
277 * @return bool Success
278 */
279 public function save( $operation, Password $password = null ) {
280 $conds = [
281 'bp_user' => $this->centralId,
282 'bp_app_id' => $this->appId,
283 ];
284 $fields = [
285 'bp_token' => MWCryptRand::generateHex( User::TOKEN_LENGTH ),
286 'bp_restrictions' => $this->restrictions->toJson(),
287 'bp_grants' => FormatJson::encode( $this->grants ),
288 ];
289
290 if ( $password !== null ) {
291 $fields['bp_password'] = $password->toString();
292 } elseif ( $operation === 'insert' ) {
293 $fields['bp_password'] = PasswordFactory::newInvalidPassword()->toString();
294 }
295
296 $dbw = self::getDB( DB_MASTER );
297 switch ( $operation ) {
298 case 'insert':
299 $dbw->insert( 'bot_passwords', $fields + $conds, __METHOD__, [ 'IGNORE' ] );
300 break;
301
302 case 'update':
303 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__ );
304 break;
305
306 default:
307 return false;
308 }
309 $ok = (bool)$dbw->affectedRows();
310 if ( $ok ) {
311 $this->token = $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__ );
312 $this->isSaved = true;
313 }
314 return $ok;
315 }
316
317 /**
318 * Delete the BotPassword from the database
319 * @return bool Success
320 */
321 public function delete() {
322 $conds = [
323 'bp_user' => $this->centralId,
324 'bp_app_id' => $this->appId,
325 ];
326 $dbw = self::getDB( DB_MASTER );
327 $dbw->delete( 'bot_passwords', $conds, __METHOD__ );
328 $ok = (bool)$dbw->affectedRows();
329 if ( $ok ) {
330 $this->token = '**unsaved**';
331 $this->isSaved = false;
332 }
333 return $ok;
334 }
335
336 /**
337 * Invalidate all passwords for a user, by name
338 * @param string $username User name
339 * @return bool Whether any passwords were invalidated
340 */
341 public static function invalidateAllPasswordsForUser( $username ) {
342 $centralId = CentralIdLookup::factory()->centralIdFromName(
343 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
344 );
345 return $centralId && self::invalidateAllPasswordsForCentralId( $centralId );
346 }
347
348 /**
349 * Invalidate all passwords for a user, by central ID
350 * @param int $centralId
351 * @return bool Whether any passwords were invalidated
352 */
353 public static function invalidateAllPasswordsForCentralId( $centralId ) {
354 global $wgEnableBotPasswords;
355
356 if ( !$wgEnableBotPasswords ) {
357 return false;
358 }
359
360 $dbw = self::getDB( DB_MASTER );
361 $dbw->update(
362 'bot_passwords',
363 [ 'bp_password' => PasswordFactory::newInvalidPassword()->toString() ],
364 [ 'bp_user' => $centralId ],
365 __METHOD__
366 );
367 return (bool)$dbw->affectedRows();
368 }
369
370 /**
371 * Remove all passwords for a user, by name
372 * @param string $username User name
373 * @return bool Whether any passwords were removed
374 */
375 public static function removeAllPasswordsForUser( $username ) {
376 $centralId = CentralIdLookup::factory()->centralIdFromName(
377 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
378 );
379 return $centralId && self::removeAllPasswordsForCentralId( $centralId );
380 }
381
382 /**
383 * Remove all passwords for a user, by central ID
384 * @param int $centralId
385 * @return bool Whether any passwords were removed
386 */
387 public static function removeAllPasswordsForCentralId( $centralId ) {
388 global $wgEnableBotPasswords;
389
390 if ( !$wgEnableBotPasswords ) {
391 return false;
392 }
393
394 $dbw = self::getDB( DB_MASTER );
395 $dbw->delete(
396 'bot_passwords',
397 [ 'bp_user' => $centralId ],
398 __METHOD__
399 );
400 return (bool)$dbw->affectedRows();
401 }
402
403 /**
404 * Returns a (raw, unhashed) random password string.
405 * @param Config $config
406 * @return string
407 */
408 public static function generatePassword( $config ) {
409 return PasswordFactory::generateRandomPasswordString(
410 max( 32, $config->get( 'MinimalPasswordLength' ) ) );
411 }
412
413 /**
414 * There are two ways to login with a bot password: "username@appId", "password" and
415 * "username", "appId@password". Transform it so it is always in the first form.
416 * Returns [bot username, bot password, could be normal password?] where the last one is a flag
417 * meaning this could either be a bot password or a normal password, it cannot be decided for
418 * certain (although in such cases it almost always will be a bot password).
419 * If this cannot be a bot password login just return false.
420 * @param string $username
421 * @param string $password
422 * @return array|false
423 */
424 public static function canonicalizeLoginData( $username, $password ) {
425 $sep = self::getSeparator();
426 // the strlen check helps minimize the password information obtainable from timing
427 if ( strlen( $password ) >= 32 && strpos( $username, $sep ) !== false ) {
428 // the separator is not valid in new usernames but might appear in legacy ones
429 if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
430 return [ $username, $password, true ];
431 }
432 } elseif ( strlen( $password ) > 32 && strpos( $password, $sep ) !== false ) {
433 $segments = explode( $sep, $password );
434 $password = array_pop( $segments );
435 $appId = implode( $sep, $segments );
436 if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
437 return [ $username . $sep . $appId, $password, true ];
438 }
439 }
440 return false;
441 }
442
443 /**
444 * Try to log the user in
445 * @param string $username Combined user name and app ID
446 * @param string $password Supplied password
447 * @param WebRequest $request
448 * @return Status On success, the good status's value is the new Session object
449 */
450 public static function login( $username, $password, WebRequest $request ) {
451 global $wgEnableBotPasswords, $wgPasswordAttemptThrottle;
452
453 if ( !$wgEnableBotPasswords ) {
454 return Status::newFatal( 'botpasswords-disabled' );
455 }
456
457 $manager = MediaWiki\Session\SessionManager::singleton();
458 $provider = $manager->getProvider( BotPasswordSessionProvider::class );
459 if ( !$provider ) {
460 return Status::newFatal( 'botpasswords-no-provider' );
461 }
462
463 // Split name into name+appId
464 $sep = self::getSeparator();
465 if ( strpos( $username, $sep ) === false ) {
466 return Status::newFatal( 'botpasswords-invalid-name', $sep );
467 }
468 list( $name, $appId ) = explode( $sep, $username, 2 );
469
470 // Find the named user
471 $user = User::newFromName( $name );
472 if ( !$user || $user->isAnon() ) {
473 return Status::newFatal( 'nosuchuser', $name );
474 }
475
476 // Throttle
477 $throttle = null;
478 if ( !empty( $wgPasswordAttemptThrottle ) ) {
479 $throttle = new MediaWiki\Auth\Throttler( $wgPasswordAttemptThrottle, [
480 'type' => 'botpassword',
481 'cache' => ObjectCache::getLocalClusterInstance(),
482 ] );
483 $result = $throttle->increase( $user->getName(), $request->getIP(), __METHOD__ );
484 if ( $result ) {
485 $msg = wfMessage( 'login-throttled' )->durationParams( $result['wait'] );
486 return Status::newFatal( $msg );
487 }
488 }
489
490 // Get the bot password
491 $bp = self::newFromUser( $user, $appId );
492 if ( !$bp ) {
493 return Status::newFatal( 'botpasswords-not-exist', $name, $appId );
494 }
495
496 // Check restrictions
497 $status = $bp->getRestrictions()->check( $request );
498 if ( !$status->isOK() ) {
499 return Status::newFatal( 'botpasswords-restriction-failed' );
500 }
501
502 // Check the password
503 $passwordObj = $bp->getPassword();
504 if ( $passwordObj instanceof InvalidPassword ) {
505 return Status::newFatal( 'botpasswords-needs-reset', $name, $appId );
506 }
507 if ( !$passwordObj->equals( $password ) ) {
508 return Status::newFatal( 'wrongpassword' );
509 }
510
511 // Ok! Create the session.
512 if ( $throttle ) {
513 $throttle->clear( $user->getName(), $request->getIP() );
514 }
515 return Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );
516 }
517 }