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