MediaWiki  master
BlockManager.php
Go to the documentation of this file.
1 <?php
21 namespace MediaWiki\Block;
22 
23 use LogicException;
31 use Message;
32 use MWCryptHash;
33 use Psr\Log\LoggerInterface;
34 use User;
35 use WebRequest;
36 use WebResponse;
37 use Wikimedia\IPSet;
38 use Wikimedia\IPUtils;
39 
46 class BlockManager {
48  private $permissionManager;
49 
51  private $userFactory;
52 
54  private $options;
55 
59  public const CONSTRUCTOR_OPTIONS = [
69  ];
70 
72  private $logger;
73 
75  private $hookRunner;
76 
84  public function __construct(
85  ServiceOptions $options,
86  PermissionManager $permissionManager,
87  UserFactory $userFactory,
88  LoggerInterface $logger,
89  HookContainer $hookContainer
90  ) {
91  $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
92  $this->options = $options;
93  $this->permissionManager = $permissionManager;
94  $this->userFactory = $userFactory;
95  $this->logger = $logger;
96  $this->hookRunner = new HookRunner( $hookContainer );
97  }
98 
131  public function getUserBlock(
132  UserIdentity $user,
133  $request,
134  $fromReplica,
135  $disableIpBlockExemptChecking = false
136  ) {
137  $fromPrimary = !$fromReplica;
138  $ip = null;
139 
140  // If this is the global user, they may be affected by IP blocks (case #1),
141  // or they may be exempt (case #2). If affected, look for additional blocks
142  // against the IP address and referenced in a cookie.
143  $checkIpBlocks = $request &&
144  // Because calling getBlock within Autopromote leads back to here,
145  // thus causing a infinite recursion. We fix this by not checking for
146  // ipblock-exempt when calling getBlock within Autopromote.
147  // See T270145.
148  !$disableIpBlockExemptChecking &&
149  !$this->permissionManager->userHasRight( $user, 'ipblock-exempt' );
150 
151  if ( $request && $checkIpBlocks ) {
152 
153  // Case #1: checking the global user, including IP blocks
154  $ip = $request->getIP();
155  $isAnon = !$user->isRegistered();
156 
157  $xff = $request->getHeader( 'X-Forwarded-For' );
158 
159  // TODO: remove dependency on DatabaseBlock (T221075)
160  $blocks = array_merge(
161  DatabaseBlock::newListFromTarget( $user, $ip, $fromPrimary ),
162  $this->getSystemIpBlocks( $ip, $isAnon ),
163  $this->getXffBlocks( $ip, $xff, $isAnon, $fromPrimary ),
164  $this->getCookieBlock( $user, $request )
165  );
166  } else {
167 
168  // Case #2: checking the global user, but they are exempt from IP blocks
169  // and cookie blocks, so we only check for a user account block.
170  // Case #3: checking whether another user's account is blocked.
171  // TODO: remove dependency on DatabaseBlock (T221075)
172  $blocks = DatabaseBlock::newListFromTarget( $user, null, $fromPrimary );
173 
174  }
175 
176  $block = $this->createGetBlockResult( $ip, $blocks );
177 
178  $legacyUser = $this->userFactory->newFromUserIdentity( $user );
179  $this->hookRunner->onGetUserBlock( clone $legacyUser, $ip, $block );
180 
181  return $block;
182  }
183 
189  private function createGetBlockResult( ?string $ip, array $blocks ): ?AbstractBlock {
190  // Filter out any duplicated blocks, e.g. from the cookie
191  $blocks = $this->getUniqueBlocks( $blocks );
192 
193  if ( count( $blocks ) === 0 ) {
194  return null;
195  } elseif ( count( $blocks ) === 1 ) {
196  return $blocks[ 0 ];
197  } else {
198  // @phan-suppress-next-line SecurityCheck-DoubleEscaped
199  return new CompositeBlock( [
200  'address' => $ip,
201  'reason' => new Message( 'blockedtext-composite-reason' ),
202  'originalBlocks' => $blocks,
203  ] );
204  }
205  }
206 
216  public function getIpBlock( string $ip, bool $fromReplica ): ?AbstractBlock {
217  if ( !IPUtils::isValid( $ip ) ) {
218  return null;
219  }
220 
221  $blocks = array_merge(
222  DatabaseBlock::newListFromTarget( $ip, $ip, !$fromReplica ),
223  $this->getSystemIpBlocks( $ip, true )
224  );
225 
226  return $this->createGetBlockResult( $ip, $blocks );
227  }
228 
236  private function getCookieBlock( UserIdentity $user, WebRequest $request ): array {
237  $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
238 
239  return $cookieBlock instanceof DatabaseBlock ? [ $cookieBlock ] : [];
240  }
241 
249  private function getSystemIpBlocks( string $ip, bool $isAnon ): array {
250  $blocks = [];
251 
252  // Proxy blocking
253  if ( !in_array( $ip, $this->options->get( MainConfigNames::ProxyWhitelist ) ) ) {
254  // Local list
255  if ( $this->isLocallyBlockedProxy( $ip ) ) {
256  // @phan-suppress-next-line SecurityCheck-DoubleEscaped
257  $blocks[] = new SystemBlock( [
258  'reason' => new Message( 'proxyblockreason' ),
259  'address' => $ip,
260  'systemBlock' => 'proxy',
261  ] );
262  } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
263  // @phan-suppress-next-line SecurityCheck-DoubleEscaped
264  $blocks[] = new SystemBlock( [
265  'reason' => new Message( 'sorbsreason' ),
266  'address' => $ip,
267  'anonOnly' => true,
268  'systemBlock' => 'dnsbl',
269  ] );
270  }
271  }
272 
273  // Soft blocking
274  if ( $isAnon && IPUtils::isInRanges( $ip, $this->options->get( MainConfigNames::SoftBlockRanges ) ) ) {
275  // @phan-suppress-next-line SecurityCheck-DoubleEscaped
276  $blocks[] = new SystemBlock( [
277  'address' => $ip,
278  'reason' => new Message( 'softblockrangesreason', [ $ip ] ),
279  'anonOnly' => true,
280  'systemBlock' => 'wgSoftBlockRanges',
281  ] );
282  }
283 
284  return $blocks;
285  }
286 
298  private function getXffBlocks( string $ip, string $xff, bool $isAnon, bool $fromPrimary ): array {
299  // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
300  if ( $this->options->get( MainConfigNames::ApplyIpBlocksToXff )
301  && !in_array( $ip, $this->options->get( MainConfigNames::ProxyWhitelist ) )
302  ) {
303  $xff = array_map( 'trim', explode( ',', $xff ) );
304  $xff = array_diff( $xff, [ $ip ] );
305  // TODO: remove dependency on DatabaseBlock (T221075)
306  return DatabaseBlock::getBlocksForIPList( $xff, $isAnon, $fromPrimary );
307  }
308 
309  return [];
310  }
311 
322  private function getUniqueBlocks( array $blocks ) {
323  $systemBlocks = [];
324  $databaseBlocks = [];
325 
326  foreach ( $blocks as $block ) {
327  if ( $block instanceof SystemBlock ) {
328  $systemBlocks[] = $block;
329  } elseif ( $block->getType() === DatabaseBlock::TYPE_AUTO ) {
331  '@phan-var DatabaseBlock $block';
332  if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
333  $databaseBlocks[$block->getParentBlockId()] = $block;
334  }
335  } else {
336  // @phan-suppress-next-line PhanTypeMismatchDimAssignment getId is not null here
337  $databaseBlocks[$block->getId()] = $block;
338  }
339  }
340 
341  return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
342  }
343 
355  private function getBlockFromCookieValue(
356  UserIdentity $user,
357  WebRequest $request
358  ) {
359  $cookieValue = $request->getCookie( 'BlockID' );
360  if ( $cookieValue === null ) {
361  return false;
362  }
363 
364  $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
365  if ( $blockCookieId !== null ) {
366  // TODO: remove dependency on DatabaseBlock (T221075)
367  $block = DatabaseBlock::newFromID( $blockCookieId );
368  if (
369  $block instanceof DatabaseBlock &&
370  $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
371  ) {
372  return $block;
373  }
374  }
375 
376  return false;
377  }
378 
386  private function shouldApplyCookieBlock( DatabaseBlock $block, $isAnon ) {
387  if ( !$block->isExpired() ) {
388  switch ( $block->getType() ) {
389  case DatabaseBlock::TYPE_IP:
390  case DatabaseBlock::TYPE_RANGE:
391  // If block is type IP or IP range, load only
392  // if user is not logged in (T152462)
393  return $isAnon &&
394  $this->options->get( MainConfigNames::CookieSetOnIpBlock );
395  case DatabaseBlock::TYPE_USER:
396  return $block->isAutoblocking() &&
397  $this->options->get( MainConfigNames::CookieSetOnAutoblock );
398  default:
399  return false;
400  }
401  }
402  return false;
403  }
404 
411  private function isLocallyBlockedProxy( $ip ) {
412  $proxyList = $this->options->get( MainConfigNames::ProxyList );
413  if ( !$proxyList ) {
414  return false;
415  }
416 
417  if ( !is_array( $proxyList ) ) {
418  // Load values from the specified file
419  $proxyList = array_map( 'trim', file( $proxyList ) );
420  }
421 
422  $proxyListIPSet = new IPSet( $proxyList );
423  return $proxyListIPSet->match( $ip );
424  }
425 
433  public function isDnsBlacklisted( $ip, $checkAllowed = false ) {
434  if ( !$this->options->get( MainConfigNames::EnableDnsBlacklist ) ||
435  ( $checkAllowed && in_array( $ip, $this->options->get( MainConfigNames::ProxyWhitelist ) ) )
436  ) {
437  return false;
438  }
439 
440  return $this->inDnsBlacklist( $ip, $this->options->get( MainConfigNames::DnsBlacklistUrls ) );
441  }
442 
450  private function inDnsBlacklist( $ip, array $bases ) {
451  $found = false;
452  // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
453  if ( IPUtils::isIPv4( $ip ) ) {
454  // Reverse IP, T23255
455  $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
456 
457  foreach ( $bases as $base ) {
458  // Make hostname
459  // If we have an access key, use that too (ProjectHoneypot, etc.)
460  $basename = $base;
461  if ( is_array( $base ) ) {
462  if ( count( $base ) >= 2 ) {
463  // Access key is 1, base URL is 0
464  $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
465  } else {
466  $hostname = "$ipReversed.{$base[0]}";
467  }
468  $basename = $base[0];
469  } else {
470  $hostname = "$ipReversed.$base";
471  }
472 
473  // Send query
474  $ipList = $this->checkHost( $hostname );
475 
476  if ( $ipList ) {
477  $this->logger->info(
478  'Hostname {hostname} is {ipList}, it\'s a proxy says {basename}!',
479  [
480  'hostname' => $hostname,
481  'ipList' => $ipList[0],
482  'basename' => $basename,
483  ]
484  );
485  $found = true;
486  break;
487  }
488 
489  $this->logger->debug( "Requested $hostname, not found in $basename." );
490  }
491  }
492 
493  return $found;
494  }
495 
502  protected function checkHost( $hostname ) {
503  return gethostbynamel( $hostname );
504  }
505 
525  public function trackBlockWithCookie( User $user, WebResponse $response ) {
526  $request = $user->getRequest();
527 
528  if ( $request->getCookie( 'BlockID' ) !== null ) {
529  $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
530  if ( $cookieBlock && $this->shouldApplyCookieBlock( $cookieBlock, $user->isAnon() ) ) {
531  return;
532  }
533  // The block pointed to by the cookie is invalid or should not be tracked.
534  $this->clearBlockCookie( $response );
535  }
536 
537  if ( !$user->isSafeToLoad() ) {
538  // Prevent a circular dependency by not allowing this method to be called
539  // before or while the user is being loaded.
540  // E.g. User > BlockManager > Block > Message > getLanguage > User.
541  // See also T180050 and T226777.
542  throw new LogicException( __METHOD__ . ' requires a loaded User object' );
543  }
544  if ( $response->headersSent() ) {
545  throw new LogicException( __METHOD__ . ' must be called pre-send' );
546  }
547 
548  $block = $user->getBlock();
549  $isAnon = $user->isAnon();
550 
551  if ( $block ) {
552  if ( $block instanceof CompositeBlock ) {
553  // TODO: Improve on simply tracking the first trackable block (T225654)
554  foreach ( $block->getOriginalBlocks() as $originalBlock ) {
555  if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
556  '@phan-var DatabaseBlock $originalBlock';
557  $this->setBlockCookie( $originalBlock, $response );
558  return;
559  }
560  }
561  } else {
562  if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
563  '@phan-var DatabaseBlock $block';
564  $this->setBlockCookie( $block, $response );
565  }
566  }
567  }
568  }
569 
580  public function setBlockCookie( DatabaseBlock $block, WebResponse $response ) {
581  // Calculate the default expiry time.
582  $maxExpiryTime = wfTimestamp( TS_MW, (int)wfTimestamp() + ( 24 * 60 * 60 ) );
583 
584  // Use the block's expiry time only if it's less than the default.
585  $expiryTime = $block->getExpiry();
586  if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
587  $expiryTime = $maxExpiryTime;
588  }
589 
590  // Set the cookie
591  $expiryValue = (int)wfTimestamp( TS_UNIX, $expiryTime );
592  $cookieOptions = [ 'httpOnly' => false ];
593  $cookieValue = $this->getCookieValue( $block );
594  $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
595  }
596 
604  private function shouldTrackBlockWithCookie( AbstractBlock $block, $isAnon ) {
605  if ( $block instanceof DatabaseBlock ) {
606  switch ( $block->getType() ) {
607  case DatabaseBlock::TYPE_IP:
608  case DatabaseBlock::TYPE_RANGE:
609  return $isAnon && $this->options->get( MainConfigNames::CookieSetOnIpBlock );
610  case DatabaseBlock::TYPE_USER:
611  return !$isAnon &&
612  $this->options->get( MainConfigNames::CookieSetOnAutoblock ) &&
613  $block->isAutoblocking();
614  default:
615  return false;
616  }
617  }
618  return false;
619  }
620 
627  public static function clearBlockCookie( WebResponse $response ) {
628  $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
629  }
630 
641  public function getIdFromCookieValue( $cookieValue ) {
642  // The cookie value must start with a number
643  if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
644  return null;
645  }
646 
647  // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
648  $bangPos = strpos( $cookieValue, '!' );
649  $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
650  if ( !$this->options->get( MainConfigNames::SecretKey ) ) {
651  // If there's no secret key, just use the ID as given.
652  return (int)$id;
653  }
654  $storedHmac = substr( $cookieValue, $bangPos + 1 );
655  $calculatedHmac = MWCryptHash::hmac( $id, $this->options->get( MainConfigNames::SecretKey ), false );
656  if ( $calculatedHmac === $storedHmac ) {
657  return (int)$id;
658  } else {
659  return null;
660  }
661  }
662 
674  public function getCookieValue( DatabaseBlock $block ) {
675  $id = (string)$block->getId();
676  if ( !$this->options->get( MainConfigNames::SecretKey ) ) {
677  // If there's no secret key, don't append a HMAC.
678  return $id;
679  }
680  $hmac = MWCryptHash::hmac( $id, $this->options->get( MainConfigNames::SecretKey ), false );
681  $cookieValue = $id . '!' . $hmac;
682  return $cookieValue;
683  }
684 
685 }
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
if(!defined('MW_SETUP_CALLBACK'))
The persistent session ID (if any) loaded at startup.
Definition: WebStart.php:82
static hmac( $data, $key, $raw=true)
Generate a keyed cryptographic hash value (HMAC) for a string, making use of the best hash algorithm ...
getType()
Get the type of target for this particular block.
getExpiry()
Get the block expiry time.
A service class for checking blocks.
trackBlockWithCookie(User $user, WebResponse $response)
Set the 'BlockID' cookie depending on block type and user authentication status.
isDnsBlacklisted( $ip, $checkAllowed=false)
Whether the given IP is in a DNS blacklist.
getIpBlock(string $ip, bool $fromReplica)
Get the blocks that apply to an IP address.
setBlockCookie(DatabaseBlock $block, WebResponse $response)
Set the 'BlockID' cookie to this block's ID and expiry time.
__construct(ServiceOptions $options, PermissionManager $permissionManager, UserFactory $userFactory, LoggerInterface $logger, HookContainer $hookContainer)
checkHost( $hostname)
Wrapper for mocking in tests.
getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
getUserBlock(UserIdentity $user, $request, $fromReplica, $disableIpBlockExemptChecking=false)
Get the blocks that apply to a user.
static clearBlockCookie(WebResponse $response)
Unset the 'BlockID' cookie.
getCookieValue(DatabaseBlock $block)
Get the BlockID cookie's value for this block.
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
static newListFromTarget( $specificTarget, $vagueTarget=null, $fromPrimary=false)
This is similar to DatabaseBlock::newFromTarget, but it returns all the relevant blocks.
getId( $wikiId=self::LOCAL)
Get the block ID.(since 1.38) ?int
A class for passing options to services.
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:561
A class containing constants representing the names of configuration variables.
const DnsBlacklistUrls
Name constant for the DnsBlacklistUrls setting, for use with Config::get()
const SoftBlockRanges
Name constant for the SoftBlockRanges setting, for use with Config::get()
const CookieSetOnAutoblock
Name constant for the CookieSetOnAutoblock setting, for use with Config::get()
const EnableDnsBlacklist
Name constant for the EnableDnsBlacklist setting, for use with Config::get()
const ApplyIpBlocksToXff
Name constant for the ApplyIpBlocksToXff setting, for use with Config::get()
const ProxyList
Name constant for the ProxyList setting, for use with Config::get()
const ProxyWhitelist
Name constant for the ProxyWhitelist setting, for use with Config::get()
const CookieSetOnIpBlock
Name constant for the CookieSetOnIpBlock setting, for use with Config::get()
const SecretKey
Name constant for the SecretKey setting, for use with Config::get()
A service class for checking permissions To obtain an instance, use MediaWikiServices::getInstance()-...
Creates User objects.
Definition: UserFactory.php:38
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:141
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:70
getBlock( $freshness=self::READ_NORMAL, $disableIpBlockExemptChecking=false)
Get the block affecting the user, or null if the user is not blocked.
Definition: User.php:1520
getRequest()
Get the WebRequest object to use with this object.
Definition: User.php:2432
isSafeToLoad()
Test if it's safe to load this User object.
Definition: User.php:350
isAnon()
Get whether the user is anonymous.
Definition: User.php:2336
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:44
getIP()
Work out the IP address based on various globals For trusted proxies, use the XFF client IP (first of...
getCookie( $key, $prefix=null, $default=null)
Get a cookie from the $_COOKIE jar.
Definition: WebRequest.php:876
getHeader( $name, $flags=0)
Get a request header, or false if it isn't set.
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:32
setCookie( $name, $value, $expire=0, $options=[])
Set the browser cookie.
clearCookie( $name, $options=[])
Unset a browser cookie.
headersSent()
Test if headers have been sent.
Interface for objects representing user identity.