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