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.
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.
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
21 namespace MediaWiki\Block
;
24 use MediaWiki\User\UserIdentity
;
30 * A service class for checking blocks.
31 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
33 * @since 1.34 Refactored from User and Block.
36 // TODO: This should be UserIdentity instead of User
40 /** @var WebRequest */
41 private $currentRequest;
44 private $applyIpBlocksToXff;
47 private $cookieSetOnAutoblock;
50 private $cookieSetOnIpBlock;
53 private $dnsBlacklistUrls;
56 private $enableDnsBlacklist;
62 private $proxyWhitelist;
65 private $softBlockRanges;
68 * @param User $currentUser
69 * @param WebRequest $currentRequest
70 * @param bool $applyIpBlocksToXff
71 * @param bool $cookieSetOnAutoblock
72 * @param bool $cookieSetOnIpBlock
73 * @param array $dnsBlacklistUrls
74 * @param bool $enableDnsBlacklist
75 * @param array $proxyList
76 * @param array $proxyWhitelist
77 * @param array $softBlockRanges
79 public function __construct(
83 $cookieSetOnAutoblock,
91 $this->currentUser
= $currentUser;
92 $this->currentRequest
= $currentRequest;
93 $this->applyIpBlocksToXff
= $applyIpBlocksToXff;
94 $this->cookieSetOnAutoblock
= $cookieSetOnAutoblock;
95 $this->cookieSetOnIpBlock
= $cookieSetOnIpBlock;
96 $this->dnsBlacklistUrls
= $dnsBlacklistUrls;
97 $this->enableDnsBlacklist
= $enableDnsBlacklist;
98 $this->proxyList
= $proxyList;
99 $this->proxyWhitelist
= $proxyWhitelist;
100 $this->softBlockRanges
= $softBlockRanges;
104 * Get the blocks that apply to a user and return the most relevant one.
106 * TODO: $user should be UserIdentity instead of User
108 * @internal This should only be called by User::getBlockedStatus
110 * @param bool $fromReplica Whether to check the replica DB first.
111 * To improve performance, non-critical checks are done against replica DBs.
112 * Check when actually saving should be done against master.
113 * @return AbstractBlock|null The most relevant block, or null if there is no block.
115 public function getUserBlock( User
$user, $fromReplica ) {
116 $isAnon = $user->getId() === 0;
118 // TODO: If $user is the current user, we should use the current request. Otherwise,
119 // we should not look for XFF or cookie blocks.
120 $request = $user->getRequest();
122 # We only need to worry about passing the IP address to the block generator if the
123 # user is not immune to autoblocks/hardblocks, and they are the current user so we
124 # know which IP address they're actually coming from
126 $sessionUser = $this->currentUser
;
127 // the session user is set up towards the end of Setup.php. Until then,
128 // assume it's a logged-out user.
129 $globalUserName = $sessionUser->isSafeToLoad()
130 ?
$sessionUser->getName()
131 : IP
::sanitizeIP( $this->currentRequest
->getIP() );
132 if ( $user->getName() === $globalUserName && !$user->isAllowed( 'ipblock-exempt' ) ) {
133 $ip = $this->currentRequest
->getIP();
137 // TODO: remove dependency on DatabaseBlock
138 $block = DatabaseBlock
::newFromTarget( $user, $ip, !$fromReplica );
141 if ( !$block instanceof AbstractBlock
) {
142 $block = $this->getBlockFromCookieValue( $user, $request );
146 if ( !$block instanceof AbstractBlock
148 && !in_array( $ip, $this->proxyWhitelist
)
151 if ( $this->isLocallyBlockedProxy( $ip ) ) {
152 $block = new SystemBlock( [
153 'byText' => wfMessage( 'proxyblocker' )->text(),
154 'reason' => wfMessage( 'proxyblockreason' )->plain(),
156 'systemBlock' => 'proxy',
158 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
159 $block = new SystemBlock( [
160 'byText' => wfMessage( 'sorbs' )->text(),
161 'reason' => wfMessage( 'sorbsreason' )->plain(),
163 'systemBlock' => 'dnsbl',
168 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
169 if ( !$block instanceof AbstractBlock
170 && $this->applyIpBlocksToXff
172 && !in_array( $ip, $this->proxyWhitelist
)
174 $xff = $request->getHeader( 'X-Forwarded-For' );
175 $xff = array_map( 'trim', explode( ',', $xff ) );
176 $xff = array_diff( $xff, [ $ip ] );
177 // TODO: remove dependency on DatabaseBlock
178 $xffblocks = DatabaseBlock
::getBlocksForIPList( $xff, $isAnon, !$fromReplica );
179 // TODO: remove dependency on DatabaseBlock
180 $block = DatabaseBlock
::chooseBlock( $xffblocks, $xff );
181 if ( $block instanceof AbstractBlock
) {
182 # Mangle the reason to alert the user that the block
183 # originated from matching the X-Forwarded-For header.
184 $block->setReason( wfMessage( 'xffblockreason', $block->getReason() )->plain() );
188 if ( !$block instanceof AbstractBlock
191 && IP
::isInRanges( $ip, $this->softBlockRanges
)
193 $block = new SystemBlock( [
195 'byText' => 'MediaWiki default',
196 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
198 'systemBlock' => 'wgSoftBlockRanges',
206 * Try to load a block from an ID given in a cookie value.
208 * @param UserIdentity $user
209 * @param WebRequest $request
210 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
212 private function getBlockFromCookieValue(
216 $blockCookieVal = $request->getCookie( 'BlockID' );
217 $response = $request->response();
219 // Make sure there's something to check. The cookie value must start with a number.
220 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
223 // Load the block from the ID in the cookie.
224 // TODO: remove dependency on DatabaseBlock
225 $blockCookieId = DatabaseBlock
::getIdFromCookieValue( $blockCookieVal );
226 if ( $blockCookieId !== null ) {
227 // An ID was found in the cookie.
228 // TODO: remove dependency on DatabaseBlock
229 $tmpBlock = DatabaseBlock
::newFromID( $blockCookieId );
230 if ( $tmpBlock instanceof DatabaseBlock
) {
231 switch ( $tmpBlock->getType() ) {
232 case DatabaseBlock
::TYPE_USER
:
233 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
234 $useBlockCookie = ( $this->cookieSetOnAutoblock
=== true );
236 case DatabaseBlock
::TYPE_IP
:
237 case DatabaseBlock
::TYPE_RANGE
:
238 // If block is type IP or IP range, load only if user is not logged in (T152462)
239 $blockIsValid = !$tmpBlock->isExpired() && $user->getId() === 0;
240 $useBlockCookie = ( $this->cookieSetOnIpBlock
=== true );
243 $blockIsValid = false;
244 $useBlockCookie = false;
247 if ( $blockIsValid && $useBlockCookie ) {
252 // If the block is not valid, remove the cookie.
253 // TODO: remove dependency on DatabaseBlock
254 DatabaseBlock
::clearCookie( $response );
256 // If the block doesn't exist, remove the cookie.
257 // TODO: remove dependency on DatabaseBlock
258 DatabaseBlock
::clearCookie( $response );
265 * Check if an IP address is in the local proxy list
270 private function isLocallyBlockedProxy( $ip ) {
271 if ( !$this->proxyList
) {
275 if ( !is_array( $this->proxyList
) ) {
276 // Load values from the specified file
277 $this->proxyList
= array_map( 'trim', file( $this->proxyList
) );
280 $resultProxyList = [];
281 $deprecatedIPEntries = [];
283 // backward compatibility: move all ip addresses in keys to values
284 foreach ( $this->proxyList
as $key => $value ) {
285 $keyIsIP = IP
::isIPAddress( $key );
286 $valueIsIP = IP
::isIPAddress( $value );
287 if ( $keyIsIP && !$valueIsIP ) {
288 $deprecatedIPEntries[] = $key;
289 $resultProxyList[] = $key;
290 } elseif ( $keyIsIP && $valueIsIP ) {
291 $deprecatedIPEntries[] = $key;
292 $resultProxyList[] = $key;
293 $resultProxyList[] = $value;
295 $resultProxyList[] = $value;
299 if ( $deprecatedIPEntries ) {
301 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
302 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
305 $proxyListIPSet = new IPSet( $resultProxyList );
306 return $proxyListIPSet->match( $ip );
310 * Whether the given IP is in a DNS blacklist.
312 * @param string $ip IP to check
313 * @param bool $checkWhitelist Whether to check the whitelist first
314 * @return bool True if blacklisted.
316 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
317 if ( !$this->enableDnsBlacklist ||
318 ( $checkWhitelist && in_array( $ip, $this->proxyWhitelist
) )
323 return $this->inDnsBlacklist( $ip, $this->dnsBlacklistUrls
);
327 * Whether the given IP is in a given DNS blacklist.
329 * @param string $ip IP to check
330 * @param array $bases Array of Strings: URL of the DNS blacklist
331 * @return bool True if blacklisted.
333 private function inDnsBlacklist( $ip, array $bases ) {
335 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
336 if ( IP
::isIPv4( $ip ) ) {
337 // Reverse IP, T23255
338 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
340 foreach ( $bases as $base ) {
342 // If we have an access key, use that too (ProjectHoneypot, etc.)
344 if ( is_array( $base ) ) {
345 if ( count( $base ) >= 2 ) {
346 // Access key is 1, base URL is 0
347 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
349 $hostname = "$ipReversed.{$base[0]}";
351 $basename = $base[0];
353 $hostname = "$ipReversed.$base";
357 $ipList = $this->checkHost( $hostname );
362 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
368 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
376 * Wrapper for mocking in tests.
378 * @param string $hostname DNSBL query
379 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
381 protected function checkHost( $hostname ) {
382 return gethostbynamel( $hostname );