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
;
27 use MediaWiki\Config\ServiceOptions
;
28 use MediaWiki\Permissions\PermissionManager
;
29 use MediaWiki\User\UserIdentity
;
37 * A service class for checking blocks.
38 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
40 * @since 1.34 Refactored from User and Block.
43 // TODO: This should be UserIdentity instead of User
47 /** @var WebRequest */
48 private $currentRequest;
50 /** @var PermissionManager */
51 private $permissionManager;
54 * TODO Make this a const when HHVM support is dropped (T192166)
59 public static $constructorOptions = [
61 'CookieSetOnAutoblock',
72 * @param ServiceOptions $options
73 * @param User $currentUser
74 * @param WebRequest $currentRequest
75 * @param PermissionManager $permissionManager
77 public function __construct(
78 ServiceOptions
$options,
80 WebRequest
$currentRequest,
81 PermissionManager
$permissionManager
83 $options->assertRequiredOptions( self
::$constructorOptions );
84 $this->options
= $options;
85 $this->currentUser
= $currentUser;
86 $this->currentRequest
= $currentRequest;
87 $this->permissionManager
= $permissionManager;
91 * Get the blocks that apply to a user. If there is only one, return that, otherwise
92 * return a composite block that combines the strictest features of the applicable
95 * TODO: $user should be UserIdentity instead of User
97 * @internal This should only be called by User::getBlockedStatus
99 * @param bool $fromReplica Whether to check the replica DB first.
100 * To improve performance, non-critical checks are done against replica DBs.
101 * Check when actually saving should be done against master.
102 * @return AbstractBlock|null The most relevant block, or null if there is no block.
104 public function getUserBlock( User
$user, $fromReplica ) {
105 $isAnon = $user->getId() === 0;
107 // TODO: If $user is the current user, we should use the current request. Otherwise,
108 // we should not look for XFF or cookie blocks.
109 $request = $user->getRequest();
111 # We only need to worry about passing the IP address to the block generator if the
112 # user is not immune to autoblocks/hardblocks, and they are the current user so we
113 # know which IP address they're actually coming from
115 $sessionUser = $this->currentUser
;
116 // the session user is set up towards the end of Setup.php. Until then,
117 // assume it's a logged-out user.
118 $globalUserName = $sessionUser->isSafeToLoad()
119 ?
$sessionUser->getName()
120 : IP
::sanitizeIP( $this->currentRequest
->getIP() );
121 if ( $user->getName() === $globalUserName &&
122 !$this->permissionManager
->userHasRight( $user, 'ipblock-exempt' ) ) {
123 $ip = $this->currentRequest
->getIP();
127 // After this, $blocks is an array of blocks or an empty array
128 // TODO: remove dependency on DatabaseBlock
129 $blocks = DatabaseBlock
::newListFromTarget( $user, $ip, !$fromReplica );
132 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
133 if ( $cookieBlock instanceof AbstractBlock
) {
134 $blocks[] = $cookieBlock;
138 if ( $ip !== null && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) ) {
140 if ( $this->isLocallyBlockedProxy( $ip ) ) {
141 $blocks[] = new SystemBlock( [
142 'byText' => wfMessage( 'proxyblocker' )->text(),
143 'reason' => wfMessage( 'proxyblockreason' )->plain(),
145 'systemBlock' => 'proxy',
147 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
148 $blocks[] = new SystemBlock( [
149 'byText' => wfMessage( 'sorbs' )->text(),
150 'reason' => wfMessage( 'sorbsreason' )->plain(),
152 'systemBlock' => 'dnsbl',
157 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
158 if ( $this->options
->get( 'ApplyIpBlocksToXff' )
160 && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) )
162 $xff = $request->getHeader( 'X-Forwarded-For' );
163 $xff = array_map( 'trim', explode( ',', $xff ) );
164 $xff = array_diff( $xff, [ $ip ] );
165 // TODO: remove dependency on DatabaseBlock
166 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, !$fromReplica );
167 $blocks = array_merge( $blocks, $xffblocks );
173 && IP
::isInRanges( $ip, $this->options
->get( 'SoftBlockRanges' ) )
175 $blocks[] = new SystemBlock( [
177 'byText' => 'MediaWiki default',
178 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
180 'systemBlock' => 'wgSoftBlockRanges',
184 // Filter out any duplicated blocks, e.g. from the cookie
185 $blocks = $this->getUniqueBlocks( $blocks );
187 if ( count( $blocks ) > 0 ) {
188 if ( count( $blocks ) === 1 ) {
189 $block = $blocks[ 0 ];
191 $block = new CompositeBlock( [
193 'byText' => 'MediaWiki default',
194 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
195 'originalBlocks' => $blocks,
205 * Given a list of blocks, return a list of unique blocks.
207 * This usually means that each block has a unique ID. For a block with ID null,
208 * if it's an autoblock, it will be filtered out if the parent block is present;
209 * if not, it is assumed to be a unique system block, and kept.
211 * @param AbstractBlock[] $blocks
212 * @return AbstractBlock[]
214 private function getUniqueBlocks( array $blocks ) {
216 $databaseBlocks = [];
218 foreach ( $blocks as $block ) {
219 if ( $block instanceof SystemBlock
) {
220 $systemBlocks[] = $block;
221 } elseif ( $block->getType() === DatabaseBlock
::TYPE_AUTO
) {
222 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
223 $databaseBlocks[$block->getParentBlockId()] = $block;
226 $databaseBlocks[$block->getId()] = $block;
230 return array_merge( $systemBlocks, $databaseBlocks );
234 * Try to load a block from an ID given in a cookie value. If the block is invalid
235 * doesn't exist, or the cookie value is malformed, remove the cookie.
237 * @param UserIdentity $user
238 * @param WebRequest $request
239 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
241 private function getBlockFromCookieValue(
245 $cookieValue = $request->getCookie( 'BlockID' );
246 if ( is_null( $cookieValue ) ) {
250 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
251 if ( !is_null( $blockCookieId ) ) {
252 // TODO: remove dependency on DatabaseBlock
253 $block = DatabaseBlock
::newFromID( $blockCookieId );
255 $block instanceof DatabaseBlock
&&
256 $this->shouldApplyCookieBlock( $block, $user->isAnon() )
262 $this->clearBlockCookie( $request->response() );
268 * Check if the block loaded from the cookie should be applied.
270 * @param DatabaseBlock $block
271 * @param bool $isAnon The user is logged out
272 * @return bool The block sould be applied
274 private function shouldApplyCookieBlock( DatabaseBlock
$block, $isAnon ) {
275 if ( !$block->isExpired() ) {
276 switch ( $block->getType() ) {
277 case DatabaseBlock
::TYPE_IP
:
278 case DatabaseBlock
::TYPE_RANGE
:
279 // If block is type IP or IP range, load only
280 // if user is not logged in (T152462)
282 $this->options
->get( 'CookieSetOnIpBlock' );
283 case DatabaseBlock
::TYPE_USER
:
284 return $block->isAutoblocking() &&
285 $this->options
->get( 'CookieSetOnAutoblock' );
294 * Check if an IP address is in the local proxy list
299 private function isLocallyBlockedProxy( $ip ) {
300 $proxyList = $this->options
->get( 'ProxyList' );
305 if ( !is_array( $proxyList ) ) {
306 // Load values from the specified file
307 $proxyList = array_map( 'trim', file( $proxyList ) );
310 $proxyListIPSet = new IPSet( $proxyList );
311 return $proxyListIPSet->match( $ip );
315 * Whether the given IP is in a DNS blacklist.
317 * @param string $ip IP to check
318 * @param bool $checkWhitelist Whether to check the whitelist first
319 * @return bool True if blacklisted.
321 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
322 if ( !$this->options
->get( 'EnableDnsBlacklist' ) ||
323 ( $checkWhitelist && in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) )
328 return $this->inDnsBlacklist( $ip, $this->options
->get( 'DnsBlacklistUrls' ) );
332 * Whether the given IP is in a given DNS blacklist.
334 * @param string $ip IP to check
335 * @param array $bases Array of Strings: URL of the DNS blacklist
336 * @return bool True if blacklisted.
338 private function inDnsBlacklist( $ip, array $bases ) {
340 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
341 if ( IP
::isIPv4( $ip ) ) {
342 // Reverse IP, T23255
343 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
345 foreach ( $bases as $base ) {
347 // If we have an access key, use that too (ProjectHoneypot, etc.)
349 if ( is_array( $base ) ) {
350 if ( count( $base ) >= 2 ) {
351 // Access key is 1, base URL is 0
352 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
354 $hostname = "$ipReversed.{$base[0]}";
356 $basename = $base[0];
358 $hostname = "$ipReversed.$base";
362 $ipList = $this->checkHost( $hostname );
367 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
373 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
381 * Wrapper for mocking in tests.
383 * @param string $hostname DNSBL query
384 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
386 protected function checkHost( $hostname ) {
387 return gethostbynamel( $hostname );
391 * Set the 'BlockID' cookie depending on block type and user authentication status.
396 public function trackBlockWithCookie( User
$user ) {
397 $request = $user->getRequest();
398 if ( $request->getCookie( 'BlockID' ) !== null ) {
399 // User already has a block cookie
403 // Defer checks until the user has been fully loaded to avoid circular dependency
404 // of User on itself (T180050 and T226777)
405 DeferredUpdates
::addCallableUpdate(
406 function () use ( $user, $request ) {
407 $block = $user->getBlock();
408 $response = $request->response();
409 $isAnon = $user->isAnon();
412 if ( $block instanceof CompositeBlock
) {
413 // TODO: Improve on simply tracking the first trackable block (T225654)
414 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
415 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
416 $this->setBlockCookie( $originalBlock, $response );
421 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
422 $this->setBlockCookie( $block, $response );
427 DeferredUpdates
::PRESEND
432 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
433 * the same as the block's, to a maximum of 24 hours.
436 * @internal Should be private.
437 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
438 * @param DatabaseBlock $block
439 * @param WebResponse $response The response on which to set the cookie.
441 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
442 // Calculate the default expiry time.
443 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
445 // Use the block's expiry time only if it's less than the default.
446 $expiryTime = $block->getExpiry();
447 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
448 $expiryTime = $maxExpiryTime;
451 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
452 $expiryValue = DateTime
::createFromFormat(
455 new DateTimeZone( 'UTC' )
457 $cookieOptions = [ 'httpOnly' => false ];
458 $cookieValue = $this->getCookieValue( $block );
459 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
463 * Check if the block should be tracked with a cookie.
465 * @param AbstractBlock $block
466 * @param bool $isAnon The user is logged out
467 * @return bool The block sould be tracked with a cookie
469 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
470 if ( $block instanceof DatabaseBlock
) {
471 switch ( $block->getType() ) {
472 case DatabaseBlock
::TYPE_IP
:
473 case DatabaseBlock
::TYPE_RANGE
:
474 return $isAnon && $this->options
->get( 'CookieSetOnIpBlock' );
475 case DatabaseBlock
::TYPE_USER
:
477 $this->options
->get( 'CookieSetOnAutoblock' ) &&
478 $block->isAutoblocking();
487 * Unset the 'BlockID' cookie.
490 * @param WebResponse $response
492 public static function clearBlockCookie( WebResponse
$response ) {
493 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
497 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
498 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
501 * @internal Should be private.
502 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
503 * @param string $cookieValue The string in which to find the ID.
504 * @return int|null The block ID, or null if the HMAC is present and invalid.
506 public function getIdFromCookieValue( $cookieValue ) {
507 // The cookie value must start with a number
508 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
512 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
513 $bangPos = strpos( $cookieValue, '!' );
514 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
515 if ( !$this->options
->get( 'SecretKey' ) ) {
516 // If there's no secret key, just use the ID as given.
519 $storedHmac = substr( $cookieValue, $bangPos +
1 );
520 $calculatedHmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
521 if ( $calculatedHmac === $storedHmac ) {
529 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
530 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
534 * @internal Should be private.
535 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
536 * @param DatabaseBlock $block
537 * @return string The block ID, probably concatenated with "!" and the HMAC.
539 public function getCookieValue( DatabaseBlock
$block ) {
540 $id = $block->getId();
541 if ( !$this->options
->get( 'SecretKey' ) ) {
542 // If there's no secret key, don't append a HMAC.
545 $hmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
546 $cookieValue = $id . '!' . $hmac;