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