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