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
;
38 * A service class for checking blocks.
39 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
41 * @since 1.34 Refactored from User and Block.
45 * TODO Make this a const when HHVM support is dropped (T192166)
50 public static $constructorOptions = [
52 'CookieSetOnAutoblock',
63 * @param ServiceOptions $options
64 * @param PermissionManager $permissionManager
66 public function __construct(
67 ServiceOptions
$options,
68 PermissionManager
$permissionManager
70 $options->assertRequiredOptions( self
::$constructorOptions );
71 $this->options
= $options;
72 $this->permissionManager
= $permissionManager;
76 * Get the blocks that apply to a user. If there is only one, return that, otherwise
77 * return a composite block that combines the strictest features of the applicable
80 * Different blocks may be sought, depending on the user and their permissions. The
82 * (1) The global user (and can be affected by IP blocks). The global request object
83 * is needed for checking the IP address, the XFF header and the cookies.
84 * (2) The global user (and exempt from IP blocks). The global request object is
85 * needed for checking the cookies.
86 * (3) Another user (not the global user). No request object is available or needed;
87 * just look for a block against the user account.
89 * Cases #1 and #2 check whether the global user is blocked in practice; the block
90 * may due to their user account being blocked or to an IP address block or cookie
91 * block (or multiple of these). Case #3 simply checks whether a user's account is
92 * blocked, and does not determine whether the person using that account is affected
93 * in practice by any IP address or cookie blocks.
95 * @internal This should only be called by User::getBlockedStatus
97 * @param WebRequest|null $request The global request object if the user is the
98 * global user (cases #1 and #2), otherwise null (case #3). The IP address and
99 * information from the request header are needed to find some types of blocks.
100 * @param bool $fromReplica Whether to check the replica DB first.
101 * To improve performance, non-critical checks are done against replica DBs.
102 * Check when actually saving should be done against master.
103 * @return AbstractBlock|null The most relevant block, or null if there is no block.
105 public function getUserBlock( User
$user, $request, $fromReplica ) {
106 $fromMaster = !$fromReplica;
109 // If this is the global user, they may be affected by IP blocks (case #1),
110 // or they may be exempt (case #2). If affected, look for additional blocks
111 // against the IP address.
112 $checkIpBlocks = $request &&
113 !$this->permissionManager
->userHasRight( $user, 'ipblock-exempt' );
115 if ( $request && $checkIpBlocks ) {
117 // Case #1: checking the global user, including IP blocks
118 $ip = $request->getIP();
119 // TODO: remove dependency on DatabaseBlock (T221075)
120 $blocks = DatabaseBlock
::newListFromTarget( $user, $ip, $fromMaster );
121 $this->getAdditionalIpBlocks( $blocks, $request, !$user->isRegistered(), $fromMaster );
122 $this->getCookieBlock( $blocks, $user, $request );
124 } elseif ( $request ) {
126 // Case #2: checking the global user, but they are exempt from IP blocks
127 // TODO: remove dependency on DatabaseBlock (T221075)
128 $blocks = DatabaseBlock
::newListFromTarget( $user, null, $fromMaster );
129 $this->getCookieBlock( $blocks, $user, $request );
133 // Case #3: checking whether a user's account is blocked
134 // TODO: remove dependency on DatabaseBlock (T221075)
135 $blocks = DatabaseBlock
::newListFromTarget( $user, null, $fromMaster );
139 // Filter out any duplicated blocks, e.g. from the cookie
140 $blocks = $this->getUniqueBlocks( $blocks );
143 if ( count( $blocks ) > 0 ) {
144 if ( count( $blocks ) === 1 ) {
145 $block = $blocks[ 0 ];
147 $block = new CompositeBlock( [
149 'byText' => 'MediaWiki default',
150 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
151 'originalBlocks' => $blocks,
156 Hooks
::run( 'GetUserBlock', [ clone $user, $ip, &$block ] );
162 * Get the cookie block, if there is one.
164 * @param AbstractBlock[] &$blocks
165 * @param UserIdentity $user
166 * @param WebRequest $request
169 private function getCookieBlock( &$blocks, UserIdentity
$user, WebRequest
$request ) {
170 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
171 if ( $cookieBlock instanceof DatabaseBlock
) {
172 $blocks[] = $cookieBlock;
177 * Check for any additional blocks against the IP address or any IPs in the XFF header.
179 * @param AbstractBlock[] &$blocks Blocks found so far
180 * @param WebRequest $request
181 * @param bool $isAnon The user is logged out
182 * @param bool $fromMaster
185 private function getAdditionalIpBlocks( &$blocks, WebRequest
$request, $isAnon, $fromMaster ) {
186 $ip = $request->getIP();
189 if ( !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) ) {
191 if ( $this->isLocallyBlockedProxy( $ip ) ) {
192 $blocks[] = new SystemBlock( [
193 'byText' => wfMessage( 'proxyblocker' )->text(),
194 'reason' => wfMessage( 'proxyblockreason' )->plain(),
196 'systemBlock' => 'proxy',
198 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
199 $blocks[] = new SystemBlock( [
200 'byText' => wfMessage( 'sorbs' )->text(),
201 'reason' => wfMessage( 'sorbsreason' )->plain(),
203 'systemBlock' => 'dnsbl',
209 if ( $isAnon && IP
::isInRanges( $ip, $this->options
->get( 'SoftBlockRanges' ) ) ) {
210 $blocks[] = new SystemBlock( [
212 'byText' => 'MediaWiki default',
213 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
215 'systemBlock' => 'wgSoftBlockRanges',
219 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
220 if ( $this->options
->get( 'ApplyIpBlocksToXff' )
221 && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) )
223 $xff = $request->getHeader( 'X-Forwarded-For' );
224 $xff = array_map( 'trim', explode( ',', $xff ) );
225 $xff = array_diff( $xff, [ $ip ] );
226 // TODO: remove dependency on DatabaseBlock (T221075)
227 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, $fromMaster );
228 $blocks = array_merge( $blocks, $xffblocks );
233 * Given a list of blocks, return a list of unique blocks.
235 * This usually means that each block has a unique ID. For a block with ID null,
236 * if it's an autoblock, it will be filtered out if the parent block is present;
237 * if not, it is assumed to be a unique system block, and kept.
239 * @param AbstractBlock[] $blocks
240 * @return AbstractBlock[]
242 private function getUniqueBlocks( array $blocks ) {
244 $databaseBlocks = [];
246 foreach ( $blocks as $block ) {
247 if ( $block instanceof SystemBlock
) {
248 $systemBlocks[] = $block;
249 } elseif ( $block->getType() === DatabaseBlock
::TYPE_AUTO
) {
250 /** @var DatabaseBlock $block */
251 '@phan-var DatabaseBlock $block';
252 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
253 $databaseBlocks[$block->getParentBlockId()] = $block;
256 $databaseBlocks[$block->getId()] = $block;
260 return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
264 * Try to load a block from an ID given in a cookie value. If the block is invalid
265 * doesn't exist, or the cookie value is malformed, remove the cookie.
267 * @param UserIdentity $user
268 * @param WebRequest $request
269 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
271 private function getBlockFromCookieValue(
275 $cookieValue = $request->getCookie( 'BlockID' );
276 if ( is_null( $cookieValue ) ) {
280 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
281 if ( !is_null( $blockCookieId ) ) {
282 // TODO: remove dependency on DatabaseBlock (T221075)
283 $block = DatabaseBlock
::newFromID( $blockCookieId );
285 $block instanceof DatabaseBlock
&&
286 $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
292 $this->clearBlockCookie( $request->response() );
298 * Check if the block loaded from the cookie should be applied.
300 * @param DatabaseBlock $block
301 * @param bool $isAnon The user is logged out
302 * @return bool The block sould be applied
304 private function shouldApplyCookieBlock( DatabaseBlock
$block, $isAnon ) {
305 if ( !$block->isExpired() ) {
306 switch ( $block->getType() ) {
307 case DatabaseBlock
::TYPE_IP
:
308 case DatabaseBlock
::TYPE_RANGE
:
309 // If block is type IP or IP range, load only
310 // if user is not logged in (T152462)
312 $this->options
->get( 'CookieSetOnIpBlock' );
313 case DatabaseBlock
::TYPE_USER
:
314 return $block->isAutoblocking() &&
315 $this->options
->get( 'CookieSetOnAutoblock' );
324 * Check if an IP address is in the local proxy list
329 private function isLocallyBlockedProxy( $ip ) {
330 $proxyList = $this->options
->get( 'ProxyList' );
335 if ( !is_array( $proxyList ) ) {
336 // Load values from the specified file
337 $proxyList = array_map( 'trim', file( $proxyList ) );
340 $proxyListIPSet = new IPSet( $proxyList );
341 return $proxyListIPSet->match( $ip );
345 * Whether the given IP is in a DNS blacklist.
347 * @param string $ip IP to check
348 * @param bool $checkWhitelist Whether to check the whitelist first
349 * @return bool True if blacklisted.
351 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
352 if ( !$this->options
->get( 'EnableDnsBlacklist' ) ||
353 ( $checkWhitelist && in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) )
358 return $this->inDnsBlacklist( $ip, $this->options
->get( 'DnsBlacklistUrls' ) );
362 * Whether the given IP is in a given DNS blacklist.
364 * @param string $ip IP to check
365 * @param array $bases Array of Strings: URL of the DNS blacklist
366 * @return bool True if blacklisted.
368 private function inDnsBlacklist( $ip, array $bases ) {
370 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
371 if ( IP
::isIPv4( $ip ) ) {
372 // Reverse IP, T23255
373 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
375 foreach ( $bases as $base ) {
377 // If we have an access key, use that too (ProjectHoneypot, etc.)
379 if ( is_array( $base ) ) {
380 if ( count( $base ) >= 2 ) {
381 // Access key is 1, base URL is 0
382 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
384 $hostname = "$ipReversed.{$base[0]}";
386 $basename = $base[0];
388 $hostname = "$ipReversed.$base";
392 $ipList = $this->checkHost( $hostname );
397 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
403 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
411 * Wrapper for mocking in tests.
413 * @param string $hostname DNSBL query
414 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
416 protected function checkHost( $hostname ) {
417 return gethostbynamel( $hostname );
421 * Set the 'BlockID' cookie depending on block type and user authentication status.
426 public function trackBlockWithCookie( User
$user ) {
427 $request = $user->getRequest();
428 if ( $request->getCookie( 'BlockID' ) !== null ) {
429 // User already has a block cookie
433 // Defer checks until the user has been fully loaded to avoid circular dependency
434 // of User on itself (T180050 and T226777)
435 DeferredUpdates
::addCallableUpdate(
436 function () use ( $user, $request ) {
437 $block = $user->getBlock();
438 $response = $request->response();
439 $isAnon = $user->isAnon();
442 if ( $block instanceof CompositeBlock
) {
443 // TODO: Improve on simply tracking the first trackable block (T225654)
444 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
445 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
446 $this->setBlockCookie( $originalBlock, $response );
451 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
452 $this->setBlockCookie( $block, $response );
457 DeferredUpdates
::PRESEND
462 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
463 * the same as the block's, to a maximum of 24 hours.
466 * @internal Should be private.
467 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
468 * @param DatabaseBlock $block
469 * @param WebResponse $response The response on which to set the cookie.
471 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
472 // Calculate the default expiry time.
473 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
475 // Use the block's expiry time only if it's less than the default.
476 $expiryTime = $block->getExpiry();
477 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
478 $expiryTime = $maxExpiryTime;
481 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
482 $expiryValue = DateTime
::createFromFormat(
485 new DateTimeZone( 'UTC' )
487 $cookieOptions = [ 'httpOnly' => false ];
488 $cookieValue = $this->getCookieValue( $block );
489 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
493 * Check if the block should be tracked with a cookie.
495 * @param AbstractBlock $block
496 * @param bool $isAnon The user is logged out
497 * @return bool The block sould be tracked with a cookie
499 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
500 if ( $block instanceof DatabaseBlock
) {
501 switch ( $block->getType() ) {
502 case DatabaseBlock
::TYPE_IP
:
503 case DatabaseBlock
::TYPE_RANGE
:
504 return $isAnon && $this->options
->get( 'CookieSetOnIpBlock' );
505 case DatabaseBlock
::TYPE_USER
:
507 $this->options
->get( 'CookieSetOnAutoblock' ) &&
508 $block->isAutoblocking();
517 * Unset the 'BlockID' cookie.
520 * @param WebResponse $response
522 public static function clearBlockCookie( WebResponse
$response ) {
523 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
527 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
528 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
531 * @internal Should be private.
532 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
533 * @param string $cookieValue The string in which to find the ID.
534 * @return int|null The block ID, or null if the HMAC is present and invalid.
536 public function getIdFromCookieValue( $cookieValue ) {
537 // The cookie value must start with a number
538 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
542 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
543 $bangPos = strpos( $cookieValue, '!' );
544 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
545 if ( !$this->options
->get( 'SecretKey' ) ) {
546 // If there's no secret key, just use the ID as given.
549 $storedHmac = substr( $cookieValue, $bangPos +
1 );
550 $calculatedHmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
551 if ( $calculatedHmac === $storedHmac ) {
559 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
560 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
564 * @internal Should be private.
565 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
566 * @param DatabaseBlock $block
567 * @return string The block ID, probably concatenated with "!" and the HMAC.
569 public function getCookieValue( DatabaseBlock
$block ) {
570 $id = $block->getId();
571 if ( !$this->options
->get( 'SecretKey' ) ) {
572 // If there's no secret key, don't append a HMAC.
575 $hmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
576 $cookieValue = $id . '!' . $hmac;