Debian Codegraph @

includes/block/BlockManager.php

raw symbols SCIP
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 LogicException;
24 use MediaWiki\Config\ServiceOptions;
25 use MediaWiki\HookContainer\HookContainer;
26 use MediaWiki\HookContainer\HookRunner;
27 use MediaWiki\MainConfigNames;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Message\Message;
30 use MediaWiki\Request\ProxyLookup;
31 use MediaWiki\Request\WebRequest;
32 use MediaWiki\Request\WebResponse;
33 use MediaWiki\User\User;
34 use MediaWiki\User\UserFactory;
35 use MediaWiki\User\UserIdentity;
36 use MediaWiki\User\UserIdentityUtils;
37 use MWCryptHash;
38 use Psr\Log\LoggerInterface;
39 use Wikimedia\IPSet;
40 use Wikimedia\IPUtils;
41
42 /**
43 * A service class for checking blocks.
44 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
45 *
46 * @since 1.34 Refactored from User and Block.
47 */
48 class BlockManager {
49 /**
50 * @internal For use by ServiceWiring
51 */
52 public const CONSTRUCTOR_OPTIONS = [
53 MainConfigNames::ApplyIpBlocksToXff,
54 MainConfigNames::CookieSetOnAutoblock,
55 MainConfigNames::CookieSetOnIpBlock,
56 MainConfigNames::DnsBlacklistUrls,
57 MainConfigNames::EnableDnsBlacklist,
58 MainConfigNames::ProxyList,
59 MainConfigNames::ProxyWhitelist,
60 MainConfigNames::SecretKey,
61 MainConfigNames::SoftBlockRanges,
62 ];
63
64 private ServiceOptions $options;
65 private UserFactory $userFactory;
66 private UserIdentityUtils $userIdentityUtils;
67 private LoggerInterface $logger;
68 private HookRunner $hookRunner;
69 private DatabaseBlockStore $blockStore;
70 private ProxyLookup $proxyLookup;
71
72 private BlockCache $userBlockCache;
73 private BlockCache $createAccountBlockCache;
74
75 public function __construct(
76 ServiceOptions $options,
77 UserFactory $userFactory,
78 UserIdentityUtils $userIdentityUtils,
79 LoggerInterface $logger,
80 HookContainer $hookContainer,
81 DatabaseBlockStore $blockStore,
82 ProxyLookup $proxyLookup
83 ) {
84 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
85 $this->options = $options;
86 $this->userFactory = $userFactory;
87 $this->userIdentityUtils = $userIdentityUtils;
88 $this->logger = $logger;
89 $this->hookRunner = new HookRunner( $hookContainer );
90 $this->blockStore = $blockStore;
91 $this->proxyLookup = $proxyLookup;
92
93 $this->userBlockCache = new BlockCache;
94 $this->createAccountBlockCache = new BlockCache;
95 }
96
97 /**
98 * Get the blocks that apply to a user. If there is only one, return that, otherwise
99 * return a composite block that combines the strictest features of the applicable
100 * blocks.
101 *
102 * Different blocks may be sought, depending on the user and their permissions. The
103 * user may be:
104 * (1) The global user (and can be affected by IP blocks). The global request object
105 * is needed for checking the IP address, the XFF header and the cookies.
106 * (2) The global user (and exempt from IP blocks). The global request object is
107 * available.
108 * (3) Another user (not the global user). No request object is available or needed;
109 * just look for a block against the user account.
110 *
111 * Cases #1 and #2 check whether the global user is blocked in practice; the block
112 * may due to their user account being blocked or to an IP address block or cookie
113 * block (or multiple of these). Case #3 simply checks whether a user's account is
114 * blocked, and does not determine whether the person using that account is affected
115 * in practice by any IP address or cookie blocks.
116 *
117 * @deprecated since 1.42 Use getBlock(), which is the same except that it expects
118 * the caller to do ipblock-exempt permission checking and to set $request to null
119 * if the user is exempt from IP blocks.
120 *
121 * @param UserIdentity $user
122 * @param WebRequest|null $request The global request object if the user is the
123 * global user (cases #1 and #2), otherwise null (case #3). The IP address and
124 * information from the request header are needed to find some types of blocks.
125 * @param bool $fromReplica Whether to check the replica DB first.
126 * To improve performance, non-critical checks are done against replica DBs.
127 * Check when actually saving should be done against primary.
128 * @param bool $disableIpBlockExemptChecking This is used internally to prevent
129 * a infinite recursion with autopromote. See T270145.
130 * @return AbstractBlock|null The most relevant block, or null if there is no block.
131 */
132 public function getUserBlock(
133 UserIdentity $user,
134 $request,
135 $fromReplica,
136 $disableIpBlockExemptChecking = false
137 ) {
138 // If this is the global user, they may be affected by IP blocks (case #1),
139 // or they may be exempt (case #2). If affected, look for additional blocks
140 // against the IP address and referenced in a cookie.
141 $checkIpBlocks = $request &&
142 // Because calling getBlock within Autopromote leads back to here,
143 // thus causing a infinite recursion. We fix this by not checking for
144 // ipblock-exempt when calling getBlock within Autopromote.
145 // See T270145.
146 !$disableIpBlockExemptChecking &&
147 !$this->isIpBlockExempt( $user );
148
149 return $this->getBlock(
150 $user,
151 $checkIpBlocks ? $request : null,
152 $fromReplica
153 );
154 }
155
156 /**
157 * Get the blocks that apply to a user. If there is only one, return that, otherwise
158 * return a composite block that combines the strictest features of the applicable
159 * blocks.
160 *
161 * If the user is exempt from IP blocks, the request should be null.
162 *
163 * @since 1.42
164 * @param UserIdentity $user The user performing the action
165 * @param WebRequest|null $request The request to use for IP and cookie
166 * blocks, or null to skip checking for such blocks. If the user has the
167 * ipblock-exempt right, the request should be null.
168 * @param bool $fromReplica Whether to check the replica DB first.
169 * To improve performance, non-critical checks are done against replica DBs.
170 * Check when actually saving should be done against primary.
171 * @return AbstractBlock|null
172 */
173 public function getBlock(
174 UserIdentity $user,
175 ?WebRequest $request,
176 $fromReplica = true
177 ): ?AbstractBlock {
178 $fromPrimary = !$fromReplica;
179 $ip = null;
180
181 // TODO: normalise the fromPrimary parameter when replication is not configured.
182 // Maybe DatabaseBlockStore can tell us about the LoadBalancer configuration.
183 $cacheKey = new BlockCacheKey(
184 $request,
185 $user,
186 $fromPrimary
187 );
188 $block = $this->userBlockCache->get( $cacheKey );
189 if ( $block !== null ) {
190 $this->logger->debug( "Block cache hit with key {$cacheKey}" );
191 return $block ?: null;
192 }
193 $this->logger->debug( "Block cache miss with key {$cacheKey}" );
194
195 if ( $request ) {
196
197 // Case #1: checking the global user, including IP blocks
198 $ip = $request->getIP();
199 // For soft blocks, i.e. blocks that don't block logged-in users,
200 // temporary users are treated as anon users, and are blocked.
201 $applySoftBlocks = !$this->userIdentityUtils->isNamed( $user );
202
203 $xff = $request->getHeader( 'X-Forwarded-For' );
204
205 $blocks = array_merge(
206 $this->blockStore->newListFromTarget( $user, $ip, $fromPrimary ),
207 $this->getSystemIpBlocks( $ip, $applySoftBlocks ),
208 $this->getXffBlocks( $ip, $xff, $applySoftBlocks, $fromPrimary ),
209 $this->getCookieBlock( $user, $request )
210 );
211 } else {
212
213 // Case #2: checking the global user, but they are exempt from IP blocks
214 // and cookie blocks, so we only check for a user account block.
215 // Case #3: checking whether another user's account is blocked.
216 $blocks = $this->blockStore->newListFromTarget( $user, null, $fromPrimary );
217
218 }
219
220 $block = $this->createGetBlockResult( $ip, $blocks );
221
222 $legacyUser = $this->userFactory->newFromUserIdentity( $user );
223 $this->hookRunner->onGetUserBlock( clone $legacyUser, $ip, $block );
224
225 $this->userBlockCache->set( $cacheKey, $block ?: false );
226 return $block;
227 }
228
229 /**
230 * Clear the cache of any blocks that refer to the specified user
231 *
232 * @param UserIdentity $user
233 */
234 public function clearUserCache( UserIdentity $user ) {
235 $this->userBlockCache->clearUser( $user );
236 $this->createAccountBlockCache->clearUser( $user );
237 }
238
239 /**
240 * Get the block which applies to a create account action, if there is any
241 *
242 * @since 1.42
243 * @param UserIdentity $user
244 * @param WebRequest|null $request The request, or null to omit IP address
245 * and cookie blocks. If the user has the ipblock-exempt right, null
246 * should be passed.
247 * @param bool $fromReplica
248 * @return AbstractBlock|null
249 */
250 public function getCreateAccountBlock(
251 UserIdentity $user,
252 ?WebRequest $request,
253 $fromReplica
254 ) {
255 $key = new BlockCacheKey( $request, $user, $fromReplica );
256 $cachedBlock = $this->createAccountBlockCache->get( $key );
257 if ( $cachedBlock !== null ) {
258 $this->logger->debug( "Create account block cache hit with key {$key}" );
259 return $cachedBlock ?: null;
260 }
261 $this->logger->debug( "Create account block cache miss with key {$key}" );
262
263 $applicableBlocks = [];
264 $userBlock = $this->getBlock( $user, $request, $fromReplica );
265 if ( $userBlock ) {
266 $applicableBlocks = $userBlock->toArray();
267 }
268
269 // T15611: if the IP address the user is trying to create an account from is
270 // blocked with createaccount disabled, prevent new account creation there even
271 // when the user is logged in
272 if ( $request ) {
273 $ipBlock = $this->blockStore->newFromTarget(
274 null, $request->getIP()
275 );
276 if ( $ipBlock ) {
277 $applicableBlocks = array_merge( $applicableBlocks, $ipBlock->toArray() );
278 }
279 }
280
281 foreach ( $applicableBlocks as $i => $block ) {
282 if ( !$block->appliesToRight( 'createaccount' ) ) {
283 unset( $applicableBlocks[$i] );
284 }
285 }
286 $result = $this->createGetBlockResult(
287 $request ? $request->getIP() : null,
288 $applicableBlocks
289 );
290 $this->createAccountBlockCache->set( $key, $result ?: false );
291 return $result;
292 }
293
294 /**
295 * Remove elements of a block which fail a callback test.
296 *
297 * @since 1.42
298 * @param Block|null $block The block, or null to pass in zero blocks.
299 * @param callable $callback The callback, which will be called once for
300 * each non-composite component of the block. The only parameter is the
301 * non-composite Block. It should return true, to keep that component,
302 * or false, to remove that component.
303 * @return Block|null
304 * - If there are zero remaining elements, null will be returned.
305 * - If there is one remaining element, a DatabaseBlock or some other
306 * non-composite block will be returned.
307 * - If there is more than one remaining element, a CompositeBlock will
308 * be returned.
309 */
310 public function filter( ?Block $block, $callback ) {
311 if ( !$block ) {
312 return null;
313 } elseif ( $block instanceof CompositeBlock ) {
314 $blocks = $block->getOriginalBlocks();
315 $originalCount = count( $blocks );
316 foreach ( $blocks as $i => $originalBlock ) {
317 if ( !$callback( $originalBlock ) ) {
318 unset( $blocks[$i] );
319 }
320 }
321 if ( !$blocks ) {
322 return null;
323 } elseif ( count( $blocks ) === 1 ) {
324 return $blocks[ array_key_first( $blocks ) ];
325 } elseif ( count( $blocks ) === $originalCount ) {
326 return $block;
327 } else {
328 return $block->withOriginalBlocks( array_values( $blocks ) );
329 }
330 } elseif ( !$callback( $block ) ) {
331 return null;
332 } else {
333 return $block;
334 }
335 }
336
337 /**
338 * Determine if a user is exempt from IP blocks
339 * @param UserIdentity $user
340 * @return bool
341 */
342 private function isIpBlockExempt( UserIdentity $user ) {
343 return MediaWikiServices::getInstance()->getPermissionManager()
344 ->userHasRight( $user, 'ipblock-exempt' );
345 }
346
347 /**
348 * @param string|null $ip
349 * @param AbstractBlock[] $blocks
350 * @return AbstractBlock|null
351 */
352 private function createGetBlockResult( ?string $ip, array $blocks ): ?AbstractBlock {
353 // Filter out any duplicated blocks, e.g. from the cookie
354 $blocks = $this->getUniqueBlocks( $blocks );
355
356 if ( count( $blocks ) === 0 ) {
357 return null;
358 } elseif ( count( $blocks ) === 1 ) {
359 return $blocks[ 0 ];
360 } else {
361 $compositeBlock = CompositeBlock::createFromBlocks( ...$blocks );
362 $compositeBlock->setTarget( $ip );
363 return $compositeBlock;
364 }
365 }
366
367 /**
368 * Get the blocks that apply to an IP address. If there is only one, return that, otherwise
369 * return a composite block that combines the strictest features of the applicable blocks.
370 *
371 * @since 1.38
372 * @param string $ip
373 * @param bool $fromReplica
374 * @return AbstractBlock|null
375 */
376 public function getIpBlock( string $ip, bool $fromReplica ): ?AbstractBlock {
377 if ( !IPUtils::isValid( $ip ) ) {
378 return null;
379 }
380
381 $blocks = array_merge(
382 $this->blockStore->newListFromTarget( $ip, $ip, !$fromReplica ),
383 $this->getSystemIpBlocks( $ip, true )
384 );
385
386 return $this->createGetBlockResult( $ip, $blocks );
387 }
388
389 /**
390 * Get the cookie block, if there is one.
391 *
392 * @param UserIdentity $user
393 * @param WebRequest $request
394 * @return AbstractBlock[]
395 */
396 private function getCookieBlock( UserIdentity $user, WebRequest $request ): array {
397 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
398
399 return $cookieBlock instanceof DatabaseBlock ? [ $cookieBlock ] : [];
400 }
401
402 /**
403 * Get any system blocks against the IP address.
404 *
405 * @param string $ip
406 * @param bool $applySoftBlocks
407 * @return AbstractBlock[]
408 */
409 private function getSystemIpBlocks( string $ip, bool $applySoftBlocks ): array {
410 $blocks = [];
411
412 // Proxy blocking
413 if ( !in_array( $ip, $this->options->get( MainConfigNames::ProxyWhitelist ) ) ) {
414 // Local list
415 if ( $this->isLocallyBlockedProxy( $ip ) ) {
416 $blocks[] = new SystemBlock( [
417 'reason' => new Message( 'proxyblockreason' ),
418 'address' => $ip,
419 'systemBlock' => 'proxy',
420 ] );
421 } elseif ( $applySoftBlocks && $this->isDnsBlacklisted( $ip ) ) {
422 $blocks[] = new SystemBlock( [
423 'reason' => new Message( 'sorbsreason' ),
424 'address' => $ip,
425 'anonOnly' => true,
426 'systemBlock' => 'dnsbl',
427 ] );
428 }
429 }
430
431 // Soft blocking
432 if ( $applySoftBlocks && IPUtils::isInRanges( $ip, $this->options->get( MainConfigNames::SoftBlockRanges ) ) ) {
433 $blocks[] = new SystemBlock( [
434 'address' => $ip,
435 'reason' => new Message( 'softblockrangesreason', [ $ip ] ),
436 'anonOnly' => true,
437 'systemBlock' => 'wgSoftBlockRanges',
438 ] );
439 }
440
441 return $blocks;
442 }
443
444 /**
445 * If `$wgApplyIpBlocksToXff` is truthy and the IP that the user is accessing the wiki from is not in
446 * `$wgProxyWhitelist`, then get the blocks that apply to the IP(s) in the X-Forwarded-For HTTP
447 * header.
448 *
449 * @param string $ip
450 * @param string $xff
451 * @param bool $applySoftBlocks
452 * @param bool $fromPrimary
453 * @return AbstractBlock[]
454 */
455 private function getXffBlocks(
456 string $ip,
457 string $xff,
458 bool $applySoftBlocks,
459 bool $fromPrimary
460 ): array {
461 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
462 if ( $this->options->get( MainConfigNames::ApplyIpBlocksToXff )
463 && !in_array( $ip, $this->options->get( MainConfigNames::ProxyWhitelist ) )
464 ) {
465 $xff = array_map( 'trim', explode( ',', $xff ) );
466 $xff = array_diff( $xff, [ $ip ] );
467 $xffblocks = $this->getBlocksForIPList( $xff, $applySoftBlocks, $fromPrimary );
468
469 // (T285159) Exclude autoblocks from XFF headers to prevent spoofed
470 // headers uncovering the IPs of autoblocked users
471 $xffblocks = array_filter( $xffblocks, static function ( $block ) {
472 return $block->getType() !== Block::TYPE_AUTO;
473 } );
474
475 return $xffblocks;
476 }
477
478 return [];
479 }
480
481 /**
482 * Get all blocks that match any IP from an array of IP addresses
483 *
484 * @internal Public to support deprecated method in DatabaseBlock
485 *
486 * @param array $ipChain List of IPs (strings), usually retrieved from the
487 * X-Forwarded-For header of the request
488 * @param bool $applySoftBlocks Include soft blocks (anonymous-only blocks). These
489 * should only block anonymous and temporary users.
490 * @param bool $fromPrimary Whether to query the primary or replica DB
491 * @return DatabaseBlock[]
492 */
493 public function getBlocksForIPList( array $ipChain, bool $applySoftBlocks, bool $fromPrimary ) {
494 if ( $ipChain === [] ) {
495 return [];
496 }
497
498 $ips = [];
499 foreach ( array_unique( $ipChain ) as $ipaddr ) {
500 // Discard invalid IP addresses. Since XFF can be spoofed and we do not
501 // necessarily trust the header given to us, make sure that we are only
502 // checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
503 // Do not treat private IP spaces as special as it may be desirable for wikis
504 // to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
505 if ( !IPUtils::isValid( $ipaddr ) ) {
506 continue;
507 }
508 // Don't check trusted IPs (includes local CDNs which will be in every request)
509 if ( $this->proxyLookup->isTrustedProxy( $ipaddr ) ) {
510 continue;
511 }
512 $ips[] = $ipaddr;
513 }
514 return $this->blockStore->newListFromIPs( $ips, $applySoftBlocks, $fromPrimary );
515 }
516
517 /**
518 * Given a list of blocks, return a list of unique blocks.
519 *
520 * This usually means that each block has a unique ID. For a block with ID null,
521 * if it's an autoblock, it will be filtered out if the parent block is present;
522 * if not, it is assumed to be a unique system block, and kept.
523 *
524 * @param AbstractBlock[] $blocks
525 * @return AbstractBlock[]
526 */
527 private function getUniqueBlocks( array $blocks ) {
528 // Blocks without an ID are considered "system blocks" for the purpose of this function
529 $systemBlocks = [];
530 $databaseBlocks = [];
531
532 foreach ( $blocks as $block ) {
533 // Autoblocks are keyed by their parent block id, if it's specified.
534 // Otherwise, they are treated as any other block.
535 if ( $block->getType() === DatabaseBlock::TYPE_AUTO && $block instanceof DatabaseBlock ) {
536 $parentBlockId = $block->getParentBlockId();
537 if ( $parentBlockId !== null ) {
538 if ( !isset( $databaseBlocks[$parentBlockId] ) ) {
539 $databaseBlocks[$parentBlockId] = $block;
540 }
541 continue;
542 }
543 }
544
545 $blockId = $block->getId();
546 if ( $blockId !== null ) {
547 $databaseBlocks[$blockId] = $block;
548 } else {
549 $systemBlocks[] = $block;
550 }
551 }
552
553 return array_values( array_merge( $systemBlocks, $databaseBlocks ) );
554 }
555
556 /**
557 * Try to load a block from an ID given in a cookie value.
558 *
559 * If the block is invalid, doesn't exist, or the cookie value is malformed, no
560 * block will be loaded. In these cases the cookie will either (1) be replaced
561 * with a valid cookie or (2) removed, next time trackBlockWithCookie is called.
562 *
563 * @param UserIdentity $user
564 * @param WebRequest $request
565 * @return DatabaseBlock|false The block object, or false if none could be loaded.
566 */
567 private function getBlockFromCookieValue(
568 UserIdentity $user,
569 WebRequest $request
570 ) {
571 $cookieValue = $request->getCookie( 'BlockID' );
572 if ( $cookieValue === null ) {
573 return false;
574 }
575
576 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
577 if ( $blockCookieId !== null ) {
578 $block = $this->blockStore->newFromID( $blockCookieId );
579 if (
580 $block instanceof DatabaseBlock &&
581 $this->shouldApplyCookieBlock( $block, !$user->isRegistered() )
582 ) {
583 return $block;
584 }
585 }
586
587 return false;
588 }
589
590 /**
591 * Check if the block loaded from the cookie should be applied.
592 *
593 * @param DatabaseBlock $block
594 * @param bool $isAnon The user is logged out
595 * @return bool The block should be applied
596 */
597 private function shouldApplyCookieBlock( DatabaseBlock $block, $isAnon ) {
598 if ( !$block->isExpired() ) {
599 switch ( $block->getType() ) {
600 case DatabaseBlock::TYPE_IP:
601 case DatabaseBlock::TYPE_RANGE:
602 // If block is type IP or IP range, load only
603 // if user is not logged in (T152462)
604 return $isAnon &&
605 $this->options->get( MainConfigNames::CookieSetOnIpBlock );
606 case DatabaseBlock::TYPE_USER:
607 return $block->isAutoblocking() &&
608 $this->options->get( MainConfigNames::CookieSetOnAutoblock );
609 default:
610 return false;
611 }
612 }
613 return false;
614 }
615
616 /**
617 * Check if an IP address is in the local proxy list
618 *
619 * @param string $ip
620 * @return bool
621 */
622 private function isLocallyBlockedProxy( $ip ) {
623 $proxyList = $this->options->get( MainConfigNames::ProxyList );
624 if ( !$proxyList ) {
625 return false;
626 }
627
628 if ( !is_array( $proxyList ) ) {
629 // Load values from the specified file
630 $proxyList = array_map( 'trim', file( $proxyList ) );
631 }
632
633 $proxyListIPSet = new IPSet( $proxyList );
634 return $proxyListIPSet->match( $ip );
635 }
636
637 /**
638 * Whether the given IP is in a DNS blacklist.
639 *
640 * @param string $ip IP to check
641 * @param bool $checkAllowed Whether to check $wgProxyWhitelist first
642 * @return bool True if blacklisted.
643 */
644 public function isDnsBlacklisted( $ip, $checkAllowed = false ) {
645 if ( !$this->options->get( MainConfigNames::EnableDnsBlacklist ) ||
646 ( $checkAllowed && in_array( $ip, $this->options->get( MainConfigNames::ProxyWhitelist ) ) )
647 ) {
648 return false;
649 }
650
651 return $this->inDnsBlacklist( $ip, $this->options->get( MainConfigNames::DnsBlacklistUrls ) );
652 }
653
654 /**
655 * Whether the given IP is in a given DNS blacklist.
656 *
657 * @param string $ip IP to check
658 * @param string[] $bases URL of the DNS blacklist
659 * @return bool True if blacklisted.
660 */
661 private function inDnsBlacklist( $ip, array $bases ) {
662 $found = false;
663 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
664 if ( IPUtils::isIPv4( $ip ) ) {
665 // Reverse IP, T23255
666 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
667
668 foreach ( $bases as $base ) {
669 // Make hostname
670 // If we have an access key, use that too (ProjectHoneypot, etc.)
671 $basename = $base;
672 if ( is_array( $base ) ) {
673 if ( count( $base ) >= 2 ) {
674 // Access key is 1, base URL is 0
675 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
676 } else {
677 $hostname = "$ipReversed.{$base[0]}";
678 }
679 $basename = $base[0];
680 } else {
681 $hostname = "$ipReversed.$base";
682 }
683
684 // Send query
685 $ipList = $this->checkHost( $hostname );
686
687 if ( $ipList ) {
688 $this->logger->info(
689 'Hostname {hostname} is {ipList}, it\'s a proxy says {basename}!',
690 [
691 'hostname' => $hostname,
692 'ipList' => $ipList[0],
693 'basename' => $basename,
694 ]
695 );
696 $found = true;
697 break;
698 }
699
700 $this->logger->debug( "Requested $hostname, not found in $basename." );
701 }
702 }
703
704 return $found;
705 }
706
707 /**
708 * Wrapper for mocking in tests.
709 *
710 * @param string $hostname DNSBL query
711 * @return string[]|false IPv4 array, or false if the IP is not blacklisted
712 */
713 protected function checkHost( $hostname ) {
714 return gethostbynamel( $hostname );
715 }
716
717 /**
718 * Set the 'BlockID' cookie depending on block type and user authentication status.
719 *
720 * If a block cookie is already set, this will check the block that the cookie references
721 * and do the following:
722 * - If the block is a valid block that should be applied, do nothing and return early.
723 * This ensures that the cookie's expiry time is based on the time of the first page
724 * load or attempt. (See discussion on T233595.)
725 * - If the block is invalid (e.g. has expired), clear the cookie and continue to check
726 * whether there is another block that should be tracked.
727 * - If the block is a valid block, but should not be tracked by a cookie, clear the
728 * cookie and continue to check whether there is another block that should be tracked.
729 *
730 * Must be called after the User object is loaded, and before headers are sent.
731 *
732 * @since 1.34
733 * @param User $user
734 * @param WebResponse $response The response on which to set the cookie.
735 */
736 public function trackBlockWithCookie( User $user, WebResponse $response ) {
737 if ( !$this->options->get( MainConfigNames::CookieSetOnIpBlock ) &&
738 !$this->options->get( MainConfigNames::CookieSetOnAutoblock ) ) {
739 // Cookie blocks are disabled, return early to prevent executing unnecessary logic.
740 return;
741 }
742
743 $request = $user->getRequest();
744
745 if ( $request->getCookie( 'BlockID' ) !== null ) {
746 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
747 if ( $cookieBlock && $this->shouldApplyCookieBlock( $cookieBlock, $user->isAnon() ) ) {
748 return;
749 }
750 // The block pointed to by the cookie is invalid or should not be tracked.
751 $this->clearBlockCookie( $response );
752 }
753
754 if ( !$user->isSafeToLoad() ) {
755 // Prevent a circular dependency by not allowing this method to be called
756 // before or while the user is being loaded.
757 // E.g. User > BlockManager > Block > Message > getLanguage > User.
758 // See also T180050 and T226777.
759 throw new LogicException( __METHOD__ . ' requires a loaded User object' );
760 }
761 if ( $response->headersSent() ) {
762 throw new LogicException( __METHOD__ . ' must be called pre-send' );
763 }
764
765 $block = $user->getBlock();
766 $isAnon = $user->isAnon();
767
768 if ( $block ) {
769 foreach ( $block->toArray() as $originalBlock ) {
770 // TODO: Improve on simply tracking the first trackable block (T225654)
771 if ( $originalBlock instanceof DatabaseBlock
772 && $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon )
773 ) {
774 $this->setBlockCookie( $originalBlock, $response );
775 return;
776 }
777 }
778 }
779 }
780
781 /**
782 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
783 * the same as the block's, to a maximum of 24 hours.
784 *
785 * @since 1.34
786 * @param DatabaseBlock $block
787 * @param WebResponse $response The response on which to set the cookie.
788 */
789 private function setBlockCookie( DatabaseBlock $block, WebResponse $response ) {
790 // Calculate the default expiry time.
791 $maxExpiryTime = wfTimestamp( TS_MW, (int)wfTimestamp() + ( 24 * 60 * 60 ) );
792
793 // Use the block's expiry time only if it's less than the default.
794 $expiryTime = $block->getExpiry();
795 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
796 $expiryTime = $maxExpiryTime;
797 }
798
799 // Set the cookie
800 $expiryValue = (int)wfTimestamp( TS_UNIX, $expiryTime );
801 $cookieOptions = [ 'httpOnly' => false ];
802 $cookieValue = $this->getCookieValue( $block );
803 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
804 }
805
806 /**
807 * Check if the block should be tracked with a cookie.
808 *
809 * @param DatabaseBlock $block
810 * @param bool $isAnon The user is logged out
811 * @return bool The block should be tracked with a cookie
812 */
813 private function shouldTrackBlockWithCookie( DatabaseBlock $block, $isAnon ) {
814 switch ( $block->getType() ) {
815 case DatabaseBlock::TYPE_IP:
816 case DatabaseBlock::TYPE_RANGE:
817 return $isAnon && $this->options->get( MainConfigNames::CookieSetOnIpBlock );
818 case DatabaseBlock::TYPE_USER:
819 return !$isAnon &&
820 $this->options->get( MainConfigNames::CookieSetOnAutoblock ) &&
821 $block->isAutoblocking();
822 default:
823 return false;
824 }
825 }
826
827 /**
828 * Unset the 'BlockID' cookie.
829 *
830 * @since 1.34
831 * @param WebResponse $response
832 */
833 public static function clearBlockCookie( WebResponse $response ) {
834 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
835 }
836
837 /**
838 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
839 * the ID and a HMAC (see self::getCookieValue), but will sometimes only be the ID.
840 *
841 * @since 1.34
842 * @param string $cookieValue The string in which to find the ID.
843 * @return int|null The block ID, or null if the HMAC is present and invalid.
844 */
845 private function getIdFromCookieValue( $cookieValue ) {
846 // The cookie value must start with a number
847 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
848 return null;
849 }
850
851 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
852 $bangPos = strpos( $cookieValue, '!' );
853 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
854 if ( !$this->options->get( MainConfigNames::SecretKey ) ) {
855 // If there's no secret key, just use the ID as given.
856 return (int)$id;
857 }
858 $storedHmac = substr( $cookieValue, $bangPos + 1 );
859 $calculatedHmac = MWCryptHash::hmac( $id, $this->options->get( MainConfigNames::SecretKey ), false );
860 if ( $calculatedHmac === $storedHmac ) {
861 return (int)$id;
862 } else {
863 return null;
864 }
865 }
866
867 /**
868 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
869 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
870 * be the block ID.
871 *
872 * @since 1.34
873 * @param DatabaseBlock $block
874 * @return string The block ID, probably concatenated with "!" and the HMAC.
875 */
876 private function getCookieValue( DatabaseBlock $block ) {
877 $id = (string)$block->getId();
878 if ( !$this->options->get( MainConfigNames::SecretKey ) ) {
879 // If there's no secret key, don't append a HMAC.
880 return $id;
881 }
882 $hmac = MWCryptHash::hmac( $id, $this->options->get( MainConfigNames::SecretKey ), false );
883 return $id . '!' . $hmac;
884 }
885 }