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