Debian Codegraph @

extensions/LoginNotify/includes/LoginNotify.php

raw symbols SCIP
1 <?php
2 /**
3 * Body of LoginNotify extension
4 *
5 * @file
6 * @ingroup Extensions
7 */
8
9 namespace LoginNotify;
10
11 use JobQueueGroup;
12 use JobSpecification;
13 use LogicException;
14 use MediaWiki\Auth\AuthManager;
15 use MediaWiki\Config\ServiceOptions;
16 use MediaWiki\Extension\CentralAuth\User\CentralAuthUser;
17 use MediaWiki\Extension\Notifications\Model\Event;
18 use MediaWiki\MediaWikiServices;
19 use MediaWiki\Registration\ExtensionRegistry;
20 use MediaWiki\Request\WebRequest;
21 use MediaWiki\User\CentralId\CentralIdLookup;
22 use MediaWiki\User\User;
23 use MediaWiki\WikiMap\WikiMap;
24 use MWCryptRand;
25 use Psr\Log\LoggerAwareInterface;
26 use Psr\Log\LoggerInterface;
27 use UnexpectedValueException;
28 use Wikimedia\Assert\Assert;
29 use Wikimedia\IPUtils;
30 use Wikimedia\ObjectCache\BagOStuff;
31 use Wikimedia\Rdbms\IDatabase;
32 use Wikimedia\Rdbms\IExpression;
33 use Wikimedia\Rdbms\IMaintainableDatabase;
34 use Wikimedia\Rdbms\IReadableDatabase;
35 use Wikimedia\Rdbms\LBFactory;
36 use Wikimedia\Rdbms\LikeValue;
37 use Wikimedia\Stats\IBufferingStatsdDataFactory;
38
39 /**
40 * Handle sending notifications on login from unknown source.
41 *
42 * @author Brian Wolff
43 */
44 class LoginNotify implements LoggerAwareInterface {
45
46 public const CONSTRUCTOR_OPTIONS = [
47 'LoginNotifyAttemptsKnownIP',
48 'LoginNotifyAttemptsNewIP',
49 'LoginNotifyCacheLoginIPExpiry',
50 'LoginNotifyCheckKnownIPs',
51 'LoginNotifyCookieDomain',
52 'LoginNotifyCookieExpire',
53 'LoginNotifyEnableOnSuccess',
54 'LoginNotifyExpiryKnownIP',
55 'LoginNotifyExpiryNewIP',
56 'LoginNotifyMaxCookieRecords',
57 'LoginNotifySecretKey',
58 'LoginNotifySeenBucketSize',
59 'LoginNotifySeenExpiry',
60 'LoginNotifyUseCheckUser',
61 'LoginNotifyUseSeenTable',
62 'LoginNotifyUseCentralId',
63 'SecretKey',
64 'UpdateRowsPerQuery'
65 ];
66
67 private const COOKIE_NAME = 'loginnotify_prevlogins';
68
69 // The following 3 constants specify outcomes of user search
70 /** User's system is known to us */
71 public const USER_KNOWN = 'known';
72 /** User's system is new for us, based on our data */
73 public const USER_NOT_KNOWN = 'not known';
74 /** We don't have data to confirm or deny this is a known system */
75 public const USER_NO_INFO = 'no info';
76
77 private BagOStuff $cache;
78 private ServiceOptions $config;
79 private LoggerInterface $log;
80 /** @var string Salt for cookie hash. DON'T USE DIRECTLY, use getSalt() */
81 private $salt;
82 /** @var string */
83 private $secret;
84 private IBufferingStatsdDataFactory $stats;
85 private LBFactory $lbFactory;
86 private JobQueueGroup $jobQueueGroup;
87 private CentralIdLookup $centralIdLookup;
88 private AuthManager $authManager;
89 /** @var int|null */
90 private $fakeTime;
91
92 public static function getInstance(): self {
93 return MediaWikiServices::getInstance()->get( 'LoginNotify.LoginNotify' );
94 }
95
96 /**
97 * @param ServiceOptions $options
98 * @param BagOStuff $cache
99 * @param LoggerInterface $log
100 * @param IBufferingStatsdDataFactory $stats
101 * @param LBFactory $lbFactory
102 * @param JobQueueGroup $jobQueueGroup
103 * @param CentralIdLookup $centralIdLookup
104 * @param AuthManager $authManager
105 */
106 public function __construct(
107 ServiceOptions $options,
108 BagOStuff $cache,
109 LoggerInterface $log,
110 IBufferingStatsdDataFactory $stats,
111 LBFactory $lbFactory,
112 JobQueueGroup $jobQueueGroup,
113 CentralIdLookup $centralIdLookup,
114 AuthManager $authManager
115 ) {
116 $this->config = $options;
117 $this->cache = $cache;
118
119 if ( $this->config->get( 'LoginNotifySecretKey' ) !== null ) {
120 $this->secret = $this->config->get( 'LoginNotifySecretKey' );
121 } else {
122 $globalSecret = $this->config->get( 'SecretKey' );
123 $this->secret = hash( 'sha256', $globalSecret . 'LoginNotify' );
124 }
125 $this->log = $log;
126 $this->stats = $stats;
127 $this->lbFactory = $lbFactory;
128 $this->jobQueueGroup = $jobQueueGroup;
129 $this->centralIdLookup = $centralIdLookup;
130 $this->authManager = $authManager;
131 }
132
133 /**
134 * Set the logger.
135 * @param LoggerInterface $logger The logger object.
136 */
137 public function setLogger( LoggerInterface $logger ) {
138 $this->log = $logger;
139 }
140
141 /**
142 * Get just network part of an IP (assuming /24 or /64)
143 *
144 * It would be nice if we could use IPUtils::getSubnet(), which also gets
145 * the /24 or /64 network in support of a similar use case, but its
146 * behaviour is broken for IPv6 addresses, returning the hex range start
147 * rather than the prefix. (T344963)
148 *
149 * @param string $ip Either IPv4 or IPv6 address
150 * @return string Just the network part (e.g. 127.0.0.)
151 */
152 private function getIPNetwork( $ip ) {
153 $ip = IPUtils::sanitizeIP( $ip );
154 if ( IPUtils::isIPv6( $ip ) ) {
155 // Match against the /64
156 $subnetRegex = '/[0-9A-F]+:[0-9A-F]+:[0-9A-F]+:[0-9A-F]+$/i';
157 } elseif ( IPUtils::isIPv4( $ip ) ) {
158 // match against the /24
159 $subnetRegex = '/\d+$/';
160 } else {
161 throw new UnexpectedValueException( "Unrecognized IP address: $ip" );
162 }
163 $prefix = preg_replace( $subnetRegex, '', $ip );
164 if ( !is_string( $prefix ) ) {
165 throw new LogicException( __METHOD__ . " Regex failed on '$ip'!?" );
166 }
167 return $prefix;
168 }
169
170 /**
171 * Returns lazy-initialized salt
172 *
173 * @return string
174 */
175 private function getSalt() {
176 // Generate salt just once to avoid duplicate cookies
177 if ( $this->salt === null ) {
178 $this->salt = \Wikimedia\base_convert( MWCryptRand::generateHex( 8 ), 16, 36 );
179 }
180
181 return $this->salt;
182 }
183
184 /**
185 * Is the current computer known to be used by the current user (fast checks)
186 * To be used for checks that are fast enough to be run at the moment the user logs in.
187 *
188 * @param User $user User in question
189 * @param WebRequest $request
190 * @return string One of USER_* constants
191 */
192 private function isKnownSystemFast( User $user, WebRequest $request ) {
193 $logContext = [ 'user' => $user->getName() ];
194 $result = $this->userIsInCookie( $user, $request );
195 if ( $result === self::USER_KNOWN ) {
196 $this->log->debug( 'Found user {user} in cookie', $logContext );
197 return $result;
198 }
199
200 if ( $this->config->get( 'LoginNotifyUseSeenTable' ) ) {
201 $id = $this->getMaybeCentralId( $user );
202 $hash = $this->getSeenHash( $request, $id );
203 $result = $this->mergeResults( $result, $this->userIsInSeenTable( $id, $hash ) );
204 if ( $result === self::USER_KNOWN ) {
205 $this->log->debug( 'Found user {user} in table', $logContext );
206 return $result;
207 }
208 }
209
210 // No need for caching unless CheckUser will be used
211 if ( $this->config->get( 'LoginNotifyUseCheckUser' ) ) {
212 $result = $this->mergeResults( $result, $this->userIsInCache( $user, $request ) );
213 if ( $result === self::USER_KNOWN ) {
214 $this->log->debug( 'Found user {user} in cache', $logContext );
215 return $result;
216 }
217 } else {
218 $result = self::USER_NOT_KNOWN;
219 }
220
221 $this->log->debug( 'Fast checks for {user}: {result}', [
222 'user' => $user->getName(),
223 'result' => $result,
224 ] );
225
226 return $result;
227 }
228
229 /**
230 * Is the current computer known to be used by the current user (slow checks)
231 * These checks are slow enough to be run via the job queue
232 *
233 * @param User $user User in question
234 * @param string $subnet User's current subnet
235 * @param string $resultSoFar Value returned by isKnownSystemFast() or null if
236 * not available.
237 * @return bool true if the user has used this computer before
238 */
239 private function isKnownSystemSlow( User $user, $subnet, $resultSoFar ) {
240 $result = $this->checkUserAllWikis( $user, $subnet );
241
242 $this->log->debug( 'Checking user {user} from {subnet} (result so far: {soFar}): {result}',
243 [
244 'function' => __METHOD__,
245 'user' => $user->getName(),
246 'subnet' => $subnet,
247 'result' => $result,
248 'soFar' => json_encode( $resultSoFar ),
249 ]
250 );
251
252 $result = $this->mergeResults( $result, $resultSoFar );
253
254 // If we have no CheckUser data for the user, and there was no cookie
255 // supplied, then treat the computer as known.
256 if ( $result === self::USER_NO_INFO ) {
257 // We have to be careful here. Whether $cookieResult is
258 // self::USER_NO_INFO, is under control of the attacker.
259 // If checking CheckUser is disabled, then we should not
260 // hit this branch.
261
262 $this->log->info(
263 "Assuming the user {user} is from a known IP since no info is available",
264 [
265 'method' => __METHOD__,
266 'user' => $user->getName()
267 ]
268 );
269 return true;
270 }
271
272 return $result === self::USER_KNOWN;
273 }
274
275 /**
276 * Check if we cached this user's ip address from last login.
277 *
278 * @param User $user User in question
279 * @param WebRequest $request
280 * @return string One of USER_* constants
281 */
282 private function userIsInCache( User $user, WebRequest $request ) {
283 $ipPrefix = $this->getIPNetwork( $request->getIP() );
284 $key = $this->getKey( $user, 'prevSubnet' );
285 $res = $this->cache->get( $key );
286 if ( $res !== false ) {
287 return $res === $ipPrefix ? self::USER_KNOWN : self::USER_NOT_KNOWN;
288 }
289 return self::USER_NO_INFO;
290 }
291
292 /**
293 * Check if the user is in our own table in a non-expired bucket
294 *
295 * @param int $centralUserId
296 * @param int|string $hash
297 * @return string One of USER_* constants
298 */
299 private function userIsInSeenTable( int $centralUserId, $hash ) {
300 if ( !$centralUserId ) {
301 return self::USER_NO_INFO;
302 }
303 $dbr = $this->getSeenPrimaryDb();
304 $seen = $dbr->newSelectQueryBuilder()
305 ->select( '1' )
306 ->from( 'loginnotify_seen_net' )
307 ->where( [
308 'lsn_user' => $centralUserId,
309 'lsn_subnet' => $hash,
310 $dbr->expr( 'lsn_time_bucket', '>=', $this->getMinBucket() )
311 ] )
312 ->caller( __METHOD__ )
313 ->fetchField();
314 if ( $seen ) {
315 return self::USER_KNOWN;
316 } elseif ( $this->config->get( 'LoginNotifyUseCheckUser' ) ) {
317 // We still need to check CheckUser
318 return self::USER_NO_INFO;
319 } else {
320 return self::USER_NOT_KNOWN;
321 }
322 }
323
324 /**
325 * Check if the user is in our table in the current bucket
326 *
327 * @param int $centralUserId
328 * @param string $hash
329 * @param bool $usePrimary
330 * @return bool
331 */
332 private function userIsInCurrentSeenBucket( int $centralUserId, $hash, $usePrimary = false ) {
333 if ( !$centralUserId ) {
334 return false;
335 }
336 if ( $usePrimary ) {
337 $dbr = $this->getSeenPrimaryDb();
338 } else {
339 $dbr = $this->getSeenReplicaDb();
340 }
341 return (bool)$dbr->newSelectQueryBuilder()
342 ->select( '1' )
343 ->from( 'loginnotify_seen_net' )
344 ->where( [
345 'lsn_user' => $centralUserId,
346 'lsn_subnet' => $hash,
347 'lsn_time_bucket' => $this->getCurrentBucket(),
348 ] )
349 ->caller( __METHOD__ )
350 ->fetchField();
351 }
352
353 /**
354 * Combine the user ID and IP prefix into a 64-bit hash. Return the hash
355 * as either an integer or a decimal string.
356 *
357 * @param WebRequest $request
358 * @param int $centralUserId
359 * @return int|string
360 */
361 private function getSeenHash( WebRequest $request, int $centralUserId ) {
362 $ipPrefix = $this->getIPNetwork( $request->getIP() );
363 $hash = hash_hmac( 'sha1', "$centralUserId|$ipPrefix", $this->secret, true );
364 // Truncate to 64 bits
365 return self::packedSignedInt64ToDecimal( substr( $hash, 0, 8 ) );
366 }
367
368 /**
369 * Convert an 8-byte string to a 64-bit integer, and return it either as a
370 * native integer, or if PHP integers are 32 bits, as a decimal string.
371 *
372 * Signed 64-bit integers are a compact and portable way to store a 64-bit
373 * hash in a DBMS. On a 64-bit platform, PHP can easily generate and handle
374 * such integers, but on a 32-bit platform it is a bit awkward.
375 *
376 * @param string $str
377 * @return int|string
378 */
379 private static function packedSignedInt64ToDecimal( $str ) {
380 if ( PHP_INT_SIZE >= 8 ) {
381 // The manual is confusing -- this does in fact return a signed number
382 return unpack( 'Jv', $str )['v'];
383 } else {
384 // PHP has precious few facilities for manipulating 64-bit numbers on a
385 // 32-bit platform. String bitwise operators are a nice hack though.
386 if ( ( $str[0] & "\x80" ) !== "\x00" ) {
387 // The number is negative. Find 2's complement and add minus sign.
388 $sign = '-';
389 $str = ~$str;
390 $carry = 1;
391 // Add with carry in big endian order
392 for ( $i = 7; $i >= 0 && $carry; $i-- ) {
393 $sum = ord( $str[$i] ) + $carry;
394 $carry = ( $sum & 0x100 ) >> 8;
395 $str[$i] = chr( $sum & 0xff );
396 }
397 } else {
398 $sign = '';
399 }
400 return $sign . \Wikimedia\base_convert( bin2hex( $str ), 16, 10 );
401 }
402 }
403
404 /**
405 * Get read a connection to the database holding the loginnotify_seen_net table.
406 *
407 * @return IReadableDatabase
408 */
409 private function getSeenReplicaDb(): IReadableDatabase {
410 return $this->lbFactory->getReplicaDatabase( 'virtual-LoginNotify' );
411 }
412
413 /**
414 * Get a write connection to the database holding the loginnotify_seen_net table.
415 *
416 * @return IDatabase
417 */
418 private function getSeenPrimaryDb(): IDatabase {
419 return $this->lbFactory->getPrimaryDatabase( 'virtual-LoginNotify' );
420 }
421
422 /**
423 * Get the lowest time bucket index which is not expired.
424 *
425 * @return int
426 */
427 private function getMinBucket() {
428 $now = $this->getCurrentTime();
429 $expiry = $this->config->get( 'LoginNotifySeenExpiry' );
430 $size = $this->config->get( 'LoginNotifySeenBucketSize' );
431 return (int)( ( $now - $expiry ) / $size );
432 }
433
434 /**
435 * Get the current time bucket index.
436 *
437 * @return int
438 */
439 private function getCurrentBucket() {
440 return (int)( $this->getCurrentTime() / $this->config->get( 'LoginNotifySeenBucketSize' ) );
441 }
442
443 /**
444 * Get the current UNIX time
445 *
446 * @return int
447 */
448 private function getCurrentTime() {
449 return $this->fakeTime ?? time();
450 }
451
452 /**
453 * Set a fake time to be returned by getCurrentTime(), for testing.
454 *
455 * @param int|null $time
456 */
457 public function setFakeTime( $time ) {
458 $this->fakeTime = $time;
459 }
460
461 /**
462 * If LoginNotifyUseCentralId is true, indicating a shared table,
463 * get the central user ID. Otherwise, get the local user ID.
464 *
465 * If CentralAuth is not installed, $this->centralIdLookup will be a
466 * LocalIdLookup and the local user ID will be returned regardless. But
467 * using CentralIdLookup unconditionally can fail if CentralAuth is
468 * installed but no users are attached to it, as is the case in CI.
469 *
470 * @param User $user
471 * @return int
472 */
473 private function getMaybeCentralId( User $user ) {
474 if ( $this->config->get( 'LoginNotifyUseCentralId' ) ) {
475 return $this->centralIdLookup->centralIdFromLocalUser( $user );
476 } else {
477 return $user->getId();
478 }
479 }
480
481 /**
482 * Is the subnet of the current IP in the CheckUser data for the user.
483 *
484 * If CentralAuth is installed, this will check not only the current wiki,
485 * but also the ten wikis where user has most edits on.
486 *
487 * @param User $user User in question
488 * @param string $subnet User's current subnet
489 * @return string One of USER_* constants
490 */
491 private function checkUserAllWikis( User $user, $subnet ) {
492 Assert::parameter( $user->isRegistered(), '$user', 'User must be logged in' );
493
494 if ( !$this->config->get( 'LoginNotifyCheckKnownIPs' )
495 || !$this->isCheckUserInstalled()
496 ) {
497 // CheckUser checks disabled.
498 // Note: It's important this be USER_NOT_KNOWN and not USER_NO_INFO.
499 return self::USER_NOT_KNOWN;
500 }
501
502 $dbr = $this->lbFactory->getReplicaDatabase();
503 $result = $this->checkUserOneWiki( $user->getId(), $subnet, $dbr );
504 if ( $result === self::USER_KNOWN ) {
505 return $result;
506 }
507
508 if ( $result === self::USER_NO_INFO
509 && $this->userHasCheckUserData( $user->getId(), $dbr )
510 ) {
511 $result = self::USER_NOT_KNOWN;
512 }
513
514 // Also check checkuser table on the top ten wikis where this user has
515 // edited the most. We only do top ten, to limit the worst-case where the
516 // user has accounts on 800 wikis.
517 if ( ExtensionRegistry::getInstance()->isLoaded( 'CentralAuth' ) ) {
518 $globalUser = CentralAuthUser::getInstance( $user );
519 if ( $globalUser->exists() ) {
520 // This is expensive, up to ~5 seconds (T167731)
521 $info = $globalUser->queryAttached();
522 // Already checked the local wiki.
523 unset( $info[WikiMap::getCurrentWikiId()] );
524 usort( $info,
525 static function ( $a, $b ) {
526 // descending order
527 return $b['editCount'] - $a['editCount'];
528 }
529 );
530 $count = 0;
531 foreach ( $info as $localInfo ) {
532 if ( !isset( $localInfo['id'] ) || !isset( $localInfo['wiki'] ) ) {
533 break;
534 }
535 if ( $count > 10 || $localInfo['editCount'] < 1 ) {
536 break;
537 }
538
539 $wiki = $localInfo['wiki'];
540 $lb = $this->lbFactory->getMainLB( $wiki );
541 $dbrLocal = $lb->getMaintenanceConnectionRef( DB_REPLICA, [], $wiki );
542
543 if ( !$this->hasCheckUserTables( $dbrLocal ) ) {
544 // Skip this wiki, no CheckUser table.
545 continue;
546 }
547 $res = $this->checkUserOneWiki(
548 $localInfo['id'],
549 $subnet,
550 $dbrLocal
551 );
552
553 if ( $res === self::USER_KNOWN ) {
554 return $res;
555 }
556 if ( $result === self::USER_NO_INFO
557 && $this->userHasCheckUserData( $user->getId(), $dbr )
558 ) {
559 $result = self::USER_NOT_KNOWN;
560 }
561 $count++;
562 }
563 }
564 }
565 return $result;
566 }
567
568 /**
569 * Actually do the query of the CheckUser table.
570 *
571 * @note This catches and ignores database errors.
572 * @param int $userId User ID number (Not necessarily for the local wiki)
573 * @param string $ipFragment Prefix to match against cuc_ip (from $this->getIPNetwork())
574 * @param IReadableDatabase $dbr A database connection (possibly foreign)
575 * @return string One of USER_* constants
576 */
577 private function checkUserOneWiki( $userId, $ipFragment, IReadableDatabase $dbr ) {
578 // The index is on (cuc_actor, cuc_ip, cuc_timestamp), instead of
579 // cuc_ip_hex which would be ideal, but CheckUser was not designed for
580 // this specific use case and we couldn't be bothered to update it.
581 // Although it would be 100x faster to use a single global summary
582 // table instead of connecting to the database of each wiki separately.
583 $IPHasBeenUsedBefore = $dbr->newSelectQueryBuilder()
584 ->select( '1' )
585 ->from( 'cu_changes' )
586 ->join( 'actor', null, 'actor_id = cuc_actor' )
587 ->where( [
588 'actor_user' => $userId,
589 $dbr->expr( 'cuc_ip', IExpression::LIKE, new LikeValue(
590 $ipFragment,
591 $dbr->anyString()
592 ) )
593 ] )
594 ->caller( __METHOD__ )
595 ->fetchField();
596 return $IPHasBeenUsedBefore ? self::USER_KNOWN : self::USER_NO_INFO;
597 }
598
599 /**
600 * Check if we have any CheckUser info for this user
601 *
602 * If we have no info for user, we maybe don't treat it as
603 * an unknown IP, since user has no known IPs.
604 *
605 * @param int $userId User id number (possibly on foreign wiki)
606 * @param IReadableDatabase $dbr DB connection (possibly to foreign wiki)
607 * @return bool
608 */
609 private function userHasCheckUserData( $userId, IReadableDatabase $dbr ) {
610 $haveIPInfo = $dbr->newSelectQueryBuilder()
611 ->select( '1' )
612 ->from( 'cu_changes' )
613 ->join( 'actor', null, 'actor_id = cuc_actor' )
614 ->where( [ 'actor_user' => $userId ] )
615 ->caller( __METHOD__ )
616 ->fetchField();
617
618 return (bool)$haveIPInfo;
619 }
620
621 /**
622 * Does this wiki have a CheckUser table?
623 *
624 * @param IMaintainableDatabase $dbr Database to check
625 * @return bool
626 */
627 private function hasCheckUserTables( IMaintainableDatabase $dbr ) {
628 if ( !$dbr->tableExists( 'cu_changes', __METHOD__ ) ) {
629 $this->log->warning( "No CheckUser table on {wikiId}", [
630 'method' => __METHOD__,
631 'wikiId' => $dbr->getDomainID()
632 ] );
633 return false;
634 }
635 return true;
636 }
637
638 /**
639 * Whether CheckUser extension is installed
640 * @return bool
641 */
642 private function isCheckUserInstalled() {
643 return ExtensionRegistry::getInstance()->isLoaded( 'CheckUser' );
644 }
645
646 /**
647 * Give the user a cookie saying that they've previously logged in from this computer.
648 *
649 * @note If user already has a cookie, this will refresh it.
650 * @param User $user User in question who just logged in.
651 */
652 private function setLoginCookie( User $user ) {
653 $cookie = $this->getPrevLoginCookie( $user->getRequest() );
654 [ , $newCookie ] = $this->checkAndGenerateCookie( $user, $cookie );
655 $expire = $this->getCurrentTime() + $this->config->get( 'LoginNotifyCookieExpire' );
656 $resp = $user->getRequest()->response();
657 $resp->setCookie(
658 self::COOKIE_NAME,
659 $newCookie,
660 $expire,
661 [
662 'domain' => $this->config->get( 'LoginNotifyCookieDomain' ),
663 // Allow sharing this cookie between wikis
664 'prefix' => ''
665 ]
666 );
667 }
668
669 /**
670 * Give the user a cookie and store the address in memcached and the DB.
671 *
672 * It is expected this be called upon successful log in.
673 *
674 * @param User $user The user in question.
675 */
676 public function recordKnownWithCookie( User $user ) {
677 if ( !$user->isNamed() ) {
678 return;
679 }
680 $this->setLoginCookie( $user );
681 $this->recordKnown( $user );
682 }
683
684 /**
685 * Store the user's IP address in memcached and the DB
686 *
687 * @param User $user
688 * @return void
689 */
690 public function recordKnown( User $user ) {
691 if ( !$user->isNamed() ) {
692 return;
693 }
694 $this->cacheLoginIP( $user );
695 $this->recordUserInSeenTable( $user );
696
697 $this->log->debug( 'Recording user {user} as known',
698 [
699 'function' => __METHOD__,
700 'user' => $user->getName(),
701 ]
702 );
703 }
704
705 /**
706 * Cache the current IP subnet as being a known location for the given user.
707 *
708 * @param User $user The user.
709 */
710 private function cacheLoginIP( User $user ) {
711 // For simplicity, this only stores the last IP subnet used.
712 // It's assumed that most of the time, we'll be able to rely on
713 // the cookie or CheckUser data.
714 $expiry = $this->config->get( 'LoginNotifyCacheLoginIPExpiry' );
715 $useCU = $this->config->get( 'LoginNotifyUseCheckUser' );
716 if ( $useCU && $expiry !== false ) {
717 $ipPrefix = $this->getIPNetwork( $user->getRequest()->getIP() );
718 $key = $this->getKey( $user, 'prevSubnet' );
719 $this->cache->set( $key, $ipPrefix, $expiry );
720 }
721 }
722
723 /**
724 * If the user/subnet combination is not already in the database, add it.
725 * Also queue a job to clean up expired rows, if necessary.
726 *
727 * @param User $user
728 * @return void
729 */
730 private function recordUserInSeenTable( User $user ) {
731 if ( !$this->config->get( 'LoginNotifyUseSeenTable' ) ) {
732 return;
733 }
734 $id = $this->getMaybeCentralId( $user );
735 if ( !$id ) {
736 return;
737 }
738
739 $request = $user->getRequest();
740 $hash = $this->getSeenHash( $request, $id );
741
742 // Check if the user/hash is in the replica DB
743 if ( $this->userIsInCurrentSeenBucket( $id, $hash ) ) {
744 return;
745 }
746
747 // Check whether purging is required
748 if ( !mt_rand( 0, (int)( $this->config->get( 'UpdateRowsPerQuery' ) / 4 ) ) ) {
749 $minId = $this->getMinExpiredId();
750 if ( $minId !== null ) {
751 $this->log->debug( 'Queueing purge job starting from lsn_id={minId}',
752 [ 'minId' => $minId ] );
753 // Deferred call to purgeSeen()
754 // removeDuplicates effectively limits concurrency to 1, since
755 // no more work will be queued until the DELETE is committed.
756 $job = new JobSpecification(
757 'LoginNotifyPurgeSeen',
758 [ 'minId' => $minId ],
759 [ 'removeDuplicates' => true ]
760 );
761 $this->jobQueueGroup->push( $job );
762 }
763 }
764
765 // Insert a row
766 $dbw = $this->getSeenPrimaryDb();
767 $fname = __METHOD__;
768 $dbw->onTransactionCommitOrIdle(
769 function () use ( $dbw, $id, $hash, $fname ) {
770 $dbw->newInsertQueryBuilder()
771 ->insert( 'loginnotify_seen_net' )
772 ->ignore()
773 ->row( [
774 'lsn_time_bucket' => $this->getCurrentBucket(),
775 'lsn_user' => $id,
776 'lsn_subnet' => $hash
777 ] )
778 ->caller( $fname )
779 ->execute();
780 },
781 $fname
782 );
783 }
784
785 /**
786 * Estimate the minimum lsn_id which has an expired time bucket.
787 *
788 * The primary key is approximately monotonic in time. Guess whether
789 * purging is required by looking at the first row ordered by
790 * primary key. If this check misses a row, it will be cleaned up
791 * when the next bucket expires.
792 *
793 * @return int|null
794 */
795 public function getMinExpiredId() {
796 $minRow = $this->getSeenPrimaryDb()->newSelectQueryBuilder()
797 ->select( [ 'lsn_id', 'lsn_time_bucket' ] )
798 ->from( 'loginnotify_seen_net' )
799 ->orderBy( 'lsn_id' )
800 ->limit( 1 )
801 ->caller( __METHOD__ )
802 ->fetchRow();
803
804 if ( $minRow && ( $minRow->lsn_time_bucket < $this->getMinBucket() ) ) {
805 return (int)$minRow->lsn_id;
806 }
807
808 return null;
809 }
810
811 /**
812 * Purge rows from the loginnotify_seen_net table that are expired.
813 *
814 * @param int $minId The lsn_id to start at
815 * @return int|null The lsn_id to continue at, or null if no more expired
816 * rows are expected.
817 */
818 public function purgeSeen( $minId ) {
819 $dbw = $this->getSeenPrimaryDb();
820 $maxId = $minId + $this->config->get( 'UpdateRowsPerQuery' );
821
822 $dbw->newDeleteQueryBuilder()
823 ->delete( 'loginnotify_seen_net' )
824 ->where( [
825 $dbw->expr( 'lsn_id', '>=', $minId ),
826 $dbw->expr( 'lsn_id', '<', $maxId ),
827 $dbw->expr( 'lsn_time_bucket', '<', $this->getMinBucket() )
828 ] )
829 ->caller( __METHOD__ )
830 ->execute();
831
832 // If there were affected rows, tell the maintenance script to keep looking
833 if ( $dbw->affectedRows() ) {
834 return $maxId;
835 } else {
836 return null;
837 }
838 }
839
840 /**
841 * Merges results of various isKnownSystem*() checks
842 *
843 * @param string $x One of USER_* constants
844 * @param string $y One of USER_* constants
845 * @return string
846 */
847 private function mergeResults( $x, $y ) {
848 if ( $x === self::USER_KNOWN || $y === self::USER_KNOWN ) {
849 return self::USER_KNOWN;
850 }
851 if ( $x === self::USER_NOT_KNOWN || $y === self::USER_NOT_KNOWN ) {
852 return self::USER_NOT_KNOWN;
853 }
854 return self::USER_NO_INFO;
855 }
856
857 /**
858 * Check if a certain user is in the cookie.
859 *
860 * @param User $user User in question
861 * @param WebRequest $request
862 * @return string One of USER_* constants
863 */
864 private function userIsInCookie( User $user, WebRequest $request ) {
865 $cookie = $this->getPrevLoginCookie( $request );
866
867 if ( $cookie === '' ) {
868 $result = self::USER_NO_INFO;
869 } else {
870 [ $userKnown, ] = $this->checkAndGenerateCookie( $user, $cookie );
871 $result = $userKnown ? self::USER_KNOWN : self::USER_NOT_KNOWN;
872 }
873
874 return $result;
875 }
876
877 /**
878 * Get the cookie with previous login names in it
879 *
880 * @param WebRequest $req
881 * @return string The cookie. Empty string if no cookie.
882 */
883 private function getPrevLoginCookie( WebRequest $req ) {
884 return $req->getCookie( self::COOKIE_NAME, '', '' );
885 }
886
887 /**
888 * Check if user is in cookie, and generate a new cookie with user record
889 *
890 * When generating a new cookie, it will add the current user to the top,
891 * remove any previous instances of the current user, and remove older user
892 * references, if there are too many records.
893 *
894 * @param User $user User that person is attempting to log in as.
895 * @param string $cookie A cookie, which has records separated by '.'.
896 * @return array Element 0 is boolean (user seen before?), 1 is the new cookie value.
897 */
898 private function checkAndGenerateCookie( User $user, $cookie ) {
899 $userSeenBefore = false;
900 if ( $cookie === '' ) {
901 $cookieRecords = [];
902 } else {
903 $cookieRecords = explode( '.', $cookie );
904 }
905 $newCookie = $this->generateUserCookieRecord( $user->getName() );
906 $maxCookieRecords = $this->config->get( 'LoginNotifyMaxCookieRecords' );
907
908 foreach ( $cookieRecords as $i => $cookieRecord ) {
909 if ( !$this->validateCookieRecord( $cookieRecord ) ) {
910 // Skip invalid or old cookie records.
911 continue;
912 }
913 $curUser = $this->isUserRecordGivenCookie( $user, $cookieRecord );
914 $userSeenBefore = $userSeenBefore || $curUser;
915 if ( $i < $maxCookieRecords && !$curUser ) {
916 $newCookie .= '.' . $cookieRecord;
917 }
918 }
919 return [ $userSeenBefore, $newCookie ];
920 }
921
922 /**
923 * See if a specific cookie record is for a specific user.
924 *
925 * Cookie record format is: Year - 32-bit salt - hash
926 * where hash is sha1-HMAC of username + | + year + salt
927 * Salt and hash is base 36 encoded.
928 *
929 * The point of the salt is to ensure that a given user creates
930 * different cookies on different machines, so that nobody
931 * can after the fact figure out a single user has used both
932 * machines.
933 *
934 * @param User $user
935 * @param string $cookieRecord
936 * @return bool
937 */
938 private function isUserRecordGivenCookie( User $user, $cookieRecord ) {
939 if ( !$this->validateCookieRecord( $cookieRecord ) ) {
940 // Most callers will probably already check this, but
941 // doesn't hurt to be careful.
942 return false;
943 }
944 $parts = explode( "-", $cookieRecord, 3 );
945 $hash = $this->generateUserCookieRecord( $user->getName(), $parts[0], $parts[1] );
946 return hash_equals( $hash, $cookieRecord );
947 }
948
949 /**
950 * Check if cookie is valid (Is not too old, has 3 fields)
951 *
952 * @param string $cookieRecord Cookie record
953 * @return bool true if valid
954 */
955 private function validateCookieRecord( $cookieRecord ) {
956 $parts = explode( "-", $cookieRecord, 3 );
957 if ( count( $parts ) !== 3 || strlen( $parts[0] ) !== 4 ) {
958 $this->log->warning( "Got cookie with invalid format",
959 [
960 'method' => __METHOD__,
961 'cookieRecord' => $cookieRecord
962 ]
963 );
964 return false;
965 }
966 if ( (int)$parts[0] < (int)gmdate( 'Y' ) - 3 ) {
967 // Record is too old. If user hasn't logged in from this
968 // computer in two years, should probably not consider it trusted.
969 return false;
970 }
971 return true;
972 }
973
974 /**
975 * Generate a single record for use in the previous login cookie
976 *
977 * The format is YYYY-SSSSSSS-HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
978 * where Y is the year, S is a 32-bit salt, H is an sha1-hmac.
979 * Both S and H are base-36 encoded. The actual cookie consists
980 * of several of these records separated by a ".".
981 *
982 * When checking if a hash is valid, provide all three arguments.
983 * When generating a new hash, only use the first argument.
984 *
985 * @param string $username Username,
986 * @param string|false $year [Optional] Year. Default to current year
987 * @param string|false $salt [Optional] Salt (expected to be base-36 encoded)
988 * @return string A record for the cookie
989 */
990 private function generateUserCookieRecord( $username, $year = false, $salt = false ) {
991 if ( $year === false ) {
992 $year = gmdate( 'Y' );
993 }
994
995 if ( $salt === false ) {
996 $salt = $this->getSalt();
997 }
998
999 // TODO: would be nice to truncate the hash, but we would need b/c
1000 $res = hash_hmac( 'sha1', $username . '|' . $year . $salt, $this->secret );
1001 '@phan-var string|false $res';
1002 if ( !is_string( $res ) ) {
1003 // Throws ValueError under php8 in case of error, remove this when mininum is php8
1004 throw new UnexpectedValueException( "Hash failed" );
1005 }
1006 $encoded = $year . '-' . $salt . '-' . \Wikimedia\base_convert( $res, 16, 36 );
1007 return $encoded;
1008 }
1009
1010 /**
1011 * Get the cache key for the counter.
1012 *
1013 * @param User $user
1014 * @param string $type 'known' or 'new'
1015 * @return string The cache key
1016 */
1017 private function getKey( User $user, $type ) {
1018 $userHash = \Wikimedia\base_convert( sha1( $user->getName() ), 16, 36, 31 );
1019 return $this->cache->makeGlobalKey(
1020 'loginnotify', $type, $userHash
1021 );
1022 }
1023
1024 /**
1025 * Increment hit counters for a failed login from an unknown computer.
1026 *
1027 * If a sufficient number of hits have accumulated, send an echo notice.
1028 *
1029 * @param User $user
1030 */
1031 private function recordLoginFailureFromUnknownSystem( User $user ) {
1032 $key = $this->getKey( $user, 'new' );
1033 $count = $this->checkAndIncKey(
1034 $key,
1035 $this->config->get( 'LoginNotifyAttemptsNewIP' ),
1036 $this->config->get( 'LoginNotifyExpiryNewIP' )
1037 );
1038 $message = '{count} failed login attempts for {user} from an unknown system';
1039 if ( $count ) {
1040 $this->incrStats( 'fail.unknown.notifications' );
1041 $this->sendNotice( $user, 'login-fail-new', $count );
1042 $message .= ', sending notification';
1043 }
1044
1045 $this->log->debug( $message,
1046 [
1047 'function' => __METHOD__,
1048 'count' => $count,
1049 'user' => $user->getName(),
1050 ]
1051 );
1052 }
1053
1054 /**
1055 * Increment hit counters for a failed login from a known computer.
1056 *
1057 * If a sufficient number of hits have accumulated, send an echo notice.
1058 *
1059 * @param User $user
1060 */
1061 private function recordLoginFailureFromKnownSystem( User $user ) {
1062 $key = $this->getKey( $user, 'known' );
1063 $count = $this->checkAndIncKey(
1064 $key,
1065 $this->config->get( 'LoginNotifyAttemptsKnownIP' ),
1066 $this->config->get( 'LoginNotifyExpiryKnownIP' )
1067 );
1068 if ( $count ) {
1069 $this->incrStats( 'fail.known.notifications' );
1070 $this->sendNotice( $user, 'login-fail-known', $count );
1071 }
1072 }
1073
1074 /**
1075 * Send a notice about login attempts
1076 *
1077 * @param User $user The account in question
1078 * @param string $type 'login-fail-new', 'login-fail-known', 'login-success'
1079 * @param int|null $count [Optional] How many failed attempts
1080 */
1081 private function sendNotice( User $user, $type, $count = null ) {
1082 $request = $user->getRequest();
1083 $this->log->info( 'Notification type {notificationtype} recorded for {user}',
1084 [
1085 'function' => __METHOD__,
1086 'notificationtype' => $type,
1087 'count' => $count,
1088 'user' => $user->getName(),
1089 'ip' => $request->getIP(),
1090 'ua' => $request->getHeader( 'user-agent' ),
1091 ]
1092 );
1093 $extra = [];
1094 if ( $count !== null ) {
1095 $extra['count'] = $count;
1096 }
1097 Event::create( [
1098 'type' => $type,
1099 'extra' => $extra,
1100 'agent' => $user,
1101 ] );
1102 }
1103
1104 /**
1105 * Check if we've reached the limit, and increment the cache key.
1106 *
1107 * @param string $key Cache key
1108 * @param int $interval The interval of one to send notice
1109 * @param int $expiry When to expire cache key.
1110 * @return false|int false to not send notice, or number of hits
1111 */
1112 private function checkAndIncKey( $key, $interval, $expiry ) {
1113 $cache = $this->cache;
1114
1115 $cur = $cache->incrWithInit( $key, $expiry );
1116 if ( $cur % $interval === 0 ) {
1117 return $cur;
1118 }
1119 return false;
1120 }
1121
1122 /**
1123 * Clear attempt counter for user.
1124 *
1125 * When a user successfully logs in, we start back from 0, as
1126 * otherwise a mistake here and there will trigger the warning.
1127 *
1128 * @param User $user The user for whom to clear the attempt counter.
1129 */
1130 public function clearCounters( User $user ) {
1131 $cache = $this->cache;
1132 $keyKnown = $this->getKey( $user, 'known' );
1133 $keyNew = $this->getKey( $user, 'new' );
1134
1135 $cache->delete( $keyKnown );
1136 $cache->delete( $keyNew );
1137 }
1138
1139 /**
1140 * On login failure, record failure and maybe send notice
1141 *
1142 * @param User $user User in question
1143 */
1144 public function recordFailure( User $user ) {
1145 $this->incrStats( 'fail.total' );
1146
1147 if ( $user->isAnon() ) {
1148 // Login failed because user doesn't exist
1149 // skip this user.
1150 $this->log->debug( "Skipping recording failure for {user} - no account",
1151 [ 'user' => $user->getName() ]
1152 );
1153 return;
1154 }
1155
1156 // No need to notify if the user can't authenticate (e.g. system or temporary users)
1157 if ( !$this->authManager->userCanAuthenticate( $user->getName() ) ) {
1158 $this->log->debug( "Skipping recording failure for user {user} - can't authenticate",
1159 [ 'user' => $user->getName() ]
1160 );
1161 return;
1162 }
1163
1164 $known = $this->isKnownSystemFast( $user, $user->getRequest() );
1165 if ( $known === self::USER_KNOWN ) {
1166 $this->recordLoginFailureFromKnownSystem( $user );
1167 } elseif ( $this->config->get( 'LoginNotifyUseCheckUser' ) ) {
1168 $this->createJob( DeferredChecksJob::TYPE_LOGIN_FAILED,
1169 $user, $user->getRequest(), $known
1170 );
1171 } else {
1172 $this->recordLoginFailureFromUnknownSystem( $user );
1173 }
1174 }
1175
1176 /**
1177 * Asynchronous part of recordFailure(), to be called from DeferredChecksJob
1178 *
1179 * @param User $user User in question
1180 * @param string $subnet User's current subnet
1181 * @param string $resultSoFar Value returned by isKnownSystemFast()
1182 */
1183 public function recordFailureDeferred( User $user, $subnet, $resultSoFar ) {
1184 $isKnown = $this->isKnownSystemSlow( $user, $subnet, $resultSoFar );
1185 if ( !$isKnown ) {
1186 $this->recordLoginFailureFromUnknownSystem( $user );
1187 } else {
1188 $this->recordLoginFailureFromKnownSystem( $user );
1189 }
1190 }
1191
1192 /**
1193 * Send a notice on successful login from an unknown IP
1194 *
1195 * @param User $user User account in question.
1196 */
1197 public function sendSuccessNotice( User $user ) {
1198 if ( !$this->config->get( 'LoginNotifyEnableOnSuccess' ) ) {
1199 return;
1200 }
1201 $this->incrStats( 'success.total' );
1202 $result = $this->isKnownSystemFast( $user, $user->getRequest() );
1203 if ( $result === self::USER_KNOWN ) {
1204 // No need to notify
1205 } elseif ( $this->config->get( 'LoginNotifyUseCheckUser' ) ) {
1206 $this->createJob( DeferredChecksJob::TYPE_LOGIN_SUCCESS,
1207 $user, $user->getRequest(), $result
1208 );
1209 } elseif ( $result === self::USER_NOT_KNOWN ) {
1210 $this->incrStats( 'success.notifications' );
1211 $this->sendNotice( $user, 'login-success' );
1212 }
1213 }
1214
1215 /**
1216 * Asynchronous part of sendSuccessNotice(), to be called from DeferredChecksJob
1217 *
1218 * @param User $user User in question
1219 * @param string $subnet User's current subnet
1220 * @param string $resultSoFar Value returned by isKnownSystemFast()
1221 */
1222 public function sendSuccessNoticeDeferred( User $user, $subnet, $resultSoFar ) {
1223 $isKnown = $this->isKnownSystemSlow( $user, $subnet, $resultSoFar );
1224 if ( $isKnown ) {
1225 $this->log->debug( 'Found data for user {user} from {subnet}',
1226 [
1227 'function' => __METHOD__,
1228 'user' => $user->getName(),
1229 'subnet' => $subnet,
1230 ]
1231 );
1232 } else {
1233 $this->incrStats( 'success.notifications' );
1234 $this->sendNotice( $user, 'login-success' );
1235 }
1236 }
1237
1238 /**
1239 * Create and enqueue a job to do asynchronous processing of user login success/failure
1240 *
1241 * @param string $type Job type, one of DeferredChecksJob::TYPE_* constants
1242 * @param User $user User in question
1243 * @param WebRequest $request
1244 * @param string $resultSoFar Value returned by isKnownSystemFast()
1245 */
1246 private function createJob( $type, User $user, WebRequest $request, $resultSoFar ) {
1247 $subnet = $this->getIPNetwork( $request->getIP() );
1248 $job = new JobSpecification( 'LoginNotifyChecks',
1249 [
1250 'checkType' => $type,
1251 'userId' => $user->getId(),
1252 'subnet' => $subnet,
1253 'resultSoFar' => $resultSoFar,
1254 ]
1255 );
1256 $this->jobQueueGroup->lazyPush( $job );
1257
1258 $this->log->debug( 'Login {status}, creating a job to verify {user}, result so far: {result}',
1259 [
1260 'function' => __METHOD__,
1261 'status' => $type,
1262 'user' => $user->getName(),
1263 'result' => $resultSoFar,
1264 ]
1265 );
1266 }
1267
1268 /**
1269 * Increments the given statistic
1270 *
1271 * @param string $metric
1272 */
1273 private function incrStats( $metric ) {
1274 $this->stats->increment( "loginnotify.$metric" );
1275 }
1276 }