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
;
26 use MediaWiki\Config\ServiceOptions
;
27 use MediaWiki\User\UserIdentity
;
35 * A service class for checking blocks.
36 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
38 * @since 1.34 Refactored from User and Block.
41 // TODO: This should be UserIdentity instead of User
45 /** @var WebRequest */
46 private $currentRequest;
49 * TODO Make this a const when HHVM support is dropped (T192166)
54 public static $constructorOptions = [
56 'CookieSetOnAutoblock',
67 * @param ServiceOptions $options
68 * @param User $currentUser
69 * @param WebRequest $currentRequest
71 public function __construct(
72 ServiceOptions
$options,
74 WebRequest
$currentRequest
76 $options->assertRequiredOptions( self
::$constructorOptions );
77 $this->options
= $options;
78 $this->currentUser
= $currentUser;
79 $this->currentRequest
= $currentRequest;
83 * Get the blocks that apply to a user. If there is only one, return that, otherwise
84 * return a composite block that combines the strictest features of the applicable
87 * TODO: $user should be UserIdentity instead of User
89 * @internal This should only be called by User::getBlockedStatus
91 * @param bool $fromReplica Whether to check the replica DB first.
92 * To improve performance, non-critical checks are done against replica DBs.
93 * Check when actually saving should be done against master.
94 * @return AbstractBlock|null The most relevant block, or null if there is no block.
96 public function getUserBlock( User
$user, $fromReplica ) {
97 $isAnon = $user->getId() === 0;
99 // TODO: If $user is the current user, we should use the current request. Otherwise,
100 // we should not look for XFF or cookie blocks.
101 $request = $user->getRequest();
103 # We only need to worry about passing the IP address to the block generator if the
104 # user is not immune to autoblocks/hardblocks, and they are the current user so we
105 # know which IP address they're actually coming from
107 $sessionUser = $this->currentUser
;
108 // the session user is set up towards the end of Setup.php. Until then,
109 // assume it's a logged-out user.
110 $globalUserName = $sessionUser->isSafeToLoad()
111 ?
$sessionUser->getName()
112 : IP
::sanitizeIP( $this->currentRequest
->getIP() );
113 if ( $user->getName() === $globalUserName && !$user->isAllowed( 'ipblock-exempt' ) ) {
114 $ip = $this->currentRequest
->getIP();
118 // After this, $blocks is an array of blocks or an empty array
119 // TODO: remove dependency on DatabaseBlock
120 $blocks = DatabaseBlock
::newListFromTarget( $user, $ip, !$fromReplica );
123 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
124 if ( $cookieBlock instanceof AbstractBlock
) {
125 $blocks[] = $cookieBlock;
129 if ( $ip !== null && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) ) {
131 if ( $this->isLocallyBlockedProxy( $ip ) ) {
132 $blocks[] = new SystemBlock( [
133 'byText' => wfMessage( 'proxyblocker' )->text(),
134 'reason' => wfMessage( 'proxyblockreason' )->plain(),
136 'systemBlock' => 'proxy',
138 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
139 $blocks[] = new SystemBlock( [
140 'byText' => wfMessage( 'sorbs' )->text(),
141 'reason' => wfMessage( 'sorbsreason' )->plain(),
143 'systemBlock' => 'dnsbl',
148 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
149 if ( $this->options
->get( 'ApplyIpBlocksToXff' )
151 && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) )
153 $xff = $request->getHeader( 'X-Forwarded-For' );
154 $xff = array_map( 'trim', explode( ',', $xff ) );
155 $xff = array_diff( $xff, [ $ip ] );
156 // TODO: remove dependency on DatabaseBlock
157 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, !$fromReplica );
158 $blocks = array_merge( $blocks, $xffblocks );
164 && IP
::isInRanges( $ip, $this->options
->get( 'SoftBlockRanges' ) )
166 $blocks[] = new SystemBlock( [
168 'byText' => 'MediaWiki default',
169 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
171 'systemBlock' => 'wgSoftBlockRanges',
175 // Filter out any duplicated blocks, e.g. from the cookie
176 $blocks = $this->getUniqueBlocks( $blocks );
178 if ( count( $blocks ) > 0 ) {
179 if ( count( $blocks ) === 1 ) {
180 $block = $blocks[ 0 ];
182 $block = new CompositeBlock( [
184 'byText' => 'MediaWiki default',
185 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
186 'originalBlocks' => $blocks,
196 * Given a list of blocks, return a list of unique blocks.
198 * This usually means that each block has a unique ID. For a block with ID null,
199 * if it's an autoblock, it will be filtered out if the parent block is present;
200 * if not, it is assumed to be a unique system block, and kept.
202 * @param AbstractBlock[] $blocks
203 * @return AbstractBlock[]
205 private function getUniqueBlocks( array $blocks ) {
207 $databaseBlocks = [];
209 foreach ( $blocks as $block ) {
210 if ( $block instanceof SystemBlock
) {
211 $systemBlocks[] = $block;
212 } elseif ( $block->getType() === DatabaseBlock
::TYPE_AUTO
) {
213 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
214 $databaseBlocks[$block->getParentBlockId()] = $block;
217 $databaseBlocks[$block->getId()] = $block;
221 return array_merge( $systemBlocks, $databaseBlocks );
225 * Try to load a block from an ID given in a cookie value. If the block is invalid
226 * or doesn't exist, remove the cookie.
228 * @param UserIdentity $user
229 * @param WebRequest $request
230 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
232 private function getBlockFromCookieValue(
236 $blockCookieId = $this->getIdFromCookieValue( $request->getCookie( 'BlockID' ) );
238 if ( $blockCookieId !== null ) {
239 // TODO: remove dependency on DatabaseBlock
240 $block = DatabaseBlock
::newFromID( $blockCookieId );
242 $block instanceof DatabaseBlock
&&
243 $this->shouldApplyCookieBlock( $block, $user->isAnon() )
247 $this->clearBlockCookie( $request->response() );
254 * Check if the block loaded from the cookie should be applied.
256 * @param DatabaseBlock $block
257 * @param bool $isAnon The user is logged out
258 * @return bool The block sould be applied
260 private function shouldApplyCookieBlock( DatabaseBlock
$block, $isAnon ) {
261 if ( !$block->isExpired() ) {
262 switch ( $block->getType() ) {
263 case DatabaseBlock
::TYPE_IP
:
264 case DatabaseBlock
::TYPE_RANGE
:
265 // If block is type IP or IP range, load only
266 // if user is not logged in (T152462)
268 $this->options
->get( 'CookieSetOnIpBlock' );
269 case DatabaseBlock
::TYPE_USER
:
270 return $block->isAutoblocking() &&
271 $this->options
->get( 'CookieSetOnAutoblock' );
280 * Check if an IP address is in the local proxy list
285 private function isLocallyBlockedProxy( $ip ) {
286 $proxyList = $this->options
->get( 'ProxyList' );
291 if ( !is_array( $proxyList ) ) {
292 // Load values from the specified file
293 $proxyList = array_map( 'trim', file( $proxyList ) );
296 $proxyListIPSet = new IPSet( $proxyList );
297 return $proxyListIPSet->match( $ip );
301 * Whether the given IP is in a DNS blacklist.
303 * @param string $ip IP to check
304 * @param bool $checkWhitelist Whether to check the whitelist first
305 * @return bool True if blacklisted.
307 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
308 if ( !$this->options
->get( 'EnableDnsBlacklist' ) ||
309 ( $checkWhitelist && in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) )
314 return $this->inDnsBlacklist( $ip, $this->options
->get( 'DnsBlacklistUrls' ) );
318 * Whether the given IP is in a given DNS blacklist.
320 * @param string $ip IP to check
321 * @param array $bases Array of Strings: URL of the DNS blacklist
322 * @return bool True if blacklisted.
324 private function inDnsBlacklist( $ip, array $bases ) {
326 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
327 if ( IP
::isIPv4( $ip ) ) {
328 // Reverse IP, T23255
329 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
331 foreach ( $bases as $base ) {
333 // If we have an access key, use that too (ProjectHoneypot, etc.)
335 if ( is_array( $base ) ) {
336 if ( count( $base ) >= 2 ) {
337 // Access key is 1, base URL is 0
338 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
340 $hostname = "$ipReversed.{$base[0]}";
342 $basename = $base[0];
344 $hostname = "$ipReversed.$base";
348 $ipList = $this->checkHost( $hostname );
353 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
359 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
367 * Wrapper for mocking in tests.
369 * @param string $hostname DNSBL query
370 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
372 protected function checkHost( $hostname ) {
373 return gethostbynamel( $hostname );
377 * Set the 'BlockID' cookie depending on block type and user authentication status.
382 public function trackBlockWithCookie( User
$user ) {
383 $request = $user->getRequest();
384 if ( $request->getCookie( 'BlockID' ) !== null ) {
385 // User already has a block cookie
389 // Defer checks until the user has been fully loaded to avoid circular dependency
390 // of User on itself (T180050 and T226777)
391 DeferredUpdates
::addCallableUpdate(
392 function () use ( $user, $request ) {
393 $block = $user->getBlock();
394 $response = $request->response();
395 $isAnon = $user->isAnon();
398 if ( $block instanceof CompositeBlock
) {
399 // TODO: Improve on simply tracking the first trackable block (T225654)
400 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
401 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
402 $this->setBlockCookie( $originalBlock, $response );
407 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
408 $this->setBlockCookie( $block, $response );
413 DeferredUpdates
::PRESEND
418 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
419 * the same as the block's, to a maximum of 24 hours.
422 * @internal Should be private.
423 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
424 * @param DatabaseBlock $block
425 * @param WebResponse $response The response on which to set the cookie.
427 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
428 // Calculate the default expiry time.
429 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
431 // Use the block's expiry time only if it's less than the default.
432 $expiryTime = $block->getExpiry();
433 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
434 $expiryTime = $maxExpiryTime;
437 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
438 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
439 $cookieOptions = [ 'httpOnly' => false ];
440 $cookieValue = $this->getCookieValue( $block );
441 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
445 * Check if the block should be tracked with a cookie.
447 * @param AbstractBlock $block
448 * @param bool $isAnon The user is logged out
449 * @return bool The block sould be tracked with a cookie
451 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
452 if ( $block instanceof DatabaseBlock
) {
453 switch ( $block->getType() ) {
454 case DatabaseBlock
::TYPE_IP
:
455 case DatabaseBlock
::TYPE_RANGE
:
456 return $isAnon && $this->options
->get( 'CookieSetOnIpBlock' );
457 case DatabaseBlock
::TYPE_USER
:
459 $this->options
->get( 'CookieSetOnAutoblock' ) &&
460 $block->isAutoblocking();
469 * Unset the 'BlockID' cookie.
472 * @param WebResponse $response
474 public static function clearBlockCookie( WebResponse
$response ) {
475 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
479 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
480 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
483 * @internal Should be private.
484 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
485 * @param string $cookieValue The string in which to find the ID.
486 * @return int|null The block ID, or null if the HMAC is present and invalid.
488 public function getIdFromCookieValue( $cookieValue ) {
489 // The cookie value must start with a number
490 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
494 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
495 $bangPos = strpos( $cookieValue, '!' );
496 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
497 if ( !$this->options
->get( 'SecretKey' ) ) {
498 // If there's no secret key, just use the ID as given.
501 $storedHmac = substr( $cookieValue, $bangPos +
1 );
502 $calculatedHmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
503 if ( $calculatedHmac === $storedHmac ) {
511 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
512 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
516 * @internal Should be private.
517 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
518 * @param DatabaseBlock $block
519 * @return string The block ID, probably concatenated with "!" and the HMAC.
521 public function getCookieValue( DatabaseBlock
$block ) {
522 $id = $block->getId();
523 if ( !$this->options
->get( 'SecretKey' ) ) {
524 // If there's no secret key, don't append a HMAC.
527 $hmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
528 $cookieValue = $id . '!' . $hmac;