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
;
38 * A service class for checking blocks.
39 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
41 * @since 1.34 Refactored from User and Block.
44 // TODO: This should be UserIdentity instead of User
48 /** @var WebRequest */
49 private $currentRequest;
51 /** @var PermissionManager */
52 private $permissionManager;
55 * TODO Make this a const when HHVM support is dropped (T192166)
60 public static $constructorOptions = [
62 'CookieSetOnAutoblock',
73 * @param ServiceOptions $options
74 * @param User $currentUser
75 * @param WebRequest $currentRequest
76 * @param PermissionManager $permissionManager
78 public function __construct(
79 ServiceOptions
$options,
81 WebRequest
$currentRequest,
82 PermissionManager
$permissionManager
84 $options->assertRequiredOptions( self
::$constructorOptions );
85 $this->options
= $options;
86 $this->currentUser
= $currentUser;
87 $this->currentRequest
= $currentRequest;
88 $this->permissionManager
= $permissionManager;
92 * Get the blocks that apply to a user. If there is only one, return that, otherwise
93 * return a composite block that combines the strictest features of the applicable
96 * TODO: $user should be UserIdentity instead of User
98 * @internal This should only be called by User::getBlockedStatus
100 * @param bool $fromReplica Whether to check the replica DB first.
101 * To improve performance, non-critical checks are done against replica DBs.
102 * Check when actually saving should be done against master.
103 * @return AbstractBlock|null The most relevant block, or null if there is no block.
105 public function getUserBlock( User
$user, $fromReplica ) {
106 $isAnon = $user->getId() === 0;
108 // TODO: If $user is the current user, we should use the current request. Otherwise,
109 // we should not look for XFF or cookie blocks.
110 $request = $user->getRequest();
112 # We only need to worry about passing the IP address to the block generator if the
113 # user is not immune to autoblocks/hardblocks, and they are the current user so we
114 # know which IP address they're actually coming from
116 $sessionUser = $this->currentUser
;
117 // the session user is set up towards the end of Setup.php. Until then,
118 // assume it's a logged-out user.
119 $globalUserName = $sessionUser->isSafeToLoad()
120 ?
$sessionUser->getName()
121 : IP
::sanitizeIP( $this->currentRequest
->getIP() );
122 if ( $user->getName() === $globalUserName &&
123 !$this->permissionManager
->userHasRight( $user, 'ipblock-exempt' ) ) {
124 $ip = $this->currentRequest
->getIP();
128 // After this, $blocks is an array of blocks or an empty array
129 // TODO: remove dependency on DatabaseBlock
130 $blocks = DatabaseBlock
::newListFromTarget( $user, $ip, !$fromReplica );
133 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
134 if ( $cookieBlock instanceof AbstractBlock
) {
135 $blocks[] = $cookieBlock;
139 if ( $ip !== null && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) ) {
141 if ( $this->isLocallyBlockedProxy( $ip ) ) {
142 $blocks[] = new SystemBlock( [
143 'byText' => wfMessage( 'proxyblocker' )->text(),
144 'reason' => wfMessage( 'proxyblockreason' )->plain(),
146 'systemBlock' => 'proxy',
148 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
149 $blocks[] = new SystemBlock( [
150 'byText' => wfMessage( 'sorbs' )->text(),
151 'reason' => wfMessage( 'sorbsreason' )->plain(),
153 'systemBlock' => 'dnsbl',
158 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
159 if ( $this->options
->get( 'ApplyIpBlocksToXff' )
161 && !in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) )
163 $xff = $request->getHeader( 'X-Forwarded-For' );
164 $xff = array_map( 'trim', explode( ',', $xff ) );
165 $xff = array_diff( $xff, [ $ip ] );
166 // TODO: remove dependency on DatabaseBlock
167 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, !$fromReplica );
168 $blocks = array_merge( $blocks, $xffblocks );
174 && IP
::isInRanges( $ip, $this->options
->get( 'SoftBlockRanges' ) )
176 $blocks[] = new SystemBlock( [
178 'byText' => 'MediaWiki default',
179 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
181 'systemBlock' => 'wgSoftBlockRanges',
185 // Filter out any duplicated blocks, e.g. from the cookie
186 $blocks = $this->getUniqueBlocks( $blocks );
189 if ( count( $blocks ) > 0 ) {
190 if ( count( $blocks ) === 1 ) {
191 $block = $blocks[ 0 ];
193 $block = new CompositeBlock( [
195 'byText' => 'MediaWiki default',
196 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
197 'originalBlocks' => $blocks,
202 Hooks
::run( 'GetUserBlock', [ clone $user, $ip, &$block ] );
208 * Given a list of blocks, return a list of unique blocks.
210 * This usually means that each block has a unique ID. For a block with ID null,
211 * if it's an autoblock, it will be filtered out if the parent block is present;
212 * if not, it is assumed to be a unique system block, and kept.
214 * @param AbstractBlock[] $blocks
215 * @return AbstractBlock[]
217 private function getUniqueBlocks( array $blocks ) {
219 $databaseBlocks = [];
221 foreach ( $blocks as $block ) {
222 if ( $block instanceof SystemBlock
) {
223 $systemBlocks[] = $block;
224 } elseif ( $block->getType() === DatabaseBlock
::TYPE_AUTO
) {
225 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
226 $databaseBlocks[$block->getParentBlockId()] = $block;
229 $databaseBlocks[$block->getId()] = $block;
233 return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
237 * Try to load a block from an ID given in a cookie value. If the block is invalid
238 * doesn't exist, or the cookie value is malformed, remove the cookie.
240 * @param UserIdentity $user
241 * @param WebRequest $request
242 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
244 private function getBlockFromCookieValue(
248 $cookieValue = $request->getCookie( 'BlockID' );
249 if ( is_null( $cookieValue ) ) {
253 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
254 if ( !is_null( $blockCookieId ) ) {
255 // TODO: remove dependency on DatabaseBlock
256 $block = DatabaseBlock
::newFromID( $blockCookieId );
258 $block instanceof DatabaseBlock
&&
259 $this->shouldApplyCookieBlock( $block, $user->isAnon() )
265 $this->clearBlockCookie( $request->response() );
271 * Check if the block loaded from the cookie should be applied.
273 * @param DatabaseBlock $block
274 * @param bool $isAnon The user is logged out
275 * @return bool The block sould be applied
277 private function shouldApplyCookieBlock( DatabaseBlock
$block, $isAnon ) {
278 if ( !$block->isExpired() ) {
279 switch ( $block->getType() ) {
280 case DatabaseBlock
::TYPE_IP
:
281 case DatabaseBlock
::TYPE_RANGE
:
282 // If block is type IP or IP range, load only
283 // if user is not logged in (T152462)
285 $this->options
->get( 'CookieSetOnIpBlock' );
286 case DatabaseBlock
::TYPE_USER
:
287 return $block->isAutoblocking() &&
288 $this->options
->get( 'CookieSetOnAutoblock' );
297 * Check if an IP address is in the local proxy list
302 private function isLocallyBlockedProxy( $ip ) {
303 $proxyList = $this->options
->get( 'ProxyList' );
308 if ( !is_array( $proxyList ) ) {
309 // Load values from the specified file
310 $proxyList = array_map( 'trim', file( $proxyList ) );
313 $proxyListIPSet = new IPSet( $proxyList );
314 return $proxyListIPSet->match( $ip );
318 * Whether the given IP is in a DNS blacklist.
320 * @param string $ip IP to check
321 * @param bool $checkWhitelist Whether to check the whitelist first
322 * @return bool True if blacklisted.
324 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
325 if ( !$this->options
->get( 'EnableDnsBlacklist' ) ||
326 ( $checkWhitelist && in_array( $ip, $this->options
->get( 'ProxyWhitelist' ) ) )
331 return $this->inDnsBlacklist( $ip, $this->options
->get( 'DnsBlacklistUrls' ) );
335 * Whether the given IP is in a given DNS blacklist.
337 * @param string $ip IP to check
338 * @param array $bases Array of Strings: URL of the DNS blacklist
339 * @return bool True if blacklisted.
341 private function inDnsBlacklist( $ip, array $bases ) {
343 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
344 if ( IP
::isIPv4( $ip ) ) {
345 // Reverse IP, T23255
346 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
348 foreach ( $bases as $base ) {
350 // If we have an access key, use that too (ProjectHoneypot, etc.)
352 if ( is_array( $base ) ) {
353 if ( count( $base ) >= 2 ) {
354 // Access key is 1, base URL is 0
355 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
357 $hostname = "$ipReversed.{$base[0]}";
359 $basename = $base[0];
361 $hostname = "$ipReversed.$base";
365 $ipList = $this->checkHost( $hostname );
370 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
376 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
384 * Wrapper for mocking in tests.
386 * @param string $hostname DNSBL query
387 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
389 protected function checkHost( $hostname ) {
390 return gethostbynamel( $hostname );
394 * Set the 'BlockID' cookie depending on block type and user authentication status.
399 public function trackBlockWithCookie( User
$user ) {
400 $request = $user->getRequest();
401 if ( $request->getCookie( 'BlockID' ) !== null ) {
402 // User already has a block cookie
406 // Defer checks until the user has been fully loaded to avoid circular dependency
407 // of User on itself (T180050 and T226777)
408 DeferredUpdates
::addCallableUpdate(
409 function () use ( $user, $request ) {
410 $block = $user->getBlock();
411 $response = $request->response();
412 $isAnon = $user->isAnon();
415 if ( $block instanceof CompositeBlock
) {
416 // TODO: Improve on simply tracking the first trackable block (T225654)
417 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
418 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
419 $this->setBlockCookie( $originalBlock, $response );
424 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
425 $this->setBlockCookie( $block, $response );
430 DeferredUpdates
::PRESEND
435 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
436 * the same as the block's, to a maximum of 24 hours.
439 * @internal Should be private.
440 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
441 * @param DatabaseBlock $block
442 * @param WebResponse $response The response on which to set the cookie.
444 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
445 // Calculate the default expiry time.
446 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
448 // Use the block's expiry time only if it's less than the default.
449 $expiryTime = $block->getExpiry();
450 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
451 $expiryTime = $maxExpiryTime;
454 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
455 $expiryValue = DateTime
::createFromFormat(
458 new DateTimeZone( 'UTC' )
460 $cookieOptions = [ 'httpOnly' => false ];
461 $cookieValue = $this->getCookieValue( $block );
462 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
466 * Check if the block should be tracked with a cookie.
468 * @param AbstractBlock $block
469 * @param bool $isAnon The user is logged out
470 * @return bool The block sould be tracked with a cookie
472 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
473 if ( $block instanceof DatabaseBlock
) {
474 switch ( $block->getType() ) {
475 case DatabaseBlock
::TYPE_IP
:
476 case DatabaseBlock
::TYPE_RANGE
:
477 return $isAnon && $this->options
->get( 'CookieSetOnIpBlock' );
478 case DatabaseBlock
::TYPE_USER
:
480 $this->options
->get( 'CookieSetOnAutoblock' ) &&
481 $block->isAutoblocking();
490 * Unset the 'BlockID' cookie.
493 * @param WebResponse $response
495 public static function clearBlockCookie( WebResponse
$response ) {
496 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
500 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
501 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
504 * @internal Should be private.
505 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
506 * @param string $cookieValue The string in which to find the ID.
507 * @return int|null The block ID, or null if the HMAC is present and invalid.
509 public function getIdFromCookieValue( $cookieValue ) {
510 // The cookie value must start with a number
511 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
515 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
516 $bangPos = strpos( $cookieValue, '!' );
517 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
518 if ( !$this->options
->get( 'SecretKey' ) ) {
519 // If there's no secret key, just use the ID as given.
522 $storedHmac = substr( $cookieValue, $bangPos +
1 );
523 $calculatedHmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
524 if ( $calculatedHmac === $storedHmac ) {
532 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
533 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
537 * @internal Should be private.
538 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
539 * @param DatabaseBlock $block
540 * @return string The block ID, probably concatenated with "!" and the HMAC.
542 public function getCookieValue( DatabaseBlock
$block ) {
543 $id = $block->getId();
544 if ( !$this->options
->get( 'SecretKey' ) ) {
545 // If there's no secret key, don't append a HMAC.
548 $hmac = MWCryptHash
::hmac( $id, $this->options
->get( 'SecretKey' ), false );
549 $cookieValue = $id . '!' . $hmac;