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
;
28 use MediaWiki\Config\ServiceOptions
;
29 use MediaWiki\Permissions\PermissionManager
;
30 use MediaWiki\User\UserIdentity
;
32 use Psr\Log\LoggerInterface
;
39 * A service class for checking blocks.
40 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
42 * @since 1.34 Refactored from User and Block.
45 /** @var PermissionManager */
46 private $permissionManager;
48 /** @var ServiceOptions */
55 public const CONSTRUCTOR_OPTIONS
= [
57 'CookieSetOnAutoblock',
67 /** @var LoggerInterface */
71 * @param ServiceOptions $options
72 * @param PermissionManager $permissionManager
73 * @param LoggerInterface $logger
75 public function __construct(
76 ServiceOptions
$options,
77 PermissionManager
$permissionManager,
78 LoggerInterface
$logger
80 $options->assertRequiredOptions( self
::CONSTRUCTOR_OPTIONS
);
81 $this->options
= $options;
82 $this->permissionManager
= $permissionManager;
83 $this->logger
= $logger;
87 * Get the blocks that apply to a user. If there is only one, return that, otherwise
88 * return a composite block that combines the strictest features of the applicable
91 * Different blocks may be sought, depending on the user and their permissions. The
93 * (1) The global user (and can be affected by IP blocks). The global request object
94 * is needed for checking the IP address, the XFF header and the cookies.
95 * (2) The global user (and exempt from IP blocks). The global request object is
96 * needed for checking the cookies.
97 * (3) Another user (not the global user). No request object is available or needed;
98 * just look for a block against the user account.
100 * Cases #1 and #2 check whether the global user is blocked in practice; the block
101 * may due to their user account being blocked or to an IP address block or cookie
102 * block (or multiple of these). Case #3 simply checks whether a user's account is
103 * blocked, and does not determine whether the person using that account is affected
104 * in practice by any IP address or cookie blocks.
106 * @internal This should only be called by User::getBlockedStatus
108 * @param WebRequest|null $request The global request object if the user is the
109 * global user (cases #1 and #2), otherwise null (case #3). The IP address and
110 * information from the request header are needed to find some types of blocks.
111 * @param bool $fromReplica Whether to check the replica DB first.
112 * To improve performance, non-critical checks are done against replica DBs.
113 * Check when actually saving should be done against master.
114 * @return AbstractBlock|null The most relevant block, or null if there is no block.
116 public function getUserBlock( User
$user, $request, $fromReplica ) {
117 $fromMaster = !$fromReplica;
120 // If this is the global user, they may be affected by IP blocks (case #1),
121 // or they may be exempt (case #2). If affected, look for additional blocks
122 // against the IP address.
123 $checkIpBlocks = $request &&
124 !$this->permissionManager
->userHasRight( $user, 'ipblock-exempt' );
126 if ( $request && $checkIpBlocks ) {
128 // Case #1: checking the global user, including IP blocks
129 $ip = $request->getIP();
130 // TODO: remove dependency on DatabaseBlock (T221075)
131 $blocks = DatabaseBlock
::newListFromTarget( $user, $ip, $fromMaster );
132 $this->getAdditionalIpBlocks( $blocks, $request, !$user->isRegistered(), $fromMaster );
133 $this->getCookieBlock( $blocks, $user, $request );
135 } elseif ( $request ) {
137 // Case #2: checking the global user, but they are exempt from IP blocks
138 // TODO: remove dependency on DatabaseBlock (T221075)
139 $blocks = DatabaseBlock
::newListFromTarget( $user, null, $fromMaster );
140 $this->getCookieBlock( $blocks, $user, $request );
144 // Case #3: checking whether a user's account is blocked
145 // TODO: remove dependency on DatabaseBlock (T221075)
146 $blocks = DatabaseBlock
::newListFromTarget( $user, null, $fromMaster );
150 // Filter out any duplicated blocks, e.g. from the cookie
151 $blocks = $this->getUniqueBlocks( $blocks );
154 if ( count( $blocks ) > 0 ) {
155 if ( count( $blocks ) === 1 ) {
156 $block = $blocks[ 0 ];
158 $block = new CompositeBlock( [
160 'byText' => 'MediaWiki default',
161 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
162 'originalBlocks' => $blocks,
167 Hooks
::run( 'GetUserBlock', [ clone $user, $ip, &$block ] );
173 * Get the cookie block, if there is one.
175 * @param AbstractBlock[] &$blocks
176 * @param UserIdentity $user
177 * @param WebRequest $request
180 private function getCookieBlock( &$blocks, UserIdentity
$user, WebRequest
$request ) {
181 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
182 if ( $cookieBlock instanceof DatabaseBlock
) {
183 $blocks[] = $cookieBlock;
188 * Check for any additional blocks against the IP address or any IPs in the XFF header.
190 * @param AbstractBlock[] &$blocks Blocks found so far
191 * @param WebRequest $request
192 * @param bool $isAnon The user is logged out
193 * @param bool $fromMaster
196 private function getAdditionalIpBlocks( &$blocks, WebRequest
$request, $isAnon, $fromMaster ) {
197 $ip = $request->getIP();
200 if ( !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) ) {
202 if ( $this->isLocallyBlockedProxy( $ip ) ) {
203 $blocks[] = new SystemBlock( [
204 'byText' => wfMessage( 'proxyblocker' )->text(),
205 'reason' => wfMessage( 'proxyblockreason' )->plain(),
207 'systemBlock' => 'proxy',
209 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
210 $blocks[] = new SystemBlock( [
211 'byText' => wfMessage( 'sorbs' )->text(),
212 'reason' => wfMessage( 'sorbsreason' )->plain(),
214 'systemBlock' => 'dnsbl',
220 if ( $isAnon && IP
::isInRanges( $ip, $this->options
->get( 'SoftBlockRanges' ) ) ) {
221 $blocks[] = new SystemBlock( [
223 'byText' => 'MediaWiki default',
224 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
226 'systemBlock' => 'wgSoftBlockRanges',
230 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
231 if ( $this->options
->get( 'ApplyIpBlocksToXff' )
232 && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) )
234 $xff = $request->getHeader( 'X-Forwarded-For' );
235 $xff = array_map( 'trim', explode( ',', $xff ) );
236 $xff = array_diff( $xff, [ $ip ] );
237 // TODO: remove dependency on DatabaseBlock (T221075)
238 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, $fromMaster );
239 $blocks = array_merge( $blocks, $xffblocks );
244 * Given a list of blocks, return a list of unique blocks.
246 * This usually means that each block has a unique ID. For a block with ID null,
247 * if it's an autoblock, it will be filtered out if the parent block is present;
248 * if not, it is assumed to be a unique system block, and kept.
250 * @param AbstractBlock[] $blocks
251 * @return AbstractBlock[]
253 private function getUniqueBlocks( array $blocks ) {
255 $databaseBlocks = [];
257 foreach ( $blocks as $block ) {
258 if ( $block instanceof SystemBlock
) {
259 $systemBlocks[] = $block;
260 } elseif ( $block->getType() === DatabaseBlock
::TYPE_AUTO
) {
261 /** @var DatabaseBlock $block */
262 '@phan-var DatabaseBlock $block';
263 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
264 $databaseBlocks[$block->getParentBlockId()] = $block;
267 $databaseBlocks[$block->getId()] = $block;
271 return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
275 * Try to load a block from an ID given in a cookie value. If the block is invalid
276 * doesn't exist, or the cookie value is malformed, remove the cookie.
278 * @param UserIdentity $user
279 * @param WebRequest $request
280 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
282 private function getBlockFromCookieValue(
286 $cookieValue = $request->getCookie( 'BlockID' );
287 if ( is_null( $cookieValue ) ) {
291 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
292 if ( !is_null( $blockCookieId ) ) {
293 // TODO: remove dependency on DatabaseBlock (T221075)
294 $block = DatabaseBlock
::newFromID( $blockCookieId );
296 $block instanceof DatabaseBlock
&&
297 $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
303 $this->clearBlockCookie( $request->response() );
309 * Check if the block loaded from the cookie should be applied.
311 * @param DatabaseBlock $block
312 * @param bool $isAnon The user is logged out
313 * @return bool The block sould be applied
315 private function shouldApplyCookieBlock( DatabaseBlock
$block, $isAnon ) {
316 if ( !$block->isExpired() ) {
317 switch ( $block->getType() ) {
318 case DatabaseBlock
::TYPE_IP
:
319 case DatabaseBlock
::TYPE_RANGE
:
320 // If block is type IP or IP range, load only
321 // if user is not logged in (T152462)
323 $this->options
->get( 'CookieSetOnIpBlock' );
324 case DatabaseBlock
::TYPE_USER
:
325 return $block->isAutoblocking() &&
326 $this->options
->get( 'CookieSetOnAutoblock' );
335 * Check if an IP address is in the local proxy list
340 private function isLocallyBlockedProxy( $ip ) {
341 $proxyList = $this->options
->get( 'ProxyList' );
346 if ( !is_array( $proxyList ) ) {
347 // Load values from the specified file
348 $proxyList = array_map( 'trim', file( $proxyList ) );
351 $proxyListIPSet = new IPSet( $proxyList );
352 return $proxyListIPSet->match( $ip );
356 * Whether the given IP is in a DNS blacklist.
358 * @param string $ip IP to check
359 * @param bool $checkWhitelist Whether to check the whitelist first
360 * @return bool True if blacklisted.
362 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
363 if ( !$this->options
->get( 'EnableDnsBlacklist' ) ||
364 ( $checkWhitelist && in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) )
369 return $this->inDnsBlacklist( $ip, $this->options
->get( 'DnsBlacklistUrls' ) );
373 * Whether the given IP is in a given DNS blacklist.
375 * @param string $ip IP to check
376 * @param array $bases Array of Strings: URL of the DNS blacklist
377 * @return bool True if blacklisted.
379 private function inDnsBlacklist( $ip, array $bases ) {
381 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
382 if ( IP
::isIPv4( $ip ) ) {
383 // Reverse IP, T23255
384 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
386 foreach ( $bases as $base ) {
388 // If we have an access key, use that too (ProjectHoneypot, etc.)
390 if ( is_array( $base ) ) {
391 if ( count( $base ) >= 2 ) {
392 // Access key is 1, base URL is 0
393 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
395 $hostname = "$ipReversed.{$base[0]}";
397 $basename = $base[0];
399 $hostname = "$ipReversed.$base";
403 $ipList = $this->checkHost( $hostname );
407 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
413 $this->logger
->debug( "Requested $hostname, not found in $basename." );
421 * Wrapper for mocking in tests.
423 * @param string $hostname DNSBL query
424 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
426 protected function checkHost( $hostname ) {
427 return gethostbynamel( $hostname );
431 * Set the 'BlockID' cookie depending on block type and user authentication status.
436 public function trackBlockWithCookie( User
$user ) {
437 $request = $user->getRequest();
438 if ( $request->getCookie( 'BlockID' ) !== null ) {
439 // User already has a block cookie
443 // Defer checks until the user has been fully loaded to avoid circular dependency
444 // of User on itself (T180050 and T226777)
445 DeferredUpdates
::addCallableUpdate(
446 function () use ( $user, $request ) {
447 $block = $user->getBlock();
448 $response = $request->response();
449 $isAnon = $user->isAnon();
452 if ( $block instanceof CompositeBlock
) {
453 // TODO: Improve on simply tracking the first trackable block (T225654)
454 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
455 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
456 '@phan-var DatabaseBlock $originalBlock';
457 $this->setBlockCookie( $originalBlock, $response );
462 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
463 '@phan-var DatabaseBlock $block';
464 $this->setBlockCookie( $block, $response );
469 DeferredUpdates
::PRESEND
474 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
475 * the same as the block's, to a maximum of 24 hours.
478 * @internal Should be private.
479 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
480 * @param DatabaseBlock $block
481 * @param WebResponse $response The response on which to set the cookie.
483 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
484 // Calculate the default expiry time.
485 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
487 // Use the block's expiry time only if it's less than the default.
488 $expiryTime = $block->getExpiry();
489 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
490 $expiryTime = $maxExpiryTime;
493 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
494 $expiryValue = DateTime
::createFromFormat(
497 new DateTimeZone( 'UTC' )
499 $cookieOptions = [ 'httpOnly' => false ];
500 $cookieValue = $this->getCookieValue( $block );
501 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
505 * Check if the block should be tracked with a cookie.
507 * @param AbstractBlock $block
508 * @param bool $isAnon The user is logged out
509 * @return bool The block sould be tracked with a cookie
511 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
512 if ( $block instanceof DatabaseBlock
) {
513 switch ( $block->getType() ) {
514 case DatabaseBlock
::TYPE_IP
:
515 case DatabaseBlock
::TYPE_RANGE
:
516 return $isAnon && $this->options
->get( 'CookieSetOnIpBlock' );
517 case DatabaseBlock
::TYPE_USER
:
519 $this->options
->get( 'CookieSetOnAutoblock' ) &&
520 $block->isAutoblocking();
529 * Unset the 'BlockID' cookie.
532 * @param WebResponse $response
534 public static function clearBlockCookie( WebResponse
$response ) {
535 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
539 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
540 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
543 * @internal Should be private.
544 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
545 * @param string $cookieValue The string in which to find the ID.
546 * @return int|null The block ID, or null if the HMAC is present and invalid.
548 public function getIdFromCookieValue( $cookieValue ) {
549 // The cookie value must start with a number
550 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
554 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
555 $bangPos = strpos( $cookieValue, '!' );
556 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
557 if ( !$this->options
->get( 'SecretKey' ) ) {
558 // If there's no secret key, just use the ID as given.
561 $storedHmac = substr( $cookieValue, $bangPos +
1 );
562 $calculatedHmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
563 if ( $calculatedHmac === $storedHmac ) {
571 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
572 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
576 * @internal Should be private.
577 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
578 * @param DatabaseBlock $block
579 * @return string The block ID, probably concatenated with "!" and the HMAC.
581 public function getCookieValue( DatabaseBlock
$block ) {
582 $id = $block->getId();
583 if ( !$this->options
->get( 'SecretKey' ) ) {
584 // If there's no secret key, don't append a HMAC.
587 $hmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
588 $cookieValue = $id . '!' . $hmac;