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