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.
44 /** @var PermissionManager */
45 private $permissionManager;
47 /** @var ServiceOptions */
51 * TODO Make this a const when HHVM support is dropped (T192166)
56 public static $constructorOptions = [
58 'CookieSetOnAutoblock',
69 * @param ServiceOptions $options
70 * @param PermissionManager $permissionManager
72 public function __construct(
73 ServiceOptions
$options,
74 PermissionManager
$permissionManager
76 $options->assertRequiredOptions( self
::$constructorOptions );
77 $this->options
= $options;
78 $this->permissionManager
= $permissionManager;
82 * Get the blocks that apply to a user. If there is only one, return that, otherwise
83 * return a composite block that combines the strictest features of the applicable
86 * Different blocks may be sought, depending on the user and their permissions. The
88 * (1) The global user (and can be affected by IP blocks). The global request object
89 * is needed for checking the IP address, the XFF header and the cookies.
90 * (2) The global user (and exempt from IP blocks). The global request object is
91 * needed for checking the cookies.
92 * (3) Another user (not the global user). No request object is available or needed;
93 * just look for a block against the user account.
95 * Cases #1 and #2 check whether the global user is blocked in practice; the block
96 * may due to their user account being blocked or to an IP address block or cookie
97 * block (or multiple of these). Case #3 simply checks whether a user's account is
98 * blocked, and does not determine whether the person using that account is affected
99 * in practice by any IP address or cookie blocks.
101 * @internal This should only be called by User::getBlockedStatus
103 * @param WebRequest|null $request The global request object if the user is the
104 * global user (cases #1 and #2), otherwise null (case #3). The IP address and
105 * information from the request header are needed to find some types of blocks.
106 * @param bool $fromReplica Whether to check the replica DB first.
107 * To improve performance, non-critical checks are done against replica DBs.
108 * Check when actually saving should be done against master.
109 * @return AbstractBlock|null The most relevant block, or null if there is no block.
111 public function getUserBlock( User
$user, $request, $fromReplica ) {
112 $fromMaster = !$fromReplica;
115 // If this is the global user, they may be affected by IP blocks (case #1),
116 // or they may be exempt (case #2). If affected, look for additional blocks
117 // against the IP address.
118 $checkIpBlocks = $request &&
119 !$this->permissionManager
->userHasRight( $user, 'ipblock-exempt' );
121 if ( $request && $checkIpBlocks ) {
123 // Case #1: checking the global user, including IP blocks
124 $ip = $request->getIP();
125 // TODO: remove dependency on DatabaseBlock (T221075)
126 $blocks = DatabaseBlock
::newListFromTarget( $user, $ip, $fromMaster );
127 $this->getAdditionalIpBlocks( $blocks, $request, !$user->isRegistered(), $fromMaster );
128 $this->getCookieBlock( $blocks, $user, $request );
130 } elseif ( $request ) {
132 // Case #2: checking the global user, but they are exempt from IP blocks
133 // TODO: remove dependency on DatabaseBlock (T221075)
134 $blocks = DatabaseBlock
::newListFromTarget( $user, null, $fromMaster );
135 $this->getCookieBlock( $blocks, $user, $request );
139 // Case #3: checking whether a user's account is blocked
140 // TODO: remove dependency on DatabaseBlock (T221075)
141 $blocks = DatabaseBlock
::newListFromTarget( $user, null, $fromMaster );
145 // Filter out any duplicated blocks, e.g. from the cookie
146 $blocks = $this->getUniqueBlocks( $blocks );
149 if ( count( $blocks ) > 0 ) {
150 if ( count( $blocks ) === 1 ) {
151 $block = $blocks[ 0 ];
153 $block = new CompositeBlock( [
155 'byText' => 'MediaWiki default',
156 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
157 'originalBlocks' => $blocks,
162 Hooks
::run( 'GetUserBlock', [ clone $user, $ip, &$block ] );
168 * Get the cookie block, if there is one.
170 * @param AbstractBlock[] &$blocks
171 * @param UserIdentity $user
172 * @param WebRequest $request
175 private function getCookieBlock( &$blocks, UserIdentity
$user, WebRequest
$request ) {
176 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
177 if ( $cookieBlock instanceof DatabaseBlock
) {
178 $blocks[] = $cookieBlock;
183 * Check for any additional blocks against the IP address or any IPs in the XFF header.
185 * @param AbstractBlock[] &$blocks Blocks found so far
186 * @param WebRequest $request
187 * @param bool $isAnon The user is logged out
188 * @param bool $fromMaster
191 private function getAdditionalIpBlocks( &$blocks, WebRequest
$request, $isAnon, $fromMaster ) {
192 $ip = $request->getIP();
195 if ( !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) ) {
197 if ( $this->isLocallyBlockedProxy( $ip ) ) {
198 $blocks[] = new SystemBlock( [
199 'byText' => wfMessage( 'proxyblocker' )->text(),
200 'reason' => wfMessage( 'proxyblockreason' )->plain(),
202 'systemBlock' => 'proxy',
204 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
205 $blocks[] = new SystemBlock( [
206 'byText' => wfMessage( 'sorbs' )->text(),
207 'reason' => wfMessage( 'sorbsreason' )->plain(),
209 'systemBlock' => 'dnsbl',
215 if ( $isAnon && IP
::isInRanges( $ip, $this->options
->get( 'SoftBlockRanges' ) ) ) {
216 $blocks[] = new SystemBlock( [
218 'byText' => 'MediaWiki default',
219 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
221 'systemBlock' => 'wgSoftBlockRanges',
225 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
226 if ( $this->options
->get( 'ApplyIpBlocksToXff' )
227 && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) )
229 $xff = $request->getHeader( 'X-Forwarded-For' );
230 $xff = array_map( 'trim', explode( ',', $xff ) );
231 $xff = array_diff( $xff, [ $ip ] );
232 // TODO: remove dependency on DatabaseBlock (T221075)
233 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, $fromMaster );
234 $blocks = array_merge( $blocks, $xffblocks );
239 * Given a list of blocks, return a list of unique blocks.
241 * This usually means that each block has a unique ID. For a block with ID null,
242 * if it's an autoblock, it will be filtered out if the parent block is present;
243 * if not, it is assumed to be a unique system block, and kept.
245 * @param AbstractBlock[] $blocks
246 * @return AbstractBlock[]
248 private function getUniqueBlocks( array $blocks ) {
250 $databaseBlocks = [];
252 foreach ( $blocks as $block ) {
253 if ( $block instanceof SystemBlock
) {
254 $systemBlocks[] = $block;
255 } elseif ( $block->getType() === DatabaseBlock
::TYPE_AUTO
) {
256 /** @var DatabaseBlock $block */
257 '@phan-var DatabaseBlock $block';
258 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
259 $databaseBlocks[$block->getParentBlockId()] = $block;
262 $databaseBlocks[$block->getId()] = $block;
266 return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
270 * Try to load a block from an ID given in a cookie value. If the block is invalid
271 * doesn't exist, or the cookie value is malformed, remove the cookie.
273 * @param UserIdentity $user
274 * @param WebRequest $request
275 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
277 private function getBlockFromCookieValue(
281 $cookieValue = $request->getCookie( 'BlockID' );
282 if ( is_null( $cookieValue ) ) {
286 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
287 if ( !is_null( $blockCookieId ) ) {
288 // TODO: remove dependency on DatabaseBlock (T221075)
289 $block = DatabaseBlock
::newFromID( $blockCookieId );
291 $block instanceof DatabaseBlock
&&
292 $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
298 $this->clearBlockCookie( $request->response() );
304 * Check if the block loaded from the cookie should be applied.
306 * @param DatabaseBlock $block
307 * @param bool $isAnon The user is logged out
308 * @return bool The block sould be applied
310 private function shouldApplyCookieBlock( DatabaseBlock
$block, $isAnon ) {
311 if ( !$block->isExpired() ) {
312 switch ( $block->getType() ) {
313 case DatabaseBlock
::TYPE_IP
:
314 case DatabaseBlock
::TYPE_RANGE
:
315 // If block is type IP or IP range, load only
316 // if user is not logged in (T152462)
318 $this->options
->get( 'CookieSetOnIpBlock' );
319 case DatabaseBlock
::TYPE_USER
:
320 return $block->isAutoblocking() &&
321 $this->options
->get( 'CookieSetOnAutoblock' );
330 * Check if an IP address is in the local proxy list
335 private function isLocallyBlockedProxy( $ip ) {
336 $proxyList = $this->options
->get( 'ProxyList' );
341 if ( !is_array( $proxyList ) ) {
342 // Load values from the specified file
343 $proxyList = array_map( 'trim', file( $proxyList ) );
346 $proxyListIPSet = new IPSet( $proxyList );
347 return $proxyListIPSet->match( $ip );
351 * Whether the given IP is in a DNS blacklist.
353 * @param string $ip IP to check
354 * @param bool $checkWhitelist Whether to check the whitelist first
355 * @return bool True if blacklisted.
357 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
358 if ( !$this->options
->get( 'EnableDnsBlacklist' ) ||
359 ( $checkWhitelist && in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) )
364 return $this->inDnsBlacklist( $ip, $this->options
->get( 'DnsBlacklistUrls' ) );
368 * Whether the given IP is in a given DNS blacklist.
370 * @param string $ip IP to check
371 * @param array $bases Array of Strings: URL of the DNS blacklist
372 * @return bool True if blacklisted.
374 private function inDnsBlacklist( $ip, array $bases ) {
376 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
377 if ( IP
::isIPv4( $ip ) ) {
378 // Reverse IP, T23255
379 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
381 foreach ( $bases as $base ) {
383 // If we have an access key, use that too (ProjectHoneypot, etc.)
385 if ( is_array( $base ) ) {
386 if ( count( $base ) >= 2 ) {
387 // Access key is 1, base URL is 0
388 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
390 $hostname = "$ipReversed.{$base[0]}";
392 $basename = $base[0];
394 $hostname = "$ipReversed.$base";
398 $ipList = $this->checkHost( $hostname );
403 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
409 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
417 * Wrapper for mocking in tests.
419 * @param string $hostname DNSBL query
420 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
422 protected function checkHost( $hostname ) {
423 return gethostbynamel( $hostname );
427 * Set the 'BlockID' cookie depending on block type and user authentication status.
432 public function trackBlockWithCookie( User
$user ) {
433 $request = $user->getRequest();
434 if ( $request->getCookie( 'BlockID' ) !== null ) {
435 // User already has a block cookie
439 // Defer checks until the user has been fully loaded to avoid circular dependency
440 // of User on itself (T180050 and T226777)
441 DeferredUpdates
::addCallableUpdate(
442 function () use ( $user, $request ) {
443 $block = $user->getBlock();
444 $response = $request->response();
445 $isAnon = $user->isAnon();
448 if ( $block instanceof CompositeBlock
) {
449 // TODO: Improve on simply tracking the first trackable block (T225654)
450 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
451 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
452 $this->setBlockCookie( $originalBlock, $response );
457 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
458 $this->setBlockCookie( $block, $response );
463 DeferredUpdates
::PRESEND
468 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
469 * the same as the block's, to a maximum of 24 hours.
472 * @internal Should be private.
473 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
474 * @param DatabaseBlock $block
475 * @param WebResponse $response The response on which to set the cookie.
477 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
478 // Calculate the default expiry time.
479 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
481 // Use the block's expiry time only if it's less than the default.
482 $expiryTime = $block->getExpiry();
483 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
484 $expiryTime = $maxExpiryTime;
487 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
488 $expiryValue = DateTime
::createFromFormat(
491 new DateTimeZone( 'UTC' )
493 $cookieOptions = [ 'httpOnly' => false ];
494 $cookieValue = $this->getCookieValue( $block );
495 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
499 * Check if the block should be tracked with a cookie.
501 * @param AbstractBlock $block
502 * @param bool $isAnon The user is logged out
503 * @return bool The block sould be tracked with a cookie
505 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
506 if ( $block instanceof DatabaseBlock
) {
507 switch ( $block->getType() ) {
508 case DatabaseBlock
::TYPE_IP
:
509 case DatabaseBlock
::TYPE_RANGE
:
510 return $isAnon && $this->options
->get( 'CookieSetOnIpBlock' );
511 case DatabaseBlock
::TYPE_USER
:
513 $this->options
->get( 'CookieSetOnAutoblock' ) &&
514 $block->isAutoblocking();
523 * Unset the 'BlockID' cookie.
526 * @param WebResponse $response
528 public static function clearBlockCookie( WebResponse
$response ) {
529 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
533 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
534 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
537 * @internal Should be private.
538 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
539 * @param string $cookieValue The string in which to find the ID.
540 * @return int|null The block ID, or null if the HMAC is present and invalid.
542 public function getIdFromCookieValue( $cookieValue ) {
543 // The cookie value must start with a number
544 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
548 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
549 $bangPos = strpos( $cookieValue, '!' );
550 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
551 if ( !$this->options
->get( 'SecretKey' ) ) {
552 // If there's no secret key, just use the ID as given.
555 $storedHmac = substr( $cookieValue, $bangPos +
1 );
556 $calculatedHmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
557 if ( $calculatedHmac === $storedHmac ) {
565 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
566 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
570 * @internal Should be private.
571 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
572 * @param DatabaseBlock $block
573 * @return string The block ID, probably concatenated with "!" and the HMAC.
575 public function getCookieValue( DatabaseBlock
$block ) {
576 $id = $block->getId();
577 if ( !$this->options
->get( 'SecretKey' ) ) {
578 // If there's no secret key, don't append a HMAC.
581 $hmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
582 $cookieValue = $id . '!' . $hmac;