CentralIdLookup: Add @since to factoryNonLocal()
[mediawiki.git] / includes / block / BlockManager.php
blobdc753ebc31fc7bccbc6344be4be54fa28a277116
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
21 namespace MediaWiki\Block;
23 use DateTime;
24 use DateTimeZone;
25 use LogicException;
26 use MediaWiki\Config\ServiceOptions;
27 use MediaWiki\HookContainer\HookContainer;
28 use MediaWiki\HookContainer\HookRunner;
29 use MediaWiki\Permissions\PermissionManager;
30 use MediaWiki\User\UserIdentity;
31 use Message;
32 use MWCryptHash;
33 use Psr\Log\LoggerInterface;
34 use User;
35 use WebRequest;
36 use WebResponse;
37 use Wikimedia\IPSet;
38 use Wikimedia\IPUtils;
40 /**
41 * A service class for checking blocks.
42 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
44 * @since 1.34 Refactored from User and Block.
46 class BlockManager {
47 /** @var PermissionManager */
48 private $permissionManager;
50 /** @var ServiceOptions */
51 private $options;
53 /**
54 * @internal For use by ServiceWiring
56 public const CONSTRUCTOR_OPTIONS = [
57 'ApplyIpBlocksToXff',
58 'CookieSetOnAutoblock',
59 'CookieSetOnIpBlock',
60 'DnsBlacklistUrls',
61 'EnableDnsBlacklist',
62 'ProxyList',
63 'ProxyWhitelist',
64 'SecretKey',
65 'SoftBlockRanges',
68 /** @var LoggerInterface */
69 private $logger;
71 /** @var HookRunner */
72 private $hookRunner;
74 /**
75 * @param ServiceOptions $options
76 * @param PermissionManager $permissionManager
77 * @param LoggerInterface $logger
78 * @param HookContainer $hookContainer
80 public function __construct(
81 ServiceOptions $options,
82 PermissionManager $permissionManager,
83 LoggerInterface $logger,
84 HookContainer $hookContainer
85 ) {
86 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
87 $this->options = $options;
88 $this->permissionManager = $permissionManager;
89 $this->logger = $logger;
90 $this->hookRunner = new HookRunner( $hookContainer );
93 /**
94 * Get the blocks that apply to a user. If there is only one, return that, otherwise
95 * return a composite block that combines the strictest features of the applicable
96 * blocks.
98 * Different blocks may be sought, depending on the user and their permissions. The
99 * user may be:
100 * (1) The global user (and can be affected by IP blocks). The global request object
101 * is needed for checking the IP address, the XFF header and the cookies.
102 * (2) The global user (and exempt from IP blocks). The global request object is
103 * available.
104 * (3) Another user (not the global user). No request object is available or needed;
105 * just look for a block against the user account.
107 * Cases #1 and #2 check whether the global user is blocked in practice; the block
108 * may due to their user account being blocked or to an IP address block or cookie
109 * block (or multiple of these). Case #3 simply checks whether a user's account is
110 * blocked, and does not determine whether the person using that account is affected
111 * in practice by any IP address or cookie blocks.
113 * @internal This should only be called by User::getBlockedStatus
114 * @param User $user
115 * @param WebRequest|null $request The global request object if the user is the
116 * global user (cases #1 and #2), otherwise null (case #3). The IP address and
117 * information from the request header are needed to find some types of blocks.
118 * @param bool $fromReplica Whether to check the replica DB first.
119 * To improve performance, non-critical checks are done against replica DBs.
120 * Check when actually saving should be done against master.
121 * @return AbstractBlock|null The most relevant block, or null if there is no block.
123 public function getUserBlock( User $user, $request, $fromReplica ) {
124 $fromMaster = !$fromReplica;
125 $ip = null;
127 // If this is the global user, they may be affected by IP blocks (case #1),
128 // or they may be exempt (case #2). If affected, look for additional blocks
129 // against the IP address and referenced in a cookie.
130 $checkIpBlocks = $request &&
131 !$this->permissionManager->userHasRight( $user, 'ipblock-exempt' );
133 if ( $request && $checkIpBlocks ) {
135 // Case #1: checking the global user, including IP blocks
136 $ip = $request->getIP();
137 // TODO: remove dependency on DatabaseBlock (T221075)
138 $blocks = DatabaseBlock::newListFromTarget( $user, $ip, $fromMaster );
139 $this->getAdditionalIpBlocks( $blocks, $request, !$user->isRegistered(), $fromMaster );
140 $this->getCookieBlock( $blocks, $user, $request );
142 } else {
144 // Case #2: checking the global user, but they are exempt from IP blocks
145 // and cookie blocks, so we only check for a user account block.
146 // Case #3: checking whether another user's account is blocked.
147 // TODO: remove dependency on DatabaseBlock (T221075)
148 $blocks = DatabaseBlock::newListFromTarget( $user, null, $fromMaster );
152 // Filter out any duplicated blocks, e.g. from the cookie
153 $blocks = $this->getUniqueBlocks( $blocks );
155 $block = null;
156 if ( count( $blocks ) > 0 ) {
157 if ( count( $blocks ) === 1 ) {
158 $block = $blocks[ 0 ];
159 } else {
160 $block = new CompositeBlock( [
161 'address' => $ip,
162 'reason' => new Message( 'blockedtext-composite-reason' ),
163 'originalBlocks' => $blocks,
164 ] );
168 $this->hookRunner->onGetUserBlock( clone $user, $ip, $block );
170 return $block;
174 * Get the cookie block, if there is one.
176 * @param AbstractBlock[] &$blocks
177 * @param UserIdentity $user
178 * @param WebRequest $request
179 * @return void
181 private function getCookieBlock( &$blocks, UserIdentity $user, WebRequest $request ) {
182 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
183 if ( $cookieBlock instanceof DatabaseBlock ) {
184 $blocks[] = $cookieBlock;
189 * Check for any additional blocks against the IP address or any IPs in the XFF header.
191 * @param AbstractBlock[] &$blocks Blocks found so far
192 * @param WebRequest $request
193 * @param bool $isAnon The user is logged out
194 * @param bool $fromMaster
195 * @return void
197 private function getAdditionalIpBlocks( &$blocks, WebRequest $request, $isAnon, $fromMaster ) {
198 $ip = $request->getIP();
200 // Proxy blocking
201 if ( !in_array( $ip, $this->options->get( 'ProxyWhitelist' ) ) ) {
202 // Local list
203 if ( $this->isLocallyBlockedProxy( $ip ) ) {
204 $blocks[] = new SystemBlock( [
205 'reason' => new Message( 'proxyblockreason' ),
206 'address' => $ip,
207 'systemBlock' => 'proxy',
208 ] );
209 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
210 $blocks[] = new SystemBlock( [
211 'reason' => new Message( 'sorbsreason' ),
212 'address' => $ip,
213 'systemBlock' => 'dnsbl',
214 ] );
218 // Soft blocking
219 if ( $isAnon && IPUtils::isInRanges( $ip, $this->options->get( 'SoftBlockRanges' ) ) ) {
220 $blocks[] = new SystemBlock( [
221 'address' => $ip,
222 'reason' => new Message( 'softblockrangesreason', [ $ip ] ),
223 'anonOnly' => true,
224 'systemBlock' => 'wgSoftBlockRanges',
225 ] );
228 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
229 if ( $this->options->get( 'ApplyIpBlocksToXff' )
230 && !in_array( $ip, $this->options->get( 'ProxyWhitelist' ) )
232 $xff = $request->getHeader( 'X-Forwarded-For' );
233 $xff = array_map( 'trim', explode( ',', $xff ) );
234 $xff = array_diff( $xff, [ $ip ] );
235 // TODO: remove dependency on DatabaseBlock (T221075)
236 $xffblocks = DatabaseBlock::getBlocksForIPList( $xff, $isAnon, $fromMaster );
237 $blocks = array_merge( $blocks, $xffblocks );
242 * Given a list of blocks, return a list of unique blocks.
244 * This usually means that each block has a unique ID. For a block with ID null,
245 * if it's an autoblock, it will be filtered out if the parent block is present;
246 * if not, it is assumed to be a unique system block, and kept.
248 * @param AbstractBlock[] $blocks
249 * @return AbstractBlock[]
251 private function getUniqueBlocks( array $blocks ) {
252 $systemBlocks = [];
253 $databaseBlocks = [];
255 foreach ( $blocks as $block ) {
256 if ( $block instanceof SystemBlock ) {
257 $systemBlocks[] = $block;
258 } elseif ( $block->getType() === DatabaseBlock::TYPE_AUTO ) {
259 /** @var DatabaseBlock $block */
260 '@phan-var DatabaseBlock $block';
261 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
262 $databaseBlocks[$block->getParentBlockId()] = $block;
264 } else {
265 $databaseBlocks[$block->getId()] = $block;
269 return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
273 * Try to load a block from an ID given in a cookie value.
275 * If the block is invalid, doesn't exist, or the cookie value is malformed, no
276 * block will be loaded. In these cases the cookie will either (1) be replaced
277 * with a valid cookie or (2) removed, next time trackBlockWithCookie is called.
279 * @param UserIdentity $user
280 * @param WebRequest $request
281 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
283 private function getBlockFromCookieValue(
284 UserIdentity $user,
285 WebRequest $request
287 $cookieValue = $request->getCookie( 'BlockID' );
288 if ( $cookieValue === null ) {
289 return false;
292 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
293 if ( $blockCookieId !== null ) {
294 // TODO: remove dependency on DatabaseBlock (T221075)
295 $block = DatabaseBlock::newFromID( $blockCookieId );
296 if (
297 $block instanceof DatabaseBlock &&
298 $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
300 return $block;
304 return false;
308 * Check if the block loaded from the cookie should be applied.
310 * @param DatabaseBlock $block
311 * @param bool $isAnon The user is logged out
312 * @return bool The block sould be applied
314 private function shouldApplyCookieBlock( DatabaseBlock $block, $isAnon ) {
315 if ( !$block->isExpired() ) {
316 switch ( $block->getType() ) {
317 case DatabaseBlock::TYPE_IP:
318 case DatabaseBlock::TYPE_RANGE:
319 // If block is type IP or IP range, load only
320 // if user is not logged in (T152462)
321 return $isAnon &&
322 $this->options->get( 'CookieSetOnIpBlock' );
323 case DatabaseBlock::TYPE_USER:
324 return $block->isAutoblocking() &&
325 $this->options->get( 'CookieSetOnAutoblock' );
326 default:
327 return false;
330 return false;
334 * Check if an IP address is in the local proxy list
336 * @param string $ip
337 * @return bool
339 private function isLocallyBlockedProxy( $ip ) {
340 $proxyList = $this->options->get( 'ProxyList' );
341 if ( !$proxyList ) {
342 return false;
345 if ( !is_array( $proxyList ) ) {
346 // Load values from the specified file
347 $proxyList = array_map( 'trim', file( $proxyList ) );
350 $proxyListIPSet = new IPSet( $proxyList );
351 return $proxyListIPSet->match( $ip );
355 * Whether the given IP is in a DNS blacklist.
357 * @param string $ip IP to check
358 * @param bool $checkWhitelist Whether to check the whitelist first
359 * @return bool True if blacklisted.
361 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
362 if ( !$this->options->get( 'EnableDnsBlacklist' ) ||
363 ( $checkWhitelist && in_array( $ip, $this->options->get( 'ProxyWhitelist' ) ) )
365 return false;
368 return $this->inDnsBlacklist( $ip, $this->options->get( 'DnsBlacklistUrls' ) );
372 * Whether the given IP is in a given DNS blacklist.
374 * @param string $ip IP to check
375 * @param array $bases Array of Strings: URL of the DNS blacklist
376 * @return bool True if blacklisted.
378 private function inDnsBlacklist( $ip, array $bases ) {
379 $found = false;
380 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
381 if ( IPUtils::isIPv4( $ip ) ) {
382 // Reverse IP, T23255
383 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
385 foreach ( $bases as $base ) {
386 // Make hostname
387 // If we have an access key, use that too (ProjectHoneypot, etc.)
388 $basename = $base;
389 if ( is_array( $base ) ) {
390 if ( count( $base ) >= 2 ) {
391 // Access key is 1, base URL is 0
392 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
393 } else {
394 $hostname = "$ipReversed.{$base[0]}";
396 $basename = $base[0];
397 } else {
398 $hostname = "$ipReversed.$base";
401 // Send query
402 $ipList = $this->checkHost( $hostname );
404 if ( $ipList ) {
405 $this->logger->info(
406 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
408 $found = true;
409 break;
412 $this->logger->debug( "Requested $hostname, not found in $basename." );
416 return $found;
420 * Wrapper for mocking in tests.
422 * @param string $hostname DNSBL query
423 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
425 protected function checkHost( $hostname ) {
426 return gethostbynamel( $hostname );
430 * Set the 'BlockID' cookie depending on block type and user authentication status.
432 * If a block cookie is already set, this will check the block that the cookie references
433 * and do the following:
434 * - If the block is a valid block that should be applied, do nothing and return early.
435 * This ensures that the cookie's expiry time is based on the time of the first page
436 * load or attempt. (See discussion on T233595.)
437 * - If the block is invalid (e.g. has expired), clear the cookie and continue to check
438 * whether there is another block that should be tracked.
439 * - If the block is a valid block, but should not be tracked by a cookie, clear the
440 * cookie and continue to check whether there is another block that should be tracked.
442 * @since 1.34
443 * @param User $user
444 * @param WebResponse $response The response on which to set the cookie.
445 * @throws LogicException If called before the User object was loaded.
446 * @throws LogicException If not called pre-send.
448 public function trackBlockWithCookie( User $user, WebResponse $response ) {
449 $request = $user->getRequest();
451 if ( $request->getCookie( 'BlockID' ) !== null ) {
452 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
453 if ( $cookieBlock && $this->shouldApplyCookieBlock( $cookieBlock, $user->isAnon() ) ) {
454 return;
456 // The block pointed to by the cookie is invalid or should not be tracked.
457 $this->clearBlockCookie( $response );
460 if ( !$user->isSafeToLoad() ) {
461 // Prevent a circular dependency by not allowing this method to be called
462 // before or while the user is being loaded.
463 // E.g. User > BlockManager > Block > Message > getLanguage > User.
464 // See also T180050 and T226777.
465 throw new LogicException( __METHOD__ . ' requires a loaded User object' );
467 if ( $response->headersSent() ) {
468 throw new LogicException( __METHOD__ . ' must be called pre-send' );
471 $block = $user->getBlock();
472 $isAnon = $user->isAnon();
474 if ( $block ) {
475 if ( $block instanceof CompositeBlock ) {
476 // TODO: Improve on simply tracking the first trackable block (T225654)
477 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
478 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
479 '@phan-var DatabaseBlock $originalBlock';
480 $this->setBlockCookie( $originalBlock, $response );
481 return;
484 } else {
485 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
486 '@phan-var DatabaseBlock $block';
487 $this->setBlockCookie( $block, $response );
494 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
495 * the same as the block's, to a maximum of 24 hours.
497 * @since 1.34
498 * @internal Should be private.
499 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
500 * @param DatabaseBlock $block
501 * @param WebResponse $response The response on which to set the cookie.
503 public function setBlockCookie( DatabaseBlock $block, WebResponse $response ) {
504 // Calculate the default expiry time.
505 $maxExpiryTime = wfTimestamp( TS_MW, (int)wfTimestamp() + ( 24 * 60 * 60 ) );
507 // Use the block's expiry time only if it's less than the default.
508 $expiryTime = $block->getExpiry();
509 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
510 $expiryTime = $maxExpiryTime;
513 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
514 $expiryValue = DateTime::createFromFormat(
515 'YmdHis',
516 $expiryTime,
517 new DateTimeZone( 'UTC' )
518 )->format( 'U' );
519 $cookieOptions = [ 'httpOnly' => false ];
520 $cookieValue = $this->getCookieValue( $block );
521 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
525 * Check if the block should be tracked with a cookie.
527 * @param AbstractBlock $block
528 * @param bool $isAnon The user is logged out
529 * @return bool The block sould be tracked with a cookie
531 private function shouldTrackBlockWithCookie( AbstractBlock $block, $isAnon ) {
532 if ( $block instanceof DatabaseBlock ) {
533 switch ( $block->getType() ) {
534 case DatabaseBlock::TYPE_IP:
535 case DatabaseBlock::TYPE_RANGE:
536 return $isAnon && $this->options->get( 'CookieSetOnIpBlock' );
537 case DatabaseBlock::TYPE_USER:
538 return !$isAnon &&
539 $this->options->get( 'CookieSetOnAutoblock' ) &&
540 $block->isAutoblocking();
541 default:
542 return false;
545 return false;
549 * Unset the 'BlockID' cookie.
551 * @since 1.34
552 * @param WebResponse $response
554 public static function clearBlockCookie( WebResponse $response ) {
555 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
559 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
560 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
562 * @since 1.34
563 * @internal Should be private.
564 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
565 * @param string $cookieValue The string in which to find the ID.
566 * @return int|null The block ID, or null if the HMAC is present and invalid.
568 public function getIdFromCookieValue( $cookieValue ) {
569 // The cookie value must start with a number
570 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
571 return null;
574 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
575 $bangPos = strpos( $cookieValue, '!' );
576 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
577 if ( !$this->options->get( 'SecretKey' ) ) {
578 // If there's no secret key, just use the ID as given.
579 return (int)$id;
581 $storedHmac = substr( $cookieValue, $bangPos + 1 );
582 $calculatedHmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
583 if ( $calculatedHmac === $storedHmac ) {
584 return (int)$id;
585 } else {
586 return null;
591 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
592 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
593 * be the block ID.
595 * @since 1.34
596 * @internal Should be private.
597 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
598 * @param DatabaseBlock $block
599 * @return string The block ID, probably concatenated with "!" and the HMAC.
601 public function getCookieValue( DatabaseBlock $block ) {
602 $id = $block->getId();
603 if ( !$this->options->get( 'SecretKey' ) ) {
604 // If there's no secret key, don't append a HMAC.
605 return $id;
607 $hmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
608 $cookieValue = $id . '!' . $hmac;
609 return $cookieValue;