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\User\UserIdentity
;
36 * A service class for checking blocks.
37 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
39 * @since 1.34 Refactored from User and Block.
42 // TODO: This should be UserIdentity instead of User
46 /** @var WebRequest */
47 private $currentRequest;
50 * TODO Make this a const when HHVM support is dropped (T192166)
55 public static $constructorOptions = [
57 'CookieSetOnAutoblock',
68 * @param ServiceOptions $options
69 * @param User $currentUser
70 * @param WebRequest $currentRequest
72 public function __construct(
73 ServiceOptions
$options,
75 WebRequest
$currentRequest
77 $options->assertRequiredOptions( self
::$constructorOptions );
78 $this->options
= $options;
79 $this->currentUser
= $currentUser;
80 $this->currentRequest
= $currentRequest;
84 * Get the blocks that apply to a user. If there is only one, return that, otherwise
85 * return a composite block that combines the strictest features of the applicable
88 * TODO: $user should be UserIdentity instead of User
90 * @internal This should only be called by User::getBlockedStatus
92 * @param bool $fromReplica Whether to check the replica DB first.
93 * To improve performance, non-critical checks are done against replica DBs.
94 * Check when actually saving should be done against master.
95 * @return AbstractBlock|null The most relevant block, or null if there is no block.
97 public function getUserBlock( User
$user, $fromReplica ) {
98 $isAnon = $user->getId() === 0;
100 // TODO: If $user is the current user, we should use the current request. Otherwise,
101 // we should not look for XFF or cookie blocks.
102 $request = $user->getRequest();
104 # We only need to worry about passing the IP address to the block generator if the
105 # user is not immune to autoblocks/hardblocks, and they are the current user so we
106 # know which IP address they're actually coming from
108 $sessionUser = $this->currentUser
;
109 // the session user is set up towards the end of Setup.php. Until then,
110 // assume it's a logged-out user.
111 $globalUserName = $sessionUser->isSafeToLoad()
112 ?
$sessionUser->getName()
113 : IP
::sanitizeIP( $this->currentRequest
->getIP() );
114 if ( $user->getName() === $globalUserName && !$user->isAllowed( 'ipblock-exempt' ) ) {
115 $ip = $this->currentRequest
->getIP();
119 // After this, $blocks is an array of blocks or an empty array
120 // TODO: remove dependency on DatabaseBlock
121 $blocks = DatabaseBlock
::newListFromTarget( $user, $ip, !$fromReplica );
124 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
125 if ( $cookieBlock instanceof AbstractBlock
) {
126 $blocks[] = $cookieBlock;
130 if ( $ip !== null && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) ) {
132 if ( $this->isLocallyBlockedProxy( $ip ) ) {
133 $blocks[] = new SystemBlock( [
134 'byText' => wfMessage( 'proxyblocker' )->text(),
135 'reason' => wfMessage( 'proxyblockreason' )->plain(),
137 'systemBlock' => 'proxy',
139 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
140 $blocks[] = new SystemBlock( [
141 'byText' => wfMessage( 'sorbs' )->text(),
142 'reason' => wfMessage( 'sorbsreason' )->plain(),
144 'systemBlock' => 'dnsbl',
149 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
150 if ( $this->options
->get( 'ApplyIpBlocksToXff' )
152 && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) )
154 $xff = $request->getHeader( 'X-Forwarded-For' );
155 $xff = array_map( 'trim', explode( ',', $xff ) );
156 $xff = array_diff( $xff, [ $ip ] );
157 // TODO: remove dependency on DatabaseBlock
158 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, !$fromReplica );
159 $blocks = array_merge( $blocks, $xffblocks );
165 && IP
::isInRanges( $ip, $this->options
->get( 'SoftBlockRanges' ) )
167 $blocks[] = new SystemBlock( [
169 'byText' => 'MediaWiki default',
170 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
172 'systemBlock' => 'wgSoftBlockRanges',
176 // Filter out any duplicated blocks, e.g. from the cookie
177 $blocks = $this->getUniqueBlocks( $blocks );
179 if ( count( $blocks ) > 0 ) {
180 if ( count( $blocks ) === 1 ) {
181 $block = $blocks[ 0 ];
183 $block = new CompositeBlock( [
185 'byText' => 'MediaWiki default',
186 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
187 'originalBlocks' => $blocks,
197 * Given a list of blocks, return a list of unique blocks.
199 * This usually means that each block has a unique ID. For a block with ID null,
200 * if it's an autoblock, it will be filtered out if the parent block is present;
201 * if not, it is assumed to be a unique system block, and kept.
203 * @param AbstractBlock[] $blocks
204 * @return AbstractBlock[]
206 private function getUniqueBlocks( array $blocks ) {
208 $databaseBlocks = [];
210 foreach ( $blocks as $block ) {
211 if ( $block instanceof SystemBlock
) {
212 $systemBlocks[] = $block;
213 } elseif ( $block->getType() === DatabaseBlock
::TYPE_AUTO
) {
214 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
215 $databaseBlocks[$block->getParentBlockId()] = $block;
218 $databaseBlocks[$block->getId()] = $block;
222 return array_merge( $systemBlocks, $databaseBlocks );
226 * Try to load a block from an ID given in a cookie value. If the block is invalid
227 * doesn't exist, or the cookie value is malformed, remove the cookie.
229 * @param UserIdentity $user
230 * @param WebRequest $request
231 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
233 private function getBlockFromCookieValue(
237 $cookieValue = $request->getCookie( 'BlockID' );
238 if ( is_null( $cookieValue ) ) {
242 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
243 if ( !is_null( $blockCookieId ) ) {
244 // TODO: remove dependency on DatabaseBlock
245 $block = DatabaseBlock
::newFromID( $blockCookieId );
247 $block instanceof DatabaseBlock
&&
248 $this->shouldApplyCookieBlock( $block, $user->isAnon() )
254 $this->clearBlockCookie( $request->response() );
260 * Check if the block loaded from the cookie should be applied.
262 * @param DatabaseBlock $block
263 * @param bool $isAnon The user is logged out
264 * @return bool The block sould be applied
266 private function shouldApplyCookieBlock( DatabaseBlock
$block, $isAnon ) {
267 if ( !$block->isExpired() ) {
268 switch ( $block->getType() ) {
269 case DatabaseBlock
::TYPE_IP
:
270 case DatabaseBlock
::TYPE_RANGE
:
271 // If block is type IP or IP range, load only
272 // if user is not logged in (T152462)
274 $this->options
->get( 'CookieSetOnIpBlock' );
275 case DatabaseBlock
::TYPE_USER
:
276 return $block->isAutoblocking() &&
277 $this->options
->get( 'CookieSetOnAutoblock' );
286 * Check if an IP address is in the local proxy list
291 private function isLocallyBlockedProxy( $ip ) {
292 $proxyList = $this->options
->get( 'ProxyList' );
297 if ( !is_array( $proxyList ) ) {
298 // Load values from the specified file
299 $proxyList = array_map( 'trim', file( $proxyList ) );
302 $proxyListIPSet = new IPSet( $proxyList );
303 return $proxyListIPSet->match( $ip );
307 * Whether the given IP is in a DNS blacklist.
309 * @param string $ip IP to check
310 * @param bool $checkWhitelist Whether to check the whitelist first
311 * @return bool True if blacklisted.
313 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
314 if ( !$this->options
->get( 'EnableDnsBlacklist' ) ||
315 ( $checkWhitelist && in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) )
320 return $this->inDnsBlacklist( $ip, $this->options
->get( 'DnsBlacklistUrls' ) );
324 * Whether the given IP is in a given DNS blacklist.
326 * @param string $ip IP to check
327 * @param array $bases Array of Strings: URL of the DNS blacklist
328 * @return bool True if blacklisted.
330 private function inDnsBlacklist( $ip, array $bases ) {
332 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
333 if ( IP
::isIPv4( $ip ) ) {
334 // Reverse IP, T23255
335 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
337 foreach ( $bases as $base ) {
339 // If we have an access key, use that too (ProjectHoneypot, etc.)
341 if ( is_array( $base ) ) {
342 if ( count( $base ) >= 2 ) {
343 // Access key is 1, base URL is 0
344 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
346 $hostname = "$ipReversed.{$base[0]}";
348 $basename = $base[0];
350 $hostname = "$ipReversed.$base";
354 $ipList = $this->checkHost( $hostname );
359 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
365 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
373 * Wrapper for mocking in tests.
375 * @param string $hostname DNSBL query
376 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
378 protected function checkHost( $hostname ) {
379 return gethostbynamel( $hostname );
383 * Set the 'BlockID' cookie depending on block type and user authentication status.
388 public function trackBlockWithCookie( User
$user ) {
389 $request = $user->getRequest();
390 if ( $request->getCookie( 'BlockID' ) !== null ) {
391 // User already has a block cookie
395 // Defer checks until the user has been fully loaded to avoid circular dependency
396 // of User on itself (T180050 and T226777)
397 DeferredUpdates
::addCallableUpdate(
398 function () use ( $user, $request ) {
399 $block = $user->getBlock();
400 $response = $request->response();
401 $isAnon = $user->isAnon();
404 if ( $block instanceof CompositeBlock
) {
405 // TODO: Improve on simply tracking the first trackable block (T225654)
406 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
407 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
408 $this->setBlockCookie( $originalBlock, $response );
413 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
414 $this->setBlockCookie( $block, $response );
419 DeferredUpdates
::PRESEND
424 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
425 * the same as the block's, to a maximum of 24 hours.
428 * @internal Should be private.
429 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
430 * @param DatabaseBlock $block
431 * @param WebResponse $response The response on which to set the cookie.
433 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
434 // Calculate the default expiry time.
435 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
437 // Use the block's expiry time only if it's less than the default.
438 $expiryTime = $block->getExpiry();
439 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
440 $expiryTime = $maxExpiryTime;
443 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
444 $expiryValue = DateTime
::createFromFormat(
447 new DateTimeZone( 'UTC' )
449 $cookieOptions = [ 'httpOnly' => false ];
450 $cookieValue = $this->getCookieValue( $block );
451 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
455 * Check if the block should be tracked with a cookie.
457 * @param AbstractBlock $block
458 * @param bool $isAnon The user is logged out
459 * @return bool The block sould be tracked with a cookie
461 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
462 if ( $block instanceof DatabaseBlock
) {
463 switch ( $block->getType() ) {
464 case DatabaseBlock
::TYPE_IP
:
465 case DatabaseBlock
::TYPE_RANGE
:
466 return $isAnon && $this->options
->get( 'CookieSetOnIpBlock' );
467 case DatabaseBlock
::TYPE_USER
:
469 $this->options
->get( 'CookieSetOnAutoblock' ) &&
470 $block->isAutoblocking();
479 * Unset the 'BlockID' cookie.
482 * @param WebResponse $response
484 public static function clearBlockCookie( WebResponse
$response ) {
485 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
489 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
490 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
493 * @internal Should be private.
494 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
495 * @param string $cookieValue The string in which to find the ID.
496 * @return int|null The block ID, or null if the HMAC is present and invalid.
498 public function getIdFromCookieValue( $cookieValue ) {
499 // The cookie value must start with a number
500 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
504 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
505 $bangPos = strpos( $cookieValue, '!' );
506 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
507 if ( !$this->options
->get( 'SecretKey' ) ) {
508 // If there's no secret key, just use the ID as given.
511 $storedHmac = substr( $cookieValue, $bangPos +
1 );
512 $calculatedHmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
513 if ( $calculatedHmac === $storedHmac ) {
521 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
522 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
526 * @internal Should be private.
527 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
528 * @param DatabaseBlock $block
529 * @return string The block ID, probably concatenated with "!" and the HMAC.
531 public function getCookieValue( DatabaseBlock
$block ) {
532 $id = $block->getId();
533 if ( !$this->options
->get( 'SecretKey' ) ) {
534 // If there's no secret key, don't append a HMAC.
537 $hmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
538 $cookieValue = $id . '!' . $hmac;