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
21 namespace MediaWiki\Block
;
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
;
33 use Psr\Log\LoggerInterface
;
38 use Wikimedia\IPUtils
;
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.
47 /** @var PermissionManager */
48 private $permissionManager;
50 /** @var ServiceOptions */
54 * @internal For use by ServiceWiring
56 public const CONSTRUCTOR_OPTIONS
= [
58 'CookieSetOnAutoblock',
68 /** @var LoggerInterface */
71 /** @var HookRunner */
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
86 $options->assertRequiredOptions( self
::CONSTRUCTOR_OPTIONS
);
87 $this->options
= $options;
88 $this->permissionManager
= $permissionManager;
89 $this->logger
= $logger;
90 $this->hookRunner
= new HookRunner( $hookContainer );
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
98 * Different blocks may be sought, depending on the user and their permissions. The
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
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
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;
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 );
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 );
156 if ( count( $blocks ) > 0 ) {
157 if ( count( $blocks ) === 1 ) {
158 $block = $blocks[ 0 ];
160 $block = new CompositeBlock( [
162 'reason' => new Message( 'blockedtext-composite-reason' ),
163 'originalBlocks' => $blocks,
168 $this->hookRunner
->onGetUserBlock( clone $user, $ip, $block );
174 * Get the cookie block, if there is one.
176 * @param AbstractBlock[] &$blocks
177 * @param UserIdentity $user
178 * @param WebRequest $request
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
197 private function getAdditionalIpBlocks( &$blocks, WebRequest
$request, $isAnon, $fromMaster ) {
198 $ip = $request->getIP();
201 if ( !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) ) {
203 if ( $this->isLocallyBlockedProxy( $ip ) ) {
204 $blocks[] = new SystemBlock( [
205 'reason' => new Message( 'proxyblockreason' ),
207 'systemBlock' => 'proxy',
209 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
210 $blocks[] = new SystemBlock( [
211 'reason' => new Message( 'sorbsreason' ),
213 'systemBlock' => 'dnsbl',
219 if ( $isAnon && IPUtils
::isInRanges( $ip, $this->options
->get( 'SoftBlockRanges' ) ) ) {
220 $blocks[] = new SystemBlock( [
222 'reason' => new Message( 'softblockrangesreason', [ $ip ] ),
224 'systemBlock' => 'wgSoftBlockRanges',
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 ) {
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;
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(
287 $cookieValue = $request->getCookie( 'BlockID' );
288 if ( $cookieValue === null ) {
292 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
293 if ( $blockCookieId !== null ) {
294 // TODO: remove dependency on DatabaseBlock (T221075)
295 $block = DatabaseBlock
::newFromID( $blockCookieId );
297 $block instanceof DatabaseBlock
&&
298 $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
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)
322 $this->options
->get( 'CookieSetOnIpBlock' );
323 case DatabaseBlock
::TYPE_USER
:
324 return $block->isAutoblocking() &&
325 $this->options
->get( 'CookieSetOnAutoblock' );
334 * Check if an IP address is in the local proxy list
339 private function isLocallyBlockedProxy( $ip ) {
340 $proxyList = $this->options
->get( 'ProxyList' );
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' ) ) )
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 ) {
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 ) {
387 // If we have an access key, use that too (ProjectHoneypot, etc.)
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]}";
394 $hostname = "$ipReversed.{$base[0]}";
396 $basename = $base[0];
398 $hostname = "$ipReversed.$base";
402 $ipList = $this->checkHost( $hostname );
406 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
412 $this->logger
->debug( "Requested $hostname, not found in $basename." );
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.
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() ) ) {
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();
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 );
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.
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(
517 new DateTimeZone( 'UTC' )
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
:
539 $this->options
->get( 'CookieSetOnAutoblock' ) &&
540 $block->isAutoblocking();
549 * Unset the 'BlockID' cookie.
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.
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 ) ) ) {
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.
581 $storedHmac = substr( $cookieValue, $bangPos +
1 );
582 $calculatedHmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
583 if ( $calculatedHmac === $storedHmac ) {
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
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.
607 $hmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
608 $cookieValue = $id . '!' . $hmac;