f92dd1e2867152818b4f1e0772a8717b1f63ff46
[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 * doesn't exist, or the cookie value is malformed, 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 $cookieValue = $request->getCookie( 'BlockID' );
238 if ( is_null( $cookieValue ) ) {
239 return false;
240 }
241
242 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
243 if ( !is_null( $blockCookieId ) ) {
244 // TODO: remove dependency on DatabaseBlock
245 $block = DatabaseBlock::newFromID( $blockCookieId );
246 if (
247 $block instanceof DatabaseBlock &&
248 $this->shouldApplyCookieBlock( $block, $user->isAnon() )
249 ) {
250 return $block;
251 }
252 }
253
254 $this->clearBlockCookie( $request->response() );
255
256 return false;
257 }
258
259 /**
260 * Check if the block loaded from the cookie should be applied.
261 *
262 * @param DatabaseBlock $block
263 * @param bool $isAnon The user is logged out
264 * @return bool The block sould be applied
265 */
266 private function shouldApplyCookieBlock( DatabaseBlock $block, $isAnon ) {
267 if ( !$block->isExpired() ) {
268 switch ( $block->getType() ) {
269 case DatabaseBlock::TYPE_IP:
270 case DatabaseBlock::TYPE_RANGE:
271 // If block is type IP or IP range, load only
272 // if user is not logged in (T152462)
273 return $isAnon &&
274 $this->options->get( 'CookieSetOnIpBlock' );
275 case DatabaseBlock::TYPE_USER:
276 return $block->isAutoblocking() &&
277 $this->options->get( 'CookieSetOnAutoblock' );
278 default:
279 return false;
280 }
281 }
282 return false;
283 }
284
285 /**
286 * Check if an IP address is in the local proxy list
287 *
288 * @param string $ip
289 * @return bool
290 */
291 private function isLocallyBlockedProxy( $ip ) {
292 $proxyList = $this->options->get( 'ProxyList' );
293 if ( !$proxyList ) {
294 return false;
295 }
296
297 if ( !is_array( $proxyList ) ) {
298 // Load values from the specified file
299 $proxyList = array_map( 'trim', file( $proxyList ) );
300 }
301
302 $proxyListIPSet = new IPSet( $proxyList );
303 return $proxyListIPSet->match( $ip );
304 }
305
306 /**
307 * Whether the given IP is in a DNS blacklist.
308 *
309 * @param string $ip IP to check
310 * @param bool $checkWhitelist Whether to check the whitelist first
311 * @return bool True if blacklisted.
312 */
313 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
314 if ( !$this->options->get( 'EnableDnsBlacklist' ) ||
315 ( $checkWhitelist && in_array( $ip, $this->options->get( 'ProxyWhitelist' ) ) )
316 ) {
317 return false;
318 }
319
320 return $this->inDnsBlacklist( $ip, $this->options->get( 'DnsBlacklistUrls' ) );
321 }
322
323 /**
324 * Whether the given IP is in a given DNS blacklist.
325 *
326 * @param string $ip IP to check
327 * @param array $bases Array of Strings: URL of the DNS blacklist
328 * @return bool True if blacklisted.
329 */
330 private function inDnsBlacklist( $ip, array $bases ) {
331 $found = false;
332 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
333 if ( IP::isIPv4( $ip ) ) {
334 // Reverse IP, T23255
335 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
336
337 foreach ( $bases as $base ) {
338 // Make hostname
339 // If we have an access key, use that too (ProjectHoneypot, etc.)
340 $basename = $base;
341 if ( is_array( $base ) ) {
342 if ( count( $base ) >= 2 ) {
343 // Access key is 1, base URL is 0
344 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
345 } else {
346 $hostname = "$ipReversed.{$base[0]}";
347 }
348 $basename = $base[0];
349 } else {
350 $hostname = "$ipReversed.$base";
351 }
352
353 // Send query
354 $ipList = $this->checkHost( $hostname );
355
356 if ( $ipList ) {
357 wfDebugLog(
358 'dnsblacklist',
359 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
360 );
361 $found = true;
362 break;
363 }
364
365 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
366 }
367 }
368
369 return $found;
370 }
371
372 /**
373 * Wrapper for mocking in tests.
374 *
375 * @param string $hostname DNSBL query
376 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
377 */
378 protected function checkHost( $hostname ) {
379 return gethostbynamel( $hostname );
380 }
381
382 /**
383 * Set the 'BlockID' cookie depending on block type and user authentication status.
384 *
385 * @since 1.34
386 * @param User $user
387 */
388 public function trackBlockWithCookie( User $user ) {
389 $request = $user->getRequest();
390 if ( $request->getCookie( 'BlockID' ) !== null ) {
391 // User already has a block cookie
392 return;
393 }
394
395 // Defer checks until the user has been fully loaded to avoid circular dependency
396 // of User on itself (T180050 and T226777)
397 DeferredUpdates::addCallableUpdate(
398 function () use ( $user, $request ) {
399 $block = $user->getBlock();
400 $response = $request->response();
401 $isAnon = $user->isAnon();
402
403 if ( $block ) {
404 if ( $block instanceof CompositeBlock ) {
405 // TODO: Improve on simply tracking the first trackable block (T225654)
406 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
407 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
408 $this->setBlockCookie( $originalBlock, $response );
409 return;
410 }
411 }
412 } else {
413 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
414 $this->setBlockCookie( $block, $response );
415 }
416 }
417 }
418 },
419 DeferredUpdates::PRESEND
420 );
421 }
422
423 /**
424 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
425 * the same as the block's, to a maximum of 24 hours.
426 *
427 * @since 1.34
428 * @internal Should be private.
429 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
430 * @param DatabaseBlock $block
431 * @param WebResponse $response The response on which to set the cookie.
432 */
433 public function setBlockCookie( DatabaseBlock $block, WebResponse $response ) {
434 // Calculate the default expiry time.
435 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
436
437 // Use the block's expiry time only if it's less than the default.
438 $expiryTime = $block->getExpiry();
439 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
440 $expiryTime = $maxExpiryTime;
441 }
442
443 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
444 $expiryValue = DateTime::createFromFormat(
445 'YmdHis',
446 $expiryTime,
447 new DateTimeZone( 'UTC' )
448 )->format( 'U' );
449 $cookieOptions = [ 'httpOnly' => false ];
450 $cookieValue = $this->getCookieValue( $block );
451 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
452 }
453
454 /**
455 * Check if the block should be tracked with a cookie.
456 *
457 * @param AbstractBlock $block
458 * @param bool $isAnon The user is logged out
459 * @return bool The block sould be tracked with a cookie
460 */
461 private function shouldTrackBlockWithCookie( AbstractBlock $block, $isAnon ) {
462 if ( $block instanceof DatabaseBlock ) {
463 switch ( $block->getType() ) {
464 case DatabaseBlock::TYPE_IP:
465 case DatabaseBlock::TYPE_RANGE:
466 return $isAnon && $this->options->get( 'CookieSetOnIpBlock' );
467 case DatabaseBlock::TYPE_USER:
468 return !$isAnon &&
469 $this->options->get( 'CookieSetOnAutoblock' ) &&
470 $block->isAutoblocking();
471 default:
472 return false;
473 }
474 }
475 return false;
476 }
477
478 /**
479 * Unset the 'BlockID' cookie.
480 *
481 * @since 1.34
482 * @param WebResponse $response
483 */
484 public static function clearBlockCookie( WebResponse $response ) {
485 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
486 }
487
488 /**
489 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
490 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
491 *
492 * @since 1.34
493 * @internal Should be private.
494 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
495 * @param string $cookieValue The string in which to find the ID.
496 * @return int|null The block ID, or null if the HMAC is present and invalid.
497 */
498 public function getIdFromCookieValue( $cookieValue ) {
499 // The cookie value must start with a number
500 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
501 return null;
502 }
503
504 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
505 $bangPos = strpos( $cookieValue, '!' );
506 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
507 if ( !$this->options->get( 'SecretKey' ) ) {
508 // If there's no secret key, just use the ID as given.
509 return $id;
510 }
511 $storedHmac = substr( $cookieValue, $bangPos + 1 );
512 $calculatedHmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
513 if ( $calculatedHmac === $storedHmac ) {
514 return $id;
515 } else {
516 return null;
517 }
518 }
519
520 /**
521 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
522 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
523 * be the block ID.
524 *
525 * @since 1.34
526 * @internal Should be private.
527 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
528 * @param DatabaseBlock $block
529 * @return string The block ID, probably concatenated with "!" and the HMAC.
530 */
531 public function getCookieValue( DatabaseBlock $block ) {
532 $id = $block->getId();
533 if ( !$this->options->get( 'SecretKey' ) ) {
534 // If there's no secret key, don't append a HMAC.
535 return $id;
536 }
537 $hmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
538 $cookieValue = $id . '!' . $hmac;
539 return $cookieValue;
540 }
541
542 }