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