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\User\UserIdentity
;
34 * A service class for checking blocks.
35 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
37 * @since 1.34 Refactored from User and Block.
40 // TODO: This should be UserIdentity instead of User
44 /** @var WebRequest */
45 private $currentRequest;
48 private $applyIpBlocksToXff;
51 private $cookieSetOnAutoblock;
54 private $cookieSetOnIpBlock;
57 private $dnsBlacklistUrls;
60 private $enableDnsBlacklist;
66 private $proxyWhitelist;
68 /** @var string|bool */
72 private $softBlockRanges;
75 * @param User $currentUser
76 * @param WebRequest $currentRequest
77 * @param bool $applyIpBlocksToXff
78 * @param bool $cookieSetOnAutoblock
79 * @param bool $cookieSetOnIpBlock
80 * @param string[] $dnsBlacklistUrls
81 * @param bool $enableDnsBlacklist
82 * @param string[] $proxyList
83 * @param string[] $proxyWhitelist
84 * @param string $secretKey
85 * @param array $softBlockRanges
87 public function __construct(
89 WebRequest
$currentRequest,
91 $cookieSetOnAutoblock,
93 array $dnsBlacklistUrls,
96 array $proxyWhitelist,
100 $this->currentUser
= $currentUser;
101 $this->currentRequest
= $currentRequest;
102 $this->applyIpBlocksToXff
= $applyIpBlocksToXff;
103 $this->cookieSetOnAutoblock
= $cookieSetOnAutoblock;
104 $this->cookieSetOnIpBlock
= $cookieSetOnIpBlock;
105 $this->dnsBlacklistUrls
= $dnsBlacklistUrls;
106 $this->enableDnsBlacklist
= $enableDnsBlacklist;
107 $this->proxyList
= $proxyList;
108 $this->proxyWhitelist
= $proxyWhitelist;
109 $this->secretKey
= $secretKey;
110 $this->softBlockRanges
= $softBlockRanges;
114 * Get the blocks that apply to a user. If there is only one, return that, otherwise
115 * return a composite block that combines the strictest features of the applicable
118 * TODO: $user should be UserIdentity instead of User
120 * @internal This should only be called by User::getBlockedStatus
122 * @param bool $fromReplica Whether to check the replica DB first.
123 * To improve performance, non-critical checks are done against replica DBs.
124 * Check when actually saving should be done against master.
125 * @return AbstractBlock|null The most relevant block, or null if there is no block.
127 public function getUserBlock( User
$user, $fromReplica ) {
128 $isAnon = $user->getId() === 0;
130 // TODO: If $user is the current user, we should use the current request. Otherwise,
131 // we should not look for XFF or cookie blocks.
132 $request = $user->getRequest();
134 # We only need to worry about passing the IP address to the block generator if the
135 # user is not immune to autoblocks/hardblocks, and they are the current user so we
136 # know which IP address they're actually coming from
138 $sessionUser = $this->currentUser
;
139 // the session user is set up towards the end of Setup.php. Until then,
140 // assume it's a logged-out user.
141 $globalUserName = $sessionUser->isSafeToLoad()
142 ?
$sessionUser->getName()
143 : IP
::sanitizeIP( $this->currentRequest
->getIP() );
144 if ( $user->getName() === $globalUserName && !$user->isAllowed( 'ipblock-exempt' ) ) {
145 $ip = $this->currentRequest
->getIP();
149 // After this, $blocks is an array of blocks or an empty array
150 // TODO: remove dependency on DatabaseBlock
151 $blocks = DatabaseBlock
::newListFromTarget( $user, $ip, !$fromReplica );
154 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
155 if ( $cookieBlock instanceof AbstractBlock
) {
156 $blocks[] = $cookieBlock;
160 if ( $ip !== null && !in_array( $ip, $this->proxyWhitelist
) ) {
162 if ( $this->isLocallyBlockedProxy( $ip ) ) {
163 $blocks[] = new SystemBlock( [
164 'byText' => wfMessage( 'proxyblocker' )->text(),
165 'reason' => wfMessage( 'proxyblockreason' )->plain(),
167 'systemBlock' => 'proxy',
169 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
170 $blocks[] = new SystemBlock( [
171 'byText' => wfMessage( 'sorbs' )->text(),
172 'reason' => wfMessage( 'sorbsreason' )->plain(),
174 'systemBlock' => 'dnsbl',
179 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
180 if ( $this->applyIpBlocksToXff
182 && !in_array( $ip, $this->proxyWhitelist
)
184 $xff = $request->getHeader( 'X-Forwarded-For' );
185 $xff = array_map( 'trim', explode( ',', $xff ) );
186 $xff = array_diff( $xff, [ $ip ] );
187 // TODO: remove dependency on DatabaseBlock
188 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, !$fromReplica );
189 $blocks = array_merge( $blocks, $xffblocks );
195 && IP
::isInRanges( $ip, $this->softBlockRanges
)
197 $blocks[] = new SystemBlock( [
199 'byText' => 'MediaWiki default',
200 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
202 'systemBlock' => 'wgSoftBlockRanges',
206 // Filter out any duplicated blocks, e.g. from the cookie
207 $blocks = $this->getUniqueBlocks( $blocks );
209 if ( count( $blocks ) > 0 ) {
210 if ( count( $blocks ) === 1 ) {
211 $block = $blocks[ 0 ];
213 $block = new CompositeBlock( [
215 'byText' => 'MediaWiki default',
216 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
217 'originalBlocks' => $blocks,
227 * Given a list of blocks, return a list of unique blocks.
229 * This usually means that each block has a unique ID. For a block with ID null,
230 * if it's an autoblock, it will be filtered out if the parent block is present;
231 * if not, it is assumed to be a unique system block, and kept.
233 * @param AbstractBlock[] $blocks
234 * @return AbstractBlock[]
236 private function getUniqueBlocks( array $blocks ) {
238 $databaseBlocks = [];
240 foreach ( $blocks as $block ) {
241 if ( $block instanceof SystemBlock
) {
242 $systemBlocks[] = $block;
243 } elseif ( $block->getType() === DatabaseBlock
::TYPE_AUTO
) {
244 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
245 $databaseBlocks[$block->getParentBlockId()] = $block;
248 $databaseBlocks[$block->getId()] = $block;
252 return array_merge( $systemBlocks, $databaseBlocks );
256 * Try to load a block from an ID given in a cookie value.
258 * @param UserIdentity $user
259 * @param WebRequest $request
260 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
262 private function getBlockFromCookieValue(
266 $blockCookieVal = $request->getCookie( 'BlockID' );
267 $response = $request->response();
269 // Make sure there's something to check. The cookie value must start with a number.
270 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
273 // Load the block from the ID in the cookie.
274 $blockCookieId = $this->getIdFromCookieValue( $blockCookieVal );
275 if ( $blockCookieId !== null ) {
276 // An ID was found in the cookie.
277 // TODO: remove dependency on DatabaseBlock
278 $tmpBlock = DatabaseBlock
::newFromID( $blockCookieId );
279 if ( $tmpBlock instanceof DatabaseBlock
) {
280 switch ( $tmpBlock->getType() ) {
281 case DatabaseBlock
::TYPE_USER
:
282 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
283 $useBlockCookie = ( $this->cookieSetOnAutoblock
=== true );
285 case DatabaseBlock
::TYPE_IP
:
286 case DatabaseBlock
::TYPE_RANGE
:
287 // If block is type IP or IP range, load only if user is not logged in (T152462)
288 $blockIsValid = !$tmpBlock->isExpired() && $user->getId() === 0;
289 $useBlockCookie = ( $this->cookieSetOnIpBlock
=== true );
292 $blockIsValid = false;
293 $useBlockCookie = false;
296 if ( $blockIsValid && $useBlockCookie ) {
301 // If the block is invalid or doesn't exist, remove the cookie.
302 $this->clearBlockCookie( $response );
308 * Check if an IP address is in the local proxy list
313 private function isLocallyBlockedProxy( $ip ) {
314 if ( !$this->proxyList
) {
318 if ( !is_array( $this->proxyList
) ) {
319 // Load values from the specified file
320 $this->proxyList
= array_map( 'trim', file( $this->proxyList
) );
323 $resultProxyList = [];
324 $deprecatedIPEntries = [];
326 // backward compatibility: move all ip addresses in keys to values
327 foreach ( $this->proxyList
as $key => $value ) {
328 $keyIsIP = IP
::isIPAddress( $key );
329 $valueIsIP = IP
::isIPAddress( $value );
330 if ( $keyIsIP && !$valueIsIP ) {
331 $deprecatedIPEntries[] = $key;
332 $resultProxyList[] = $key;
333 } elseif ( $keyIsIP && $valueIsIP ) {
334 $deprecatedIPEntries[] = $key;
335 $resultProxyList[] = $key;
336 $resultProxyList[] = $value;
338 $resultProxyList[] = $value;
342 if ( $deprecatedIPEntries ) {
344 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
345 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
348 $proxyListIPSet = new IPSet( $resultProxyList );
349 return $proxyListIPSet->match( $ip );
353 * Whether the given IP is in a DNS blacklist.
355 * @param string $ip IP to check
356 * @param bool $checkWhitelist Whether to check the whitelist first
357 * @return bool True if blacklisted.
359 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
360 if ( !$this->enableDnsBlacklist ||
361 ( $checkWhitelist && in_array( $ip, $this->proxyWhitelist
) )
366 return $this->inDnsBlacklist( $ip, $this->dnsBlacklistUrls
);
370 * Whether the given IP is in a given DNS blacklist.
372 * @param string $ip IP to check
373 * @param array $bases Array of Strings: URL of the DNS blacklist
374 * @return bool True if blacklisted.
376 private function inDnsBlacklist( $ip, array $bases ) {
378 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
379 if ( IP
::isIPv4( $ip ) ) {
380 // Reverse IP, T23255
381 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
383 foreach ( $bases as $base ) {
385 // If we have an access key, use that too (ProjectHoneypot, etc.)
387 if ( is_array( $base ) ) {
388 if ( count( $base ) >= 2 ) {
389 // Access key is 1, base URL is 0
390 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
392 $hostname = "$ipReversed.{$base[0]}";
394 $basename = $base[0];
396 $hostname = "$ipReversed.$base";
400 $ipList = $this->checkHost( $hostname );
405 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
411 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
419 * Wrapper for mocking in tests.
421 * @param string $hostname DNSBL query
422 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
424 protected function checkHost( $hostname ) {
425 return gethostbynamel( $hostname );
429 * Set the 'BlockID' cookie depending on block type and user authentication status.
434 public function trackBlockWithCookie( User
$user ) {
435 $request = $user->getRequest();
436 if ( $request->getCookie( 'BlockID' ) !== null ) {
437 // User already has a block cookie
441 // Defer checks until the user has been fully loaded to avoid circular dependency
442 // of User on itself (T180050 and T226777)
443 DeferredUpdates
::addCallableUpdate(
444 function () use ( $user, $request ) {
445 $block = $user->getBlock();
446 $response = $request->response();
447 $isAnon = $user->isAnon();
450 if ( $block instanceof CompositeBlock
) {
451 // TODO: Improve on simply tracking the first trackable block (T225654)
452 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
453 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
454 $this->setBlockCookie( $originalBlock, $response );
459 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
460 $this->setBlockCookie( $block, $response );
465 DeferredUpdates
::PRESEND
470 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
471 * the same as the block's, to a maximum of 24 hours.
474 * @internal Should be private.
475 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
476 * @param DatabaseBlock $block
477 * @param WebResponse $response The response on which to set the cookie.
479 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
480 // Calculate the default expiry time.
481 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
483 // Use the block's expiry time only if it's less than the default.
484 $expiryTime = $block->getExpiry();
485 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
486 $expiryTime = $maxExpiryTime;
489 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
490 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
491 $cookieOptions = [ 'httpOnly' => false ];
492 $cookieValue = $this->getCookieValue( $block );
493 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
497 * Check if the block should be tracked with a cookie.
499 * @param AbstractBlock $block
500 * @param bool $isAnon The user is logged out
501 * @return bool The block sould be tracked with a cookie
503 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
504 if ( $block instanceof DatabaseBlock
) {
505 switch ( $block->getType() ) {
506 case DatabaseBlock
::TYPE_IP
:
507 case DatabaseBlock
::TYPE_RANGE
:
508 return $isAnon && $this->cookieSetOnIpBlock
;
509 case DatabaseBlock
::TYPE_USER
:
510 return !$isAnon && $this->cookieSetOnAutoblock
&& $block->isAutoblocking();
519 * Unset the 'BlockID' cookie.
522 * @param WebResponse $response
524 public static function clearBlockCookie( WebResponse
$response ) {
525 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
529 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
530 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
533 * @internal Should be private.
534 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
535 * @param string $cookieValue The string in which to find the ID.
536 * @return int|null The block ID, or null if the HMAC is present and invalid.
538 public function getIdFromCookieValue( $cookieValue ) {
539 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
540 $bangPos = strpos( $cookieValue, '!' );
541 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
542 if ( !$this->secretKey
) {
543 // If there's no secret key, just use the ID as given.
546 $storedHmac = substr( $cookieValue, $bangPos +
1 );
547 $calculatedHmac = MWCryptHash
::hmac( $id, $this->secretKey
, false );
548 if ( $calculatedHmac === $storedHmac ) {
556 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
557 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
561 * @internal Should be private.
562 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
563 * @param DatabaseBlock $block
564 * @return string The block ID, probably concatenated with "!" and the HMAC.
566 public function getCookieValue( DatabaseBlock
$block ) {
567 $id = $block->getId();
568 if ( !$this->secretKey
) {
569 // If there's no secret key, don't append a HMAC.
572 $hmac = MWCryptHash
::hmac( $id, $this->secretKey
, false );
573 $cookieValue = $id . '!' . $hmac;