f102d49c3b9108e88d5a5584d24e9b3a907535cd
[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 * 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
269 */
270 public function save( $operation, Password $password = null ) {
271 $conds = [
272 'bp_user' => $this->centralId,
273 'bp_app_id' => $this->appId,
274 ];
275 $fields = [
276 'bp_token' => MWCryptRand::generateHex( User::TOKEN_LENGTH ),
277 'bp_restrictions' => $this->restrictions->toJson(),
278 'bp_grants' => FormatJson::encode( $this->grants ),
279 ];
280
281 if ( $password !== null ) {
282 $fields['bp_password'] = $password->toString();
283 } elseif ( $operation === 'insert' ) {
284 $fields['bp_password'] = PasswordFactory::newInvalidPassword()->toString();
285 }
286
287 $dbw = self::getDB( DB_MASTER );
288 switch ( $operation ) {
289 case 'insert':
290 $dbw->insert( 'bot_passwords', $fields + $conds, __METHOD__, [ 'IGNORE' ] );
291 break;
292
293 case 'update':
294 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__ );
295 break;
296
297 default:
298 return false;
299 }
300 $ok = (bool)$dbw->affectedRows();
301 if ( $ok ) {
302 $this->token = $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__ );
303 $this->isSaved = true;
304 }
305 return $ok;
306 }
307
308 /**
309 * Delete the BotPassword from the database
310 * @return bool Success
311 */
312 public function delete() {
313 $conds = [
314 'bp_user' => $this->centralId,
315 'bp_app_id' => $this->appId,
316 ];
317 $dbw = self::getDB( DB_MASTER );
318 $dbw->delete( 'bot_passwords', $conds, __METHOD__ );
319 $ok = (bool)$dbw->affectedRows();
320 if ( $ok ) {
321 $this->token = '**unsaved**';
322 $this->isSaved = false;
323 }
324 return $ok;
325 }
326
327 /**
328 * Invalidate all passwords for a user, by name
329 * @param string $username User name
330 * @return bool Whether any passwords were invalidated
331 */
332 public static function invalidateAllPasswordsForUser( $username ) {
333 $centralId = CentralIdLookup::factory()->centralIdFromName(
334 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
335 );
336 return $centralId && self::invalidateAllPasswordsForCentralId( $centralId );
337 }
338
339 /**
340 * Invalidate all passwords for a user, by central ID
341 * @param int $centralId
342 * @return bool Whether any passwords were invalidated
343 */
344 public static function invalidateAllPasswordsForCentralId( $centralId ) {
345 global $wgEnableBotPasswords;
346
347 if ( !$wgEnableBotPasswords ) {
348 return false;
349 }
350
351 $dbw = self::getDB( DB_MASTER );
352 $dbw->update(
353 'bot_passwords',
354 [ 'bp_password' => PasswordFactory::newInvalidPassword()->toString() ],
355 [ 'bp_user' => $centralId ],
356 __METHOD__
357 );
358 return (bool)$dbw->affectedRows();
359 }
360
361 /**
362 * Remove all passwords for a user, by name
363 * @param string $username User name
364 * @return bool Whether any passwords were removed
365 */
366 public static function removeAllPasswordsForUser( $username ) {
367 $centralId = CentralIdLookup::factory()->centralIdFromName(
368 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
369 );
370 return $centralId && self::removeAllPasswordsForCentralId( $centralId );
371 }
372
373 /**
374 * Remove all passwords for a user, by central ID
375 * @param int $centralId
376 * @return bool Whether any passwords were removed
377 */
378 public static function removeAllPasswordsForCentralId( $centralId ) {
379 global $wgEnableBotPasswords;
380
381 if ( !$wgEnableBotPasswords ) {
382 return false;
383 }
384
385 $dbw = self::getDB( DB_MASTER );
386 $dbw->delete(
387 'bot_passwords',
388 [ 'bp_user' => $centralId ],
389 __METHOD__
390 );
391 return (bool)$dbw->affectedRows();
392 }
393
394 /**
395 * Returns a (raw, unhashed) random password string.
396 * @param Config $config
397 * @return string
398 */
399 public static function generatePassword( $config ) {
400 return PasswordFactory::generateRandomPasswordString(
401 max( 32, $config->get( 'MinimalPasswordLength' ) ) );
402 }
403
404 /**
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
414 */
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 ];
422 }
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 ];
429 }
430 }
431 return false;
432 }
433
434 /**
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
440 */
441 public static function login( $username, $password, WebRequest $request ) {
442 global $wgEnableBotPasswords, $wgPasswordAttemptThrottle;
443
444 if ( !$wgEnableBotPasswords ) {
445 return Status::newFatal( 'botpasswords-disabled' );
446 }
447
448 $manager = MediaWiki\Session\SessionManager::singleton();
449 $provider = $manager->getProvider( BotPasswordSessionProvider::class );
450 if ( !$provider ) {
451 return Status::newFatal( 'botpasswords-no-provider' );
452 }
453
454 // Split name into name+appId
455 $sep = self::getSeparator();
456 if ( strpos( $username, $sep ) === false ) {
457 return Status::newFatal( 'botpasswords-invalid-name', $sep );
458 }
459 list( $name, $appId ) = explode( $sep, $username, 2 );
460
461 // Find the named user
462 $user = User::newFromName( $name );
463 if ( !$user || $user->isAnon() ) {
464 return Status::newFatal( 'nosuchuser', $name );
465 }
466
467 // Throttle
468 $throttle = null;
469 if ( !empty( $wgPasswordAttemptThrottle ) ) {
470 $throttle = new MediaWiki\Auth\Throttler( $wgPasswordAttemptThrottle, [
471 'type' => 'botpassword',
472 'cache' => ObjectCache::getLocalClusterInstance(),
473 ] );
474 $result = $throttle->increase( $user->getName(), $request->getIP(), __METHOD__ );
475 if ( $result ) {
476 $msg = wfMessage( 'login-throttled' )->durationParams( $result['wait'] );
477 return Status::newFatal( $msg );
478 }
479 }
480
481 // Get the bot password
482 $bp = self::newFromUser( $user, $appId );
483 if ( !$bp ) {
484 return Status::newFatal( 'botpasswords-not-exist', $name, $appId );
485 }
486
487 // Check restrictions
488 $status = $bp->getRestrictions()->check( $request );
489 if ( !$status->isOK() ) {
490 return Status::newFatal( 'botpasswords-restriction-failed' );
491 }
492
493 // Check the password
494 if ( !$bp->getPassword()->equals( $password ) ) {
495 return Status::newFatal( 'wrongpassword' );
496 }
497
498 // Ok! Create the session.
499 if ( $throttle ) {
500 $throttle->clear( $user->getName(), $request->getIP() );
501 }
502 return Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );
503 }
504 }