Services: Convert BlockManager's static to a const now HHVM is gone
[lhc/web/wiklou.git] / includes / block / BlockManager.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Block;
22
23 use DateTime;
24 use DateTimeZone;
25 use DeferredUpdates;
26 use Hooks;
27 use IP;
28 use MediaWiki\Config\ServiceOptions;
29 use MediaWiki\Permissions\PermissionManager;
30 use MediaWiki\User\UserIdentity;
31 use MWCryptHash;
32 use Psr\Log\LoggerInterface;
33 use User;
34 use WebRequest;
35 use WebResponse;
36 use Wikimedia\IPSet;
37
38 /**
39 * A service class for checking blocks.
40 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
41 *
42 * @since 1.34 Refactored from User and Block.
43 */
44 class BlockManager {
45 /** @var PermissionManager */
46 private $permissionManager;
47
48 /** @var ServiceOptions */
49 private $options;
50
51 /**
52 * @var array
53 * @since 1.34
54 */
55 public const CONSTRUCTOR_OPTIONS = [
56 'ApplyIpBlocksToXff',
57 'CookieSetOnAutoblock',
58 'CookieSetOnIpBlock',
59 'DnsBlacklistUrls',
60 'EnableDnsBlacklist',
61 'ProxyList',
62 'ProxyWhitelist',
63 'SecretKey',
64 'SoftBlockRanges',
65 ];
66
67 /** @var LoggerInterface */
68 private $logger;
69
70 /**
71 * @param ServiceOptions $options
72 * @param PermissionManager $permissionManager
73 * @param LoggerInterface $logger
74 */
75 public function __construct(
76 ServiceOptions $options,
77 PermissionManager $permissionManager,
78 LoggerInterface $logger
79 ) {
80 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
81 $this->options = $options;
82 $this->permissionManager = $permissionManager;
83 $this->logger = $logger;
84 }
85
86 /**
87 * Get the blocks that apply to a user. If there is only one, return that, otherwise
88 * return a composite block that combines the strictest features of the applicable
89 * blocks.
90 *
91 * Different blocks may be sought, depending on the user and their permissions. The
92 * user may be:
93 * (1) The global user (and can be affected by IP blocks). The global request object
94 * is needed for checking the IP address, the XFF header and the cookies.
95 * (2) The global user (and exempt from IP blocks). The global request object is
96 * needed for checking the cookies.
97 * (3) Another user (not the global user). No request object is available or needed;
98 * just look for a block against the user account.
99 *
100 * Cases #1 and #2 check whether the global user is blocked in practice; the block
101 * may due to their user account being blocked or to an IP address block or cookie
102 * block (or multiple of these). Case #3 simply checks whether a user's account is
103 * blocked, and does not determine whether the person using that account is affected
104 * in practice by any IP address or cookie blocks.
105 *
106 * @internal This should only be called by User::getBlockedStatus
107 * @param User $user
108 * @param WebRequest|null $request The global request object if the user is the
109 * global user (cases #1 and #2), otherwise null (case #3). The IP address and
110 * information from the request header are needed to find some types of blocks.
111 * @param bool $fromReplica Whether to check the replica DB first.
112 * To improve performance, non-critical checks are done against replica DBs.
113 * Check when actually saving should be done against master.
114 * @return AbstractBlock|null The most relevant block, or null if there is no block.
115 */
116 public function getUserBlock( User $user, $request, $fromReplica ) {
117 $fromMaster = !$fromReplica;
118 $ip = null;
119
120 // If this is the global user, they may be affected by IP blocks (case #1),
121 // or they may be exempt (case #2). If affected, look for additional blocks
122 // against the IP address.
123 $checkIpBlocks = $request &&
124 !$this->permissionManager->userHasRight( $user, 'ipblock-exempt' );
125
126 if ( $request && $checkIpBlocks ) {
127
128 // Case #1: checking the global user, including IP blocks
129 $ip = $request->getIP();
130 // TODO: remove dependency on DatabaseBlock (T221075)
131 $blocks = DatabaseBlock::newListFromTarget( $user, $ip, $fromMaster );
132 $this->getAdditionalIpBlocks( $blocks, $request, !$user->isRegistered(), $fromMaster );
133 $this->getCookieBlock( $blocks, $user, $request );
134
135 } elseif ( $request ) {
136
137 // Case #2: checking the global user, but they are exempt from IP blocks
138 // TODO: remove dependency on DatabaseBlock (T221075)
139 $blocks = DatabaseBlock::newListFromTarget( $user, null, $fromMaster );
140 $this->getCookieBlock( $blocks, $user, $request );
141
142 } else {
143
144 // Case #3: checking whether a user's account is blocked
145 // TODO: remove dependency on DatabaseBlock (T221075)
146 $blocks = DatabaseBlock::newListFromTarget( $user, null, $fromMaster );
147
148 }
149
150 // Filter out any duplicated blocks, e.g. from the cookie
151 $blocks = $this->getUniqueBlocks( $blocks );
152
153 $block = null;
154 if ( count( $blocks ) > 0 ) {
155 if ( count( $blocks ) === 1 ) {
156 $block = $blocks[ 0 ];
157 } else {
158 $block = new CompositeBlock( [
159 'address' => $ip,
160 'byText' => 'MediaWiki default',
161 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
162 'originalBlocks' => $blocks,
163 ] );
164 }
165 }
166
167 Hooks::run( 'GetUserBlock', [ clone $user, $ip, &$block ] );
168
169 return $block;
170 }
171
172 /**
173 * Get the cookie block, if there is one.
174 *
175 * @param AbstractBlock[] &$blocks
176 * @param UserIdentity $user
177 * @param WebRequest $request
178 * @return void
179 */
180 private function getCookieBlock( &$blocks, UserIdentity $user, WebRequest $request ) {
181 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
182 if ( $cookieBlock instanceof DatabaseBlock ) {
183 $blocks[] = $cookieBlock;
184 }
185 }
186
187 /**
188 * Check for any additional blocks against the IP address or any IPs in the XFF header.
189 *
190 * @param AbstractBlock[] &$blocks Blocks found so far
191 * @param WebRequest $request
192 * @param bool $isAnon The user is logged out
193 * @param bool $fromMaster
194 * @return void
195 */
196 private function getAdditionalIpBlocks( &$blocks, WebRequest $request, $isAnon, $fromMaster ) {
197 $ip = $request->getIP();
198
199 // Proxy blocking
200 if ( !in_array( $ip, $this->options->get( 'ProxyWhitelist' ) ) ) {
201 // Local list
202 if ( $this->isLocallyBlockedProxy( $ip ) ) {
203 $blocks[] = new SystemBlock( [
204 'byText' => wfMessage( 'proxyblocker' )->text(),
205 'reason' => wfMessage( 'proxyblockreason' )->plain(),
206 'address' => $ip,
207 'systemBlock' => 'proxy',
208 ] );
209 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
210 $blocks[] = new SystemBlock( [
211 'byText' => wfMessage( 'sorbs' )->text(),
212 'reason' => wfMessage( 'sorbsreason' )->plain(),
213 'address' => $ip,
214 'systemBlock' => 'dnsbl',
215 ] );
216 }
217 }
218
219 // Soft blocking
220 if ( $isAnon && IP::isInRanges( $ip, $this->options->get( 'SoftBlockRanges' ) ) ) {
221 $blocks[] = new SystemBlock( [
222 'address' => $ip,
223 'byText' => 'MediaWiki default',
224 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
225 'anonOnly' => true,
226 'systemBlock' => 'wgSoftBlockRanges',
227 ] );
228 }
229
230 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
231 if ( $this->options->get( 'ApplyIpBlocksToXff' )
232 && !in_array( $ip, $this->options->get( 'ProxyWhitelist' ) )
233 ) {
234 $xff = $request->getHeader( 'X-Forwarded-For' );
235 $xff = array_map( 'trim', explode( ',', $xff ) );
236 $xff = array_diff( $xff, [ $ip ] );
237 // TODO: remove dependency on DatabaseBlock (T221075)
238 $xffblocks = DatabaseBlock::getBlocksForIPList( $xff, $isAnon, $fromMaster );
239 $blocks = array_merge( $blocks, $xffblocks );
240 }
241 }
242
243 /**
244 * Given a list of blocks, return a list of unique blocks.
245 *
246 * This usually means that each block has a unique ID. For a block with ID null,
247 * if it's an autoblock, it will be filtered out if the parent block is present;
248 * if not, it is assumed to be a unique system block, and kept.
249 *
250 * @param AbstractBlock[] $blocks
251 * @return AbstractBlock[]
252 */
253 private function getUniqueBlocks( array $blocks ) {
254 $systemBlocks = [];
255 $databaseBlocks = [];
256
257 foreach ( $blocks as $block ) {
258 if ( $block instanceof SystemBlock ) {
259 $systemBlocks[] = $block;
260 } elseif ( $block->getType() === DatabaseBlock::TYPE_AUTO ) {
261 /** @var DatabaseBlock $block */
262 '@phan-var DatabaseBlock $block';
263 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
264 $databaseBlocks[$block->getParentBlockId()] = $block;
265 }
266 } else {
267 $databaseBlocks[$block->getId()] = $block;
268 }
269 }
270
271 return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
272 }
273
274 /**
275 * Try to load a block from an ID given in a cookie value. If the block is invalid
276 * doesn't exist, or the cookie value is malformed, remove the cookie.
277 *
278 * @param UserIdentity $user
279 * @param WebRequest $request
280 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
281 */
282 private function getBlockFromCookieValue(
283 UserIdentity $user,
284 WebRequest $request
285 ) {
286 $cookieValue = $request->getCookie( 'BlockID' );
287 if ( is_null( $cookieValue ) ) {
288 return false;
289 }
290
291 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
292 if ( !is_null( $blockCookieId ) ) {
293 // TODO: remove dependency on DatabaseBlock (T221075)
294 $block = DatabaseBlock::newFromID( $blockCookieId );
295 if (
296 $block instanceof DatabaseBlock &&
297 $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
298 ) {
299 return $block;
300 }
301 }
302
303 $this->clearBlockCookie( $request->response() );
304
305 return false;
306 }
307
308 /**
309 * Check if the block loaded from the cookie should be applied.
310 *
311 * @param DatabaseBlock $block
312 * @param bool $isAnon The user is logged out
313 * @return bool The block sould be applied
314 */
315 private function shouldApplyCookieBlock( DatabaseBlock $block, $isAnon ) {
316 if ( !$block->isExpired() ) {
317 switch ( $block->getType() ) {
318 case DatabaseBlock::TYPE_IP:
319 case DatabaseBlock::TYPE_RANGE:
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' );
324 case DatabaseBlock::TYPE_USER:
325 return $block->isAutoblocking() &&
326 $this->options->get( 'CookieSetOnAutoblock' );
327 default:
328 return false;
329 }
330 }
331 return false;
332 }
333
334 /**
335 * Check if an IP address is in the local proxy list
336 *
337 * @param string $ip
338 * @return bool
339 */
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
355 /**
356 * Whether the given IP is in a DNS blacklist.
357 *
358 * @param string $ip IP to check
359 * @param bool $checkWhitelist Whether to check the whitelist first
360 * @return bool True if blacklisted.
361 */
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
372 /**
373 * Whether the given IP is in a given DNS blacklist.
374 *
375 * @param string $ip IP to check
376 * @param array $bases Array of Strings: URL of the DNS blacklist
377 * @return bool True if blacklisted.
378 */
379 private function inDnsBlacklist( $ip, array $bases ) {
380 $found = false;
381 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
382 if ( IP::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
420 /**
421 * Wrapper for mocking in tests.
422 *
423 * @param string $hostname DNSBL query
424 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
425 */
426 protected function checkHost( $hostname ) {
427 return gethostbynamel( $hostname );
428 }
429
430 /**
431 * Set the 'BlockID' cookie depending on block type and user authentication status.
432 *
433 * @since 1.34
434 * @param User $user
435 */
436 public function trackBlockWithCookie( User $user ) {
437 $request = $user->getRequest();
438 if ( $request->getCookie( 'BlockID' ) !== null ) {
439 // User already has a block cookie
440 return;
441 }
442
443 // Defer checks until the user has been fully loaded to avoid circular dependency
444 // of User on itself (T180050 and T226777)
445 DeferredUpdates::addCallableUpdate(
446 function () use ( $user, $request ) {
447 $block = $user->getBlock();
448 $response = $request->response();
449 $isAnon = $user->isAnon();
450
451 if ( $block ) {
452 if ( $block instanceof CompositeBlock ) {
453 // TODO: Improve on simply tracking the first trackable block (T225654)
454 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
455 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
456 '@phan-var DatabaseBlock $originalBlock';
457 $this->setBlockCookie( $originalBlock, $response );
458 return;
459 }
460 }
461 } else {
462 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
463 '@phan-var DatabaseBlock $block';
464 $this->setBlockCookie( $block, $response );
465 }
466 }
467 }
468 },
469 DeferredUpdates::PRESEND
470 );
471 }
472
473 /**
474 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
475 * the same as the block's, to a maximum of 24 hours.
476 *
477 * @since 1.34
478 * @internal Should be private.
479 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
480 * @param DatabaseBlock $block
481 * @param WebResponse $response The response on which to set the cookie.
482 */
483 public function setBlockCookie( DatabaseBlock $block, WebResponse $response ) {
484 // Calculate the default expiry time.
485 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
486
487 // Use the block's expiry time only if it's less than the default.
488 $expiryTime = $block->getExpiry();
489 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
490 $expiryTime = $maxExpiryTime;
491 }
492
493 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
494 $expiryValue = DateTime::createFromFormat(
495 'YmdHis',
496 $expiryTime,
497 new DateTimeZone( 'UTC' )
498 )->format( 'U' );
499 $cookieOptions = [ 'httpOnly' => false ];
500 $cookieValue = $this->getCookieValue( $block );
501 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
502 }
503
504 /**
505 * Check if the block should be tracked with a cookie.
506 *
507 * @param AbstractBlock $block
508 * @param bool $isAnon The user is logged out
509 * @return bool The block sould be tracked with a cookie
510 */
511 private function shouldTrackBlockWithCookie( AbstractBlock $block, $isAnon ) {
512 if ( $block instanceof DatabaseBlock ) {
513 switch ( $block->getType() ) {
514 case DatabaseBlock::TYPE_IP:
515 case DatabaseBlock::TYPE_RANGE:
516 return $isAnon && $this->options->get( 'CookieSetOnIpBlock' );
517 case DatabaseBlock::TYPE_USER:
518 return !$isAnon &&
519 $this->options->get( 'CookieSetOnAutoblock' ) &&
520 $block->isAutoblocking();
521 default:
522 return false;
523 }
524 }
525 return false;
526 }
527
528 /**
529 * Unset the 'BlockID' cookie.
530 *
531 * @since 1.34
532 * @param WebResponse $response
533 */
534 public static function clearBlockCookie( WebResponse $response ) {
535 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
536 }
537
538 /**
539 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
540 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
541 *
542 * @since 1.34
543 * @internal Should be private.
544 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
545 * @param string $cookieValue The string in which to find the ID.
546 * @return int|null The block ID, or null if the HMAC is present and invalid.
547 */
548 public function getIdFromCookieValue( $cookieValue ) {
549 // The cookie value must start with a number
550 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
551 return null;
552 }
553
554 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
555 $bangPos = strpos( $cookieValue, '!' );
556 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
557 if ( !$this->options->get( 'SecretKey' ) ) {
558 // If there's no secret key, just use the ID as given.
559 return $id;
560 }
561 $storedHmac = substr( $cookieValue, $bangPos + 1 );
562 $calculatedHmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
563 if ( $calculatedHmac === $storedHmac ) {
564 return $id;
565 } else {
566 return null;
567 }
568 }
569
570 /**
571 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
572 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
573 * be the block ID.
574 *
575 * @since 1.34
576 * @internal Should be private.
577 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
578 * @param DatabaseBlock $block
579 * @return string The block ID, probably concatenated with "!" and the HMAC.
580 */
581 public function getCookieValue( DatabaseBlock $block ) {
582 $id = $block->getId();
583 if ( !$this->options->get( 'SecretKey' ) ) {
584 // If there's no secret key, don't append a HMAC.
585 return $id;
586 }
587 $hmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
588 $cookieValue = $id . '!' . $hmac;
589 return $cookieValue;
590 }
591
592 }