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