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
;
25 use MediaWiki\User\UserIdentity
;
33 * A service class for checking blocks.
34 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
36 * @since 1.34 Refactored from User and Block.
39 // TODO: This should be UserIdentity instead of User
43 /** @var WebRequest */
44 private $currentRequest;
47 private $applyIpBlocksToXff;
50 private $cookieSetOnAutoblock;
53 private $cookieSetOnIpBlock;
56 private $dnsBlacklistUrls;
59 private $enableDnsBlacklist;
65 private $proxyWhitelist;
67 /** @var string|bool */
71 private $softBlockRanges;
74 * @param User $currentUser
75 * @param WebRequest $currentRequest
76 * @param bool $applyIpBlocksToXff
77 * @param bool $cookieSetOnAutoblock
78 * @param bool $cookieSetOnIpBlock
79 * @param array $dnsBlacklistUrls
80 * @param bool $enableDnsBlacklist
81 * @param array $proxyList
82 * @param array $proxyWhitelist
83 * @param string $secretKey
84 * @param array $softBlockRanges
86 public function __construct(
90 $cookieSetOnAutoblock,
99 $this->currentUser
= $currentUser;
100 $this->currentRequest
= $currentRequest;
101 $this->applyIpBlocksToXff
= $applyIpBlocksToXff;
102 $this->cookieSetOnAutoblock
= $cookieSetOnAutoblock;
103 $this->cookieSetOnIpBlock
= $cookieSetOnIpBlock;
104 $this->dnsBlacklistUrls
= $dnsBlacklistUrls;
105 $this->enableDnsBlacklist
= $enableDnsBlacklist;
106 $this->proxyList
= $proxyList;
107 $this->proxyWhitelist
= $proxyWhitelist;
108 $this->secretKey
= $secretKey;
109 $this->softBlockRanges
= $softBlockRanges;
113 * Get the blocks that apply to a user and return the most relevant one.
115 * TODO: $user should be UserIdentity instead of User
117 * @internal This should only be called by User::getBlockedStatus
119 * @param bool $fromReplica Whether to check the replica DB first.
120 * To improve performance, non-critical checks are done against replica DBs.
121 * Check when actually saving should be done against master.
122 * @return AbstractBlock|null The most relevant block, or null if there is no block.
124 public function getUserBlock( User
$user, $fromReplica ) {
125 $isAnon = $user->getId() === 0;
127 // TODO: If $user is the current user, we should use the current request. Otherwise,
128 // we should not look for XFF or cookie blocks.
129 $request = $user->getRequest();
131 # We only need to worry about passing the IP address to the block generator if the
132 # user is not immune to autoblocks/hardblocks, and they are the current user so we
133 # know which IP address they're actually coming from
135 $sessionUser = $this->currentUser
;
136 // the session user is set up towards the end of Setup.php. Until then,
137 // assume it's a logged-out user.
138 $globalUserName = $sessionUser->isSafeToLoad()
139 ?
$sessionUser->getName()
140 : IP
::sanitizeIP( $this->currentRequest
->getIP() );
141 if ( $user->getName() === $globalUserName && !$user->isAllowed( 'ipblock-exempt' ) ) {
142 $ip = $this->currentRequest
->getIP();
146 // TODO: remove dependency on DatabaseBlock
147 $block = DatabaseBlock
::newFromTarget( $user, $ip, !$fromReplica );
150 if ( !$block instanceof AbstractBlock
) {
151 $block = $this->getBlockFromCookieValue( $user, $request );
155 if ( !$block instanceof AbstractBlock
157 && !in_array( $ip, $this->proxyWhitelist
)
160 if ( $this->isLocallyBlockedProxy( $ip ) ) {
161 $block = new SystemBlock( [
162 'byText' => wfMessage( 'proxyblocker' )->text(),
163 'reason' => wfMessage( 'proxyblockreason' )->plain(),
165 'systemBlock' => 'proxy',
167 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
168 $block = new SystemBlock( [
169 'byText' => wfMessage( 'sorbs' )->text(),
170 'reason' => wfMessage( 'sorbsreason' )->plain(),
172 'systemBlock' => 'dnsbl',
177 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
178 if ( !$block instanceof AbstractBlock
179 && $this->applyIpBlocksToXff
181 && !in_array( $ip, $this->proxyWhitelist
)
183 $xff = $request->getHeader( 'X-Forwarded-For' );
184 $xff = array_map( 'trim', explode( ',', $xff ) );
185 $xff = array_diff( $xff, [ $ip ] );
186 // TODO: remove dependency on DatabaseBlock
187 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, !$fromReplica );
188 // TODO: remove dependency on DatabaseBlock
189 $block = DatabaseBlock
::chooseBlock( $xffblocks, $xff );
190 if ( $block instanceof AbstractBlock
) {
191 # Mangle the reason to alert the user that the block
192 # originated from matching the X-Forwarded-For header.
193 $block->setReason( wfMessage( 'xffblockreason', $block->getReason() )->plain() );
197 if ( !$block instanceof AbstractBlock
200 && IP
::isInRanges( $ip, $this->softBlockRanges
)
202 $block = new SystemBlock( [
204 'byText' => 'MediaWiki default',
205 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
207 'systemBlock' => 'wgSoftBlockRanges',
215 * Try to load a block from an ID given in a cookie value.
217 * @param UserIdentity $user
218 * @param WebRequest $request
219 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
221 private function getBlockFromCookieValue(
225 $blockCookieVal = $request->getCookie( 'BlockID' );
226 $response = $request->response();
228 // Make sure there's something to check. The cookie value must start with a number.
229 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
232 // Load the block from the ID in the cookie.
233 $blockCookieId = $this->getIdFromCookieValue( $blockCookieVal );
234 if ( $blockCookieId !== null ) {
235 // An ID was found in the cookie.
236 // TODO: remove dependency on DatabaseBlock
237 $tmpBlock = DatabaseBlock
::newFromID( $blockCookieId );
238 if ( $tmpBlock instanceof DatabaseBlock
) {
239 switch ( $tmpBlock->getType() ) {
240 case DatabaseBlock
::TYPE_USER
:
241 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
242 $useBlockCookie = ( $this->cookieSetOnAutoblock
=== true );
244 case DatabaseBlock
::TYPE_IP
:
245 case DatabaseBlock
::TYPE_RANGE
:
246 // If block is type IP or IP range, load only if user is not logged in (T152462)
247 $blockIsValid = !$tmpBlock->isExpired() && $user->getId() === 0;
248 $useBlockCookie = ( $this->cookieSetOnIpBlock
=== true );
251 $blockIsValid = false;
252 $useBlockCookie = false;
255 if ( $blockIsValid && $useBlockCookie ) {
260 // If the block is invalid or doesn't exist, remove the cookie.
261 $this->clearBlockCookie( $response );
267 * Check if an IP address is in the local proxy list
272 private function isLocallyBlockedProxy( $ip ) {
273 if ( !$this->proxyList
) {
277 if ( !is_array( $this->proxyList
) ) {
278 // Load values from the specified file
279 $this->proxyList
= array_map( 'trim', file( $this->proxyList
) );
282 $resultProxyList = [];
283 $deprecatedIPEntries = [];
285 // backward compatibility: move all ip addresses in keys to values
286 foreach ( $this->proxyList
as $key => $value ) {
287 $keyIsIP = IP
::isIPAddress( $key );
288 $valueIsIP = IP
::isIPAddress( $value );
289 if ( $keyIsIP && !$valueIsIP ) {
290 $deprecatedIPEntries[] = $key;
291 $resultProxyList[] = $key;
292 } elseif ( $keyIsIP && $valueIsIP ) {
293 $deprecatedIPEntries[] = $key;
294 $resultProxyList[] = $key;
295 $resultProxyList[] = $value;
297 $resultProxyList[] = $value;
301 if ( $deprecatedIPEntries ) {
303 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
304 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
307 $proxyListIPSet = new IPSet( $resultProxyList );
308 return $proxyListIPSet->match( $ip );
312 * Whether the given IP is in a DNS blacklist.
314 * @param string $ip IP to check
315 * @param bool $checkWhitelist Whether to check the whitelist first
316 * @return bool True if blacklisted.
318 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
319 if ( !$this->enableDnsBlacklist ||
320 ( $checkWhitelist && in_array( $ip, $this->proxyWhitelist
) )
325 return $this->inDnsBlacklist( $ip, $this->dnsBlacklistUrls
);
329 * Whether the given IP is in a given DNS blacklist.
331 * @param string $ip IP to check
332 * @param array $bases Array of Strings: URL of the DNS blacklist
333 * @return bool True if blacklisted.
335 private function inDnsBlacklist( $ip, array $bases ) {
337 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
338 if ( IP
::isIPv4( $ip ) ) {
339 // Reverse IP, T23255
340 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
342 foreach ( $bases as $base ) {
344 // If we have an access key, use that too (ProjectHoneypot, etc.)
346 if ( is_array( $base ) ) {
347 if ( count( $base ) >= 2 ) {
348 // Access key is 1, base URL is 0
349 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
351 $hostname = "$ipReversed.{$base[0]}";
353 $basename = $base[0];
355 $hostname = "$ipReversed.$base";
359 $ipList = $this->checkHost( $hostname );
364 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
370 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
378 * Wrapper for mocking in tests.
380 * @param string $hostname DNSBL query
381 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
383 protected function checkHost( $hostname ) {
384 return gethostbynamel( $hostname );
388 * Set the 'BlockID' cookie depending on block type and user authentication status.
393 public function trackBlockWithCookie( User
$user ) {
394 $block = $user->getBlock();
395 $request = $user->getRequest();
399 $request->getCookie( 'BlockID' ) === null &&
400 $this->shouldTrackBlockWithCookie( $block, $user->isAnon() )
402 $this->setBlockCookie( $block, $request->response() );
407 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
408 * the same as the block's, to a maximum of 24 hours.
411 * @internal Should be private.
412 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
413 * @param DatabaseBlock $block
414 * @param WebResponse $response The response on which to set the cookie.
416 public function setBlockCookie( DatabaseBlock
$block, WebResponse
$response ) {
417 // Calculate the default expiry time.
418 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
420 // Use the block's expiry time only if it's less than the default.
421 $expiryTime = $block->getExpiry();
422 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
423 $expiryTime = $maxExpiryTime;
426 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
427 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
428 $cookieOptions = [ 'httpOnly' => false ];
429 $cookieValue = $this->getCookieValue( $block );
430 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
434 * Check if the block should be tracked with a cookie.
436 * @param AbstractBlock $block
437 * @param bool $isAnon The user is logged out
438 * @return bool The block sould be tracked with a cookie
440 private function shouldTrackBlockWithCookie( AbstractBlock
$block, $isAnon ) {
441 if ( $block instanceof DatabaseBlock
) {
442 switch ( $block->getType() ) {
443 case DatabaseBlock
::TYPE_IP
:
444 case DatabaseBlock
::TYPE_RANGE
:
445 return $isAnon && $this->cookieSetOnIpBlock
;
446 case DatabaseBlock
::TYPE_USER
:
447 return !$isAnon && $this->cookieSetOnAutoblock
&& $block->isAutoblocking();
456 * Unset the 'BlockID' cookie.
459 * @param WebResponse $response
461 public static function clearBlockCookie( WebResponse
$response ) {
462 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
466 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
467 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
470 * @internal Should be private.
471 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
472 * @param string $cookieValue The string in which to find the ID.
473 * @return int|null The block ID, or null if the HMAC is present and invalid.
475 public function getIdFromCookieValue( $cookieValue ) {
476 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
477 $bangPos = strpos( $cookieValue, '!' );
478 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
479 if ( !$this->secretKey
) {
480 // If there's no secret key, just use the ID as given.
483 $storedHmac = substr( $cookieValue, $bangPos +
1 );
484 $calculatedHmac = MWCryptHash
::hmac( $id, $this->secretKey
, false );
485 if ( $calculatedHmac === $storedHmac ) {
493 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
494 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
498 * @internal Should be private.
499 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
500 * @param DatabaseBlock $block
501 * @return string The block ID, probably concatenated with "!" and the HMAC.
503 public function getCookieValue( DatabaseBlock
$block ) {
504 $id = $block->getId();
505 if ( !$this->secretKey
) {
506 // If there's no secret key, don't append a HMAC.
509 $hmac = MWCryptHash
::hmac( $id, $this->secretKey
, false );
510 $cookieValue = $id . '!' . $hmac;