MediaWiki  master
BlockManager.php
Go to the documentation of this file.
1 <?php
21 namespace MediaWiki\Block;
22 
23 use DateTime;
24 use DateTimeZone;
25 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 {
49 
51  private $options;
52 
57  public const CONSTRUCTOR_OPTIONS = [
58  'ApplyIpBlocksToXff',
59  'CookieSetOnAutoblock',
60  'CookieSetOnIpBlock',
61  'DnsBlacklistUrls',
62  'EnableDnsBlacklist',
63  'ProxyList',
64  'ProxyWhitelist',
65  'SecretKey',
66  'SoftBlockRanges',
67  ];
68 
70  private $logger;
71 
73  private $hookRunner;
74 
81  public function __construct(
84  LoggerInterface $logger,
85  HookContainer $hookContainer
86  ) {
87  $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
88  $this->options = $options;
89  $this->permissionManager = $permissionManager;
90  $this->logger = $logger;
91  $this->hookRunner = new HookRunner( $hookContainer );
92  }
93 
124  public function getUserBlock( User $user, $request, $fromReplica ) {
125  $fromMaster = !$fromReplica;
126  $ip = null;
127 
128  // If this is the global user, they may be affected by IP blocks (case #1),
129  // or they may be exempt (case #2). If affected, look for additional blocks
130  // against the IP address and referenced in a cookie.
131  $checkIpBlocks = $request &&
132  !$this->permissionManager->userHasRight( $user, 'ipblock-exempt' );
133 
134  if ( $request && $checkIpBlocks ) {
135 
136  // Case #1: checking the global user, including IP blocks
137  $ip = $request->getIP();
138  // TODO: remove dependency on DatabaseBlock (T221075)
139  $blocks = DatabaseBlock::newListFromTarget( $user, $ip, $fromMaster );
140  $this->getAdditionalIpBlocks( $blocks, $request, !$user->isRegistered(), $fromMaster );
141  $this->getCookieBlock( $blocks, $user, $request );
142 
143  } else {
144 
145  // Case #2: checking the global user, but they are exempt from IP blocks
146  // and cookie blocks, so we only check for a user account block.
147  // Case #3: checking whether another user's account is blocked.
148  // TODO: remove dependency on DatabaseBlock (T221075)
149  $blocks = DatabaseBlock::newListFromTarget( $user, null, $fromMaster );
150 
151  }
152 
153  // Filter out any duplicated blocks, e.g. from the cookie
154  $blocks = $this->getUniqueBlocks( $blocks );
155 
156  $block = null;
157  if ( count( $blocks ) > 0 ) {
158  if ( count( $blocks ) === 1 ) {
159  $block = $blocks[ 0 ];
160  } else {
161  $block = new CompositeBlock( [
162  'address' => $ip,
163  'reason' => new Message( 'blockedtext-composite-reason' ),
164  'originalBlocks' => $blocks,
165  ] );
166  }
167  }
168 
169  $this->hookRunner->onGetUserBlock( clone $user, $ip, $block );
170 
171  return $block;
172  }
173 
182  private function getCookieBlock( &$blocks, UserIdentity $user, WebRequest $request ) {
183  $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
184  if ( $cookieBlock instanceof DatabaseBlock ) {
185  $blocks[] = $cookieBlock;
186  }
187  }
188 
198  private function getAdditionalIpBlocks( &$blocks, WebRequest $request, $isAnon, $fromMaster ) {
199  $ip = $request->getIP();
200 
201  // Proxy blocking
202  if ( !in_array( $ip, $this->options->get( 'ProxyWhitelist' ) ) ) {
203  // Local list
204  if ( $this->isLocallyBlockedProxy( $ip ) ) {
205  $blocks[] = new SystemBlock( [
206  'reason' => new Message( 'proxyblockreason' ),
207  'address' => $ip,
208  'systemBlock' => 'proxy',
209  ] );
210  } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
211  $blocks[] = new SystemBlock( [
212  'reason' => new Message( 'sorbsreason' ),
213  'address' => $ip,
214  'systemBlock' => 'dnsbl',
215  ] );
216  }
217  }
218 
219  // Soft blocking
220  if ( $isAnon && IPUtils::isInRanges( $ip, $this->options->get( 'SoftBlockRanges' ) ) ) {
221  $blocks[] = new SystemBlock( [
222  'address' => $ip,
223  'reason' => new Message( 'softblockrangesreason', [ $ip ] ),
224  'anonOnly' => true,
225  'systemBlock' => 'wgSoftBlockRanges',
226  ] );
227  }
228 
229  // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
230  if ( $this->options->get( 'ApplyIpBlocksToXff' )
231  && !in_array( $ip, $this->options->get( 'ProxyWhitelist' ) )
232  ) {
233  $xff = $request->getHeader( 'X-Forwarded-For' );
234  $xff = array_map( 'trim', explode( ',', $xff ) );
235  $xff = array_diff( $xff, [ $ip ] );
236  // TODO: remove dependency on DatabaseBlock (T221075)
237  $xffblocks = DatabaseBlock::getBlocksForIPList( $xff, $isAnon, $fromMaster );
238  $blocks = array_merge( $blocks, $xffblocks );
239  }
240  }
241 
252  private function getUniqueBlocks( array $blocks ) {
253  $systemBlocks = [];
254  $databaseBlocks = [];
255 
256  foreach ( $blocks as $block ) {
257  if ( $block instanceof SystemBlock ) {
258  $systemBlocks[] = $block;
259  } elseif ( $block->getType() === DatabaseBlock::TYPE_AUTO ) {
261  '@phan-var DatabaseBlock $block';
262  if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
263  $databaseBlocks[$block->getParentBlockId()] = $block;
264  }
265  } else {
266  $databaseBlocks[$block->getId()] = $block;
267  }
268  }
269 
270  return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
271  }
272 
284  private function getBlockFromCookieValue(
285  UserIdentity $user,
286  WebRequest $request
287  ) {
288  $cookieValue = $request->getCookie( 'BlockID' );
289  if ( $cookieValue === null ) {
290  return false;
291  }
292 
293  $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
294  if ( $blockCookieId !== null ) {
295  // TODO: remove dependency on DatabaseBlock (T221075)
296  $block = DatabaseBlock::newFromID( $blockCookieId );
297  if (
298  $block instanceof DatabaseBlock &&
299  $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
300  ) {
301  return $block;
302  }
303  }
304 
305  return false;
306  }
307 
315  private function shouldApplyCookieBlock( DatabaseBlock $block, $isAnon ) {
316  if ( !$block->isExpired() ) {
317  switch ( $block->getType() ) {
320  // If block is type IP or IP range, load only
321  // if user is not logged in (T152462)
322  return $isAnon &&
323  $this->options->get( 'CookieSetOnIpBlock' );
325  return $block->isAutoblocking() &&
326  $this->options->get( 'CookieSetOnAutoblock' );
327  default:
328  return false;
329  }
330  }
331  return false;
332  }
333 
340  private function isLocallyBlockedProxy( $ip ) {
341  $proxyList = $this->options->get( 'ProxyList' );
342  if ( !$proxyList ) {
343  return false;
344  }
345 
346  if ( !is_array( $proxyList ) ) {
347  // Load values from the specified file
348  $proxyList = array_map( 'trim', file( $proxyList ) );
349  }
350 
351  $proxyListIPSet = new IPSet( $proxyList );
352  return $proxyListIPSet->match( $ip );
353  }
354 
362  public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
363  if ( !$this->options->get( 'EnableDnsBlacklist' ) ||
364  ( $checkWhitelist && in_array( $ip, $this->options->get( 'ProxyWhitelist' ) ) )
365  ) {
366  return false;
367  }
368 
369  return $this->inDnsBlacklist( $ip, $this->options->get( 'DnsBlacklistUrls' ) );
370  }
371 
379  private function inDnsBlacklist( $ip, array $bases ) {
380  $found = false;
381  // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
382  if ( IPUtils::isIPv4( $ip ) ) {
383  // Reverse IP, T23255
384  $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
385 
386  foreach ( $bases as $base ) {
387  // Make hostname
388  // If we have an access key, use that too (ProjectHoneypot, etc.)
389  $basename = $base;
390  if ( is_array( $base ) ) {
391  if ( count( $base ) >= 2 ) {
392  // Access key is 1, base URL is 0
393  $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
394  } else {
395  $hostname = "$ipReversed.{$base[0]}";
396  }
397  $basename = $base[0];
398  } else {
399  $hostname = "$ipReversed.$base";
400  }
401 
402  // Send query
403  $ipList = $this->checkHost( $hostname );
404 
405  if ( $ipList ) {
406  $this->logger->info(
407  "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
408  );
409  $found = true;
410  break;
411  }
412 
413  $this->logger->debug( "Requested $hostname, not found in $basename." );
414  }
415  }
416 
417  return $found;
418  }
419 
426  protected function checkHost( $hostname ) {
427  return gethostbynamel( $hostname );
428  }
429 
449  public function trackBlockWithCookie( User $user, WebResponse $response ) {
450  $request = $user->getRequest();
451 
452  if ( $request->getCookie( 'BlockID' ) !== null ) {
453  $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
454  if ( $cookieBlock && $this->shouldApplyCookieBlock( $cookieBlock, $user->isAnon() ) ) {
455  return;
456  }
457  // The block pointed to by the cookie is invalid or should not be tracked.
458  $this->clearBlockCookie( $response );
459  }
460 
461  if ( !$user->isSafeToLoad() ) {
462  // Prevent a circular dependency by not allowing this method to be called
463  // before or while the user is being loaded.
464  // E.g. User > BlockManager > Block > Message > getLanguage > User.
465  // See also T180050 and T226777.
466  throw new LogicException( __METHOD__ . ' requires a loaded User object' );
467  }
468  if ( $response->headersSent() ) {
469  throw new LogicException( __METHOD__ . ' must be called pre-send' );
470  }
471 
472  $block = $user->getBlock();
473  $isAnon = $user->isAnon();
474 
475  if ( $block ) {
476  if ( $block instanceof CompositeBlock ) {
477  // TODO: Improve on simply tracking the first trackable block (T225654)
478  foreach ( $block->getOriginalBlocks() as $originalBlock ) {
479  if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
480  '@phan-var DatabaseBlock $originalBlock';
481  $this->setBlockCookie( $originalBlock, $response );
482  return;
483  }
484  }
485  } else {
486  if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
487  '@phan-var DatabaseBlock $block';
488  $this->setBlockCookie( $block, $response );
489  }
490  }
491  }
492  }
493 
504  public function setBlockCookie( DatabaseBlock $block, WebResponse $response ) {
505  // Calculate the default expiry time.
506  $maxExpiryTime = wfTimestamp( TS_MW, (int)wfTimestamp() + ( 24 * 60 * 60 ) );
507 
508  // Use the block's expiry time only if it's less than the default.
509  $expiryTime = $block->getExpiry();
510  if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
511  $expiryTime = $maxExpiryTime;
512  }
513 
514  // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
515  $expiryValue = DateTime::createFromFormat(
516  'YmdHis',
517  $expiryTime,
518  new DateTimeZone( 'UTC' )
519  )->format( 'U' );
520  $cookieOptions = [ 'httpOnly' => false ];
521  $cookieValue = $this->getCookieValue( $block );
522  $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
523  }
524 
532  private function shouldTrackBlockWithCookie( AbstractBlock $block, $isAnon ) {
533  if ( $block instanceof DatabaseBlock ) {
534  switch ( $block->getType() ) {
537  return $isAnon && $this->options->get( 'CookieSetOnIpBlock' );
539  return !$isAnon &&
540  $this->options->get( 'CookieSetOnAutoblock' ) &&
541  $block->isAutoblocking();
542  default:
543  return false;
544  }
545  }
546  return false;
547  }
548 
555  public static function clearBlockCookie( WebResponse $response ) {
556  $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
557  }
558 
569  public function getIdFromCookieValue( $cookieValue ) {
570  // The cookie value must start with a number
571  if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
572  return null;
573  }
574 
575  // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
576  $bangPos = strpos( $cookieValue, '!' );
577  $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
578  if ( !$this->options->get( 'SecretKey' ) ) {
579  // If there's no secret key, just use the ID as given.
580  return (int)$id;
581  }
582  $storedHmac = substr( $cookieValue, $bangPos + 1 );
583  $calculatedHmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
584  if ( $calculatedHmac === $storedHmac ) {
585  return (int)$id;
586  } else {
587  return null;
588  }
589  }
590 
602  public function getCookieValue( DatabaseBlock $block ) {
603  $id = $block->getId();
604  if ( !$this->options->get( 'SecretKey' ) ) {
605  // If there's no secret key, don't append a HMAC.
606  return $id;
607  }
608  $hmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
609  $cookieValue = $id . '!' . $hmac;
610  return $cookieValue;
611  }
612 
613 }
MediaWiki\Block\BlockManager\$logger
LoggerInterface $logger
Definition: BlockManager.php:53
MediaWiki\Block\BlockManager\trackBlockWithCookie
trackBlockWithCookie(User $user, WebResponse $response)
Set the 'BlockID' cookie depending on block type and user authentication status.
Definition: BlockManager.php:449
MWCryptHash\hmac
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
Definition: MWCryptHash.php:106
User\isAnon
isAnon()
Get whether the user is anonymous.
Definition: User.php:2922
MediaWiki\Block
Definition: AbstractBlock.php:21
User\isRegistered
isRegistered()
Alias of isLoggedIn() with a name that describes its actual functionality.
Definition: User.php:2906
MediaWiki\Block\BlockManager
A service class for checking blocks.
Definition: BlockManager.php:46
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1808
MediaWiki\Block\BlockManager\__construct
__construct(ServiceOptions $options, PermissionManager $permissionManager, LoggerInterface $logger, HookContainer $hookContainer)
Definition: BlockManager.php:81
MediaWiki\Block\DatabaseBlock\getType
getType()
Get the type of target for this particular block.int|null AbstractBlock::TYPE_ constant,...
Definition: DatabaseBlock.php:1110
MediaWiki\Block\BlockManager\shouldApplyCookieBlock
shouldApplyCookieBlock(DatabaseBlock $block, $isAnon)
Check if the block loaded from the cookie should be applied.
Definition: BlockManager.php:315
MediaWiki\Block\AbstractBlock\TYPE_AUTO
const TYPE_AUTO
Definition: AbstractBlock.php:91
WebResponse\setCookie
setCookie( $name, $value, $expire=0, $options=[])
Set the browser cookie.
Definition: WebResponse.php:141
User\isSafeToLoad
isSafeToLoad()
Test if it's safe to load this User object.
Definition: User.php:301
MWCryptHash
Definition: MWCryptHash.php:26
$base
$base
Definition: generateLocalAutoload.php:11
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:32
User\getRequest
getRequest()
Get the WebRequest object to use with this object.
Definition: User.php:3040
MediaWiki\Block\AbstractBlock\TYPE_RANGE
const TYPE_RANGE
Definition: AbstractBlock.php:90
MediaWiki\Block\DatabaseBlock
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
Definition: DatabaseBlock.php:52
WebResponse\clearCookie
clearCookie( $name, $options=[])
Unset a browser cookie.
Definition: WebResponse.php:255
MediaWiki\Block\DatabaseBlock\getBlocksForIPList
static getBlocksForIPList(array $ipChain, $isAnon, $fromMaster=false)
Get all blocks that match any IP from an array of IP addresses.
Definition: DatabaseBlock.php:928
MediaWiki\Config\ServiceOptions
A class for passing options to services.
Definition: ServiceOptions.php:25
MediaWiki\User\UserIdentity\isRegistered
isRegistered()
MediaWiki\Block\BlockManager\shouldTrackBlockWithCookie
shouldTrackBlockWithCookie(AbstractBlock $block, $isAnon)
Check if the block should be tracked with a cookie.
Definition: BlockManager.php:532
MediaWiki\Block\BlockManager\setBlockCookie
setBlockCookie(DatabaseBlock $block, WebResponse $response)
Set the 'BlockID' cookie to this block's ID and expiry time.
Definition: BlockManager.php:504
MediaWiki\Block\BlockManager\isLocallyBlockedProxy
isLocallyBlockedProxy( $ip)
Check if an IP address is in the local proxy list.
Definition: BlockManager.php:340
MediaWiki\Block\CompositeBlock
Multiple Block class.
Definition: CompositeBlock.php:35
MediaWiki\Block\BlockManager\getUniqueBlocks
getUniqueBlocks(array $blocks)
Given a list of blocks, return a list of unique blocks.
Definition: BlockManager.php:252
MediaWiki\Block\AbstractBlock\TYPE_IP
const TYPE_IP
Definition: AbstractBlock.php:89
MediaWiki\Block\BlockManager\inDnsBlacklist
inDnsBlacklist( $ip, array $bases)
Whether the given IP is in a given DNS blacklist.
Definition: BlockManager.php:379
WebResponse\headersSent
headersSent()
Test if headers have been sent.
Definition: WebResponse.php:116
MediaWiki\Block\BlockManager\getIdFromCookieValue
getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
Definition: BlockManager.php:569
MediaWiki\Block\AbstractBlock\getType
getType()
Get the type of target for this particular block.
Definition: AbstractBlock.php:435
MediaWiki\Block\DatabaseBlock\isExpired
isExpired()
Has the block expired?
Definition: DatabaseBlock.php:670
User\getBlock
getBlock( $fromReplica=true)
Get the block affecting the user, or null if the user is not blocked.
Definition: User.php:1795
MediaWiki\Block\DatabaseBlock\isAutoblocking
isAutoblocking( $x=null)
Definition: DatabaseBlock.php:816
MediaWiki\Block\AbstractBlock\TYPE_USER
const TYPE_USER
Definition: AbstractBlock.php:88
MediaWiki\Permissions\PermissionManager
A service class for checking permissions To obtain an instance, use MediaWikiServices::getInstance()-...
Definition: PermissionManager.php:49
MediaWiki\Block\BlockManager\getBlockFromCookieValue
getBlockFromCookieValue(UserIdentity $user, WebRequest $request)
Try to load a block from an ID given in a cookie value.
Definition: BlockManager.php:284
MediaWiki\Block\SystemBlock
System blocks are temporary blocks that are created on enforcement (e.g.
Definition: SystemBlock.php:33
MediaWiki\Block\BlockManager\$options
ServiceOptions $options
Definition: BlockManager.php:51
MediaWiki\Block\BlockManager\clearBlockCookie
static clearBlockCookie(WebResponse $response)
Unset the 'BlockID' cookie.
Definition: BlockManager.php:555
MediaWiki\Block\BlockManager\$permissionManager
PermissionManager $permissionManager
Definition: BlockManager.php:48
MediaWiki\Block\BlockManager\getCookieBlock
getCookieBlock(&$blocks, UserIdentity $user, WebRequest $request)
Get the cookie block, if there is one.
Definition: BlockManager.php:182
MediaWiki\Block\AbstractBlock\getExpiry
getExpiry()
Get the block expiry time.
Definition: AbstractBlock.php:469
WebRequest\getCookie
getCookie( $key, $prefix=null, $default=null)
Get a cookie from the $_COOKIE jar.
Definition: WebRequest.php:859
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:42
MediaWiki\Block\BlockManager\getUserBlock
getUserBlock(User $user, $request, $fromReplica)
Get the blocks that apply to a user.
Definition: BlockManager.php:124
WebRequest\getIP
getIP()
Work out the IP address based on various globals For trusted proxies, use the XFF client IP (first of...
Definition: WebRequest.php:1287
MediaWiki\Block\DatabaseBlock\getId
getId()
Get the block ID.int|null
Definition: DatabaseBlock.php:755
MediaWiki\Block\BlockManager\getCookieValue
getCookieValue(DatabaseBlock $block)
Get the BlockID cookie's value for this block.
Definition: BlockManager.php:602
MediaWiki\Block\BlockManager\isDnsBlacklisted
isDnsBlacklisted( $ip, $checkWhitelist=false)
Whether the given IP is in a DNS blacklist.
Definition: BlockManager.php:362
WebRequest\getHeader
getHeader( $name, $flags=0)
Get a request header, or false if it isn't set.
Definition: WebRequest.php:1146
Message
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:161
MediaWiki\Block\BlockManager\$hookRunner
HookRunner $hookRunner
Definition: BlockManager.php:73
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:44
MediaWiki\Block\AbstractBlock
Definition: AbstractBlock.php:38
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:569
MediaWiki\Block\BlockManager\checkHost
checkHost( $hostname)
Wrapper for mocking in tests.
Definition: BlockManager.php:426
WebResponse
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:30
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:55
MediaWiki\Block\DatabaseBlock\newListFromTarget
static newListFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
This is similar to DatabaseBlock::newFromTarget, but it returns all the relevant blocks.
Definition: DatabaseBlock.php:895
MediaWiki\Block\BlockManager\getAdditionalIpBlocks
getAdditionalIpBlocks(&$blocks, WebRequest $request, $isAnon, $fromMaster)
Check for any additional blocks against the IP address or any IPs in the XFF header.
Definition: BlockManager.php:198
MediaWiki\Config\ServiceOptions\assertRequiredOptions
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
Definition: ServiceOptions.php:62
MediaWiki\Block\DatabaseBlock\newFromID
static newFromID( $id)
Load a block from the block id.
Definition: DatabaseBlock.php:158