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