summaryrefslogtreecommitdiff
path: root/www/wiki/includes/user/BotPassword.php
blob: 8074c328f271266d1ec84414bfc18f465464b4dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
<?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\MediaWikiServices;
use MediaWiki\Session\BotPasswordSessionProvider;
use Wikimedia\Rdbms\IMaintainableDatabase;

/**
 * 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 IMaintainableDatabase
	 */
	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' => isset( $data['restrictions'] )
				? $data['restrictions']
				: MWRestrictions::newDefault(),
			'bp_grants' => isset( $data['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 = new \PasswordFactory();
		$passwordFactory->init( \RequestContext::getMain()->getConfig() );
		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, could be normal password?] where the last one is a flag
	 * meaning this could either be a bot password or a normal password, it cannot be decided for
	 * certain (although in such cases it almost always will be a 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, true ];
			}
		} 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, true ];
			}
		}
		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 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 Status::newFatal( 'nosuchuser', $name );
		}

		if ( $user->isLocked() ) {
			return Status::newFatal( 'botpasswords-locked' );
		}

		// Throttle
		$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 Status::newFatal( $msg );
			}
		}

		// Get the bot password
		$bp = self::newFromUser( $user, $appId );
		if ( !$bp ) {
			return Status::newFatal( 'botpasswords-not-exist', $name, $appId );
		}

		// Check restrictions
		$status = $bp->getRestrictions()->check( $request );
		if ( !$status->isOK() ) {
			return Status::newFatal( 'botpasswords-restriction-failed' );
		}

		// Check the password
		$passwordObj = $bp->getPassword();
		if ( $passwordObj instanceof InvalidPassword ) {
			return Status::newFatal( 'botpasswords-needs-reset', $name, $appId );
		}
		if ( !$passwordObj->equals( $password ) ) {
			return Status::newFatal( 'wrongpassword' );
		}

		// Ok! Create the session.
		if ( $throttle ) {
			$throttle->clear( $user->getName(), $request->getIP() );
		}
		return Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );
	}
}