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 */
52 * TODO Make this a const when HHVM support is dropped (T192166)
57 public static $constructorOptions = [
59 'CookieSetOnAutoblock',
69 /** @var LoggerInterface */
73 * @param ServiceOptions $options
74 * @param PermissionManager $permissionManager
75 * @param LoggerInterface $logger
77 public function __construct(
78 ServiceOptions
$options,
79 PermissionManager
$permissionManager,
80 LoggerInterface
$logger
82 $options->assertRequiredOptions( self
::$constructorOptions );
83 $this->options
= $options;
84 $this->permissionManager
= $permissionManager;
85 $this->logger
= $logger;
89 * Get the blocks that apply to a user. If there is only one, return that, otherwise
90 * return a composite block that combines the strictest features of the applicable
93 * Different blocks may be sought, depending on the user and their permissions. The
95 * (1) The global user (and can be affected by IP blocks). The global request object
96 * is needed for checking the IP address, the XFF header and the cookies.
97 * (2) The global user (and exempt from IP blocks). The global request object is
98 * needed for checking the cookies.
99 * (3) Another user (not the global user). No request object is available or needed;
100 * just look for a block against the user account.
102 * Cases #1 and #2 check whether the global user is blocked in practice; the block
103 * may due to their user account being blocked or to an IP address block or cookie
104 * block (or multiple of these). Case #3 simply checks whether a user's account is
105 * blocked, and does not determine whether the person using that account is affected
106 * in practice by any IP address or cookie blocks.
108 * @internal This should only be called by User::getBlockedStatus
110 * @param WebRequest|null $request The global request object if the user is the
111 * global user (cases #1 and #2), otherwise null (case #3). The IP address and
112 * information from the request header are needed to find some types of blocks.
113 * @param bool $fromReplica Whether to check the replica DB first.
114 * To improve performance, non-critical checks are done against replica DBs.
115 * Check when actually saving should be done against master.
116 * @return AbstractBlock|null The most relevant block, or null if there is no block.
118 public function getUserBlock( User
$user, $request, $fromReplica ) {
119 $fromMaster = !$fromReplica;
122 // If this is the global user, they may be affected by IP blocks (case #1),
123 // or they may be exempt (case #2). If affected, look for additional blocks
124 // against the IP address.
125 $checkIpBlocks = $request &&
126 !$this->permissionManager
->userHasRight( $user, 'ipblock-exempt' );
128 if ( $request && $checkIpBlocks ) {
130 // Case #1: checking the global user, including IP blocks
131 $ip = $request->getIP();
132 // TODO: remove dependency on DatabaseBlock (T221075)
133 $blocks = DatabaseBlock
::newListFromTarget( $user, $ip, $fromMaster );
134 $this->getAdditionalIpBlocks( $blocks, $request, !$user->isRegistered(), $fromMaster );
135 $this->getCookieBlock( $blocks, $user, $request );
137 } elseif ( $request ) {
139 // Case #2: checking the global user, but they are exempt from IP blocks
140 // TODO: remove dependency on DatabaseBlock (T221075)
141 $blocks = DatabaseBlock
::newListFromTarget( $user, null, $fromMaster );
142 $this->getCookieBlock( $blocks, $user, $request );
146 // Case #3: checking whether a 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 'byText' => 'MediaWiki default',
163 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
164 'originalBlocks' => $blocks,
169 Hooks
::run( 'GetUserBlock', [ clone $user, $ip, &$block ] );
175 * Get the cookie block, if there is one.
177 * @param AbstractBlock[] &$blocks
178 * @param UserIdentity $user
179 * @param WebRequest $request
182 private function getCookieBlock( &$blocks, UserIdentity
$user, WebRequest
$request ) {
183 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
184 if ( $cookieBlock instanceof DatabaseBlock
) {
185 $blocks[] = $cookieBlock;
190 * Check for any additional blocks against the IP address or any IPs in the XFF header.
192 * @param AbstractBlock[] &$blocks Blocks found so far
193 * @param WebRequest $request
194 * @param bool $isAnon The user is logged out
195 * @param bool $fromMaster
198 private function getAdditionalIpBlocks( &$blocks, WebRequest
$request, $isAnon, $fromMaster ) {
199 $ip = $request->getIP();
202 if ( !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) ) {
204 if ( $this->isLocallyBlockedProxy( $ip ) ) {
205 $blocks[] = new SystemBlock( [
206 'byText' => wfMessage( 'proxyblocker' )->text(),
207 'reason' => wfMessage( 'proxyblockreason' )->plain(),
209 'systemBlock' => 'proxy',
211 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
212 $blocks[] = new SystemBlock( [
213 'byText' => wfMessage( 'sorbs' )->text(),
214 'reason' => wfMessage( 'sorbsreason' )->plain(),
216 'systemBlock' => 'dnsbl',
222 if ( $isAnon && IP
::isInRanges( $ip, $this->options
->get( 'SoftBlockRanges' ) ) ) {
223 $blocks[] = new SystemBlock( [
225 'byText' => 'MediaWiki default',
226 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
228 'systemBlock' => 'wgSoftBlockRanges',
232 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
233 if ( $this->options
->get( 'ApplyIpBlocksToXff' )
234 && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) )
236 $xff = $request->getHeader( 'X-Forwarded-For' );
237 $xff = array_map( 'trim', explode( ',', $xff ) );
238 $xff = array_diff( $xff, [ $ip ] );
239 // TODO: remove dependency on DatabaseBlock (T221075)
240 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, $fromMaster );
241 $blocks = array_merge( $blocks, $xffblocks );
246 * Given a list of blocks, return a list of unique blocks.
248 * This usually means that each block has a unique ID. For a block with ID null,
249 * if it's an autoblock, it will be filtered out if the parent block is present;
250 * if not, it is assumed to be a unique system block, and kept.
252 * @param AbstractBlock[] $blocks
253 * @return AbstractBlock[]
255 private function getUniqueBlocks( array $blocks ) {
257 $databaseBlocks = [];
259 foreach ( $blocks as $block ) {
260 if ( $block instanceof SystemBlock
) {
261 $systemBlocks[] = $block;
262 } elseif ( $block->getType() === DatabaseBlock
::TYPE_AUTO
) {
263 /** @var DatabaseBlock $block */
264 '@phan-var DatabaseBlock $block';
265 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
266 $databaseBlocks[$block->getParentBlockId()] = $block;
269 $databaseBlocks[$block->getId()] = $block;
273 return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
277 * Try to load a block from an ID given in a cookie value. If the block is invalid
278 * doesn't exist, or the cookie value is malformed, remove the cookie.
280 * @param UserIdentity $user
281 * @param WebRequest $request
282 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
284 private function getBlockFromCookieValue(
288 $cookieValue = $request->getCookie( 'BlockID' );
289 if ( is_null( $cookieValue ) ) {
293 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
294 if ( !is_null( $blockCookieId ) ) {
295 // TODO: remove dependency on DatabaseBlock (T221075)
296 $block = DatabaseBlock
::newFromID( $blockCookieId );
298 $block instanceof DatabaseBlock
&&
299 $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
305 $this->clearBlockCookie( $request->response() );
311 * Check if the block loaded from the cookie should be applied.
313 * @param DatabaseBlock $block
314 * @param bool $isAnon The user is logged out
315 * @return bool The block sould be applied
317 private function shouldApplyCookieBlock( DatabaseBlock
$block, $isAnon ) {
318 if ( !$block->isExpired() ) {
319 switch ( $block->getType() ) {
320 case DatabaseBlock
::TYPE_IP
:
321 case DatabaseBlock
::TYPE_RANGE
:
322 // If block is type IP or IP range, load only
323 // if user is not logged in (T152462)
325 $this->options
->get( 'CookieSetOnIpBlock' );
326 case DatabaseBlock
::TYPE_USER
:
327 return $block->isAutoblocking() &&
328 $this->options
->get( 'CookieSetOnAutoblock' );
337 * Check if an IP address is in the local proxy list
342 private function isLocallyBlockedProxy( $ip ) {
343 $proxyList = $this->options
->get( 'ProxyList' );
348 if ( !is_array( $proxyList ) ) {
349 // Load values from the specified file
350 $proxyList = array_map( 'trim', file( $proxyList ) );
353 $proxyListIPSet = new IPSet( $proxyList );
354 return $proxyListIPSet->match( $ip );
358 * Whether the given IP is in a DNS blacklist.
360 * @param string $ip IP to check
361 * @param bool $checkWhitelist Whether to check the whitelist first
362 * @return bool True if blacklisted.
364 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
365 if ( !$this->options
->get( 'EnableDnsBlacklist' ) ||
366 ( $checkWhitelist && in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) )
371 return $this->inDnsBlacklist( $ip, $this->options
->get( 'DnsBlacklistUrls' ) );
375 * Whether the given IP is in a given DNS blacklist.
377 * @param string $ip IP to check
378 * @param array $bases Array of Strings: URL of the DNS blacklist
379 * @return bool True if blacklisted.
381 private function inDnsBlacklist( $ip, array $bases ) {
383 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
384 if ( IP
::isIPv4( $ip ) ) {
385 // Reverse IP, T23255
386 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
388 foreach ( $bases as $base ) {
390 // If we have an access key, use that too (ProjectHoneypot, etc.)
392 if ( is_array( $base ) ) {
393 if ( count( $base ) >= 2 ) {
394 // Access key is 1, base URL is 0
395 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
397 $hostname = "$ipReversed.{$base[0]}";
399 $basename = $base[0];
401 $hostname = "$ipReversed.$base";
405 $ipList = $this->checkHost( $hostname );
409 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
415 $this->logger
->debug( "Requested $hostname, not found in $basename." );
423 * Wrapper for mocking in tests.
425 * @param string $hostname DNSBL query
426 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
428 protected function checkHost( $hostname ) {
429 return gethostbynamel( $hostname );
433 * Set the 'BlockID' cookie depending on block type and user authentication status.
438 public function trackBlockWithCookie( User
$user ) {
439 $request = $user->getRequest();
440 if ( $request->getCookie( 'BlockID' ) !== null ) {
441 // User already has a block cookie
445 // Defer checks until the user has been fully loaded to avoid circular dependency
446 // of User on itself (T180050 and T226777)
447 DeferredUpdates
::addCallableUpdate(
448 function () use ( $user, $request ) {
449 $block = $user->getBlock();
450 $response = $request->response();
451 $isAnon = $user->isAnon();
454 if ( $block instanceof CompositeBlock
) {
455 // TODO: Improve on simply tracking the first trackable block (T225654)
456 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
457 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
458 '@phan-var DatabaseBlock $originalBlock';
459 $this->setBlockCookie( $originalBlock, $response );
464 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
465 '@phan-var DatabaseBlock $block';
466 $this->setBlockCookie( $block, $response );
471 DeferredUpdates
::PRESEND
476 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
477 * the same as the block's, to a maximum of 24 hours.
480 * @internal Should be private.
481 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
482 * @param DatabaseBlock $block
483 * @param WebResponse $response The response on which to set the cookie.
485 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
486 // Calculate the default expiry time.
487 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
489 // Use the block's expiry time only if it's less than the default.
490 $expiryTime = $block->getExpiry();
491 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
492 $expiryTime = $maxExpiryTime;
495 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
496 $expiryValue = DateTime
::createFromFormat(
499 new DateTimeZone( 'UTC' )
501 $cookieOptions = [ 'httpOnly' => false ];
502 $cookieValue = $this->getCookieValue( $block );
503 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
507 * Check if the block should be tracked with a cookie.
509 * @param AbstractBlock $block
510 * @param bool $isAnon The user is logged out
511 * @return bool The block sould be tracked with a cookie
513 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
514 if ( $block instanceof DatabaseBlock
) {
515 switch ( $block->getType() ) {
516 case DatabaseBlock
::TYPE_IP
:
517 case DatabaseBlock
::TYPE_RANGE
:
518 return $isAnon && $this->options
->get( 'CookieSetOnIpBlock' );
519 case DatabaseBlock
::TYPE_USER
:
521 $this->options
->get( 'CookieSetOnAutoblock' ) &&
522 $block->isAutoblocking();
531 * Unset the 'BlockID' cookie.
534 * @param WebResponse $response
536 public static function clearBlockCookie( WebResponse
$response ) {
537 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
541 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
542 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
545 * @internal Should be private.
546 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
547 * @param string $cookieValue The string in which to find the ID.
548 * @return int|null The block ID, or null if the HMAC is present and invalid.
550 public function getIdFromCookieValue( $cookieValue ) {
551 // The cookie value must start with a number
552 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
556 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
557 $bangPos = strpos( $cookieValue, '!' );
558 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
559 if ( !$this->options
->get( 'SecretKey' ) ) {
560 // If there's no secret key, just use the ID as given.
563 $storedHmac = substr( $cookieValue, $bangPos +
1 );
564 $calculatedHmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
565 if ( $calculatedHmac === $storedHmac ) {
573 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
574 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
578 * @internal Should be private.
579 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
580 * @param DatabaseBlock $block
581 * @return string The block ID, probably concatenated with "!" and the HMAC.
583 public function getCookieValue( DatabaseBlock
$block ) {
584 $id = $block->getId();
585 if ( !$this->options
->get( 'SecretKey' ) ) {
586 // If there's no secret key, don't append a HMAC.
589 $hmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
590 $cookieValue = $id . '!' . $hmac;