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
;
25 use MediaWiki\User\UserIdentity
;
31 * A service class for checking blocks.
32 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
34 * @since 1.34 Refactored from User and Block.
37 // TODO: This should be UserIdentity instead of User
41 /** @var WebRequest */
42 private $currentRequest;
45 private $applyIpBlocksToXff;
48 private $cookieSetOnAutoblock;
51 private $cookieSetOnIpBlock;
54 private $dnsBlacklistUrls;
57 private $enableDnsBlacklist;
63 private $proxyWhitelist;
66 private $softBlockRanges;
69 * @param User $currentUser
70 * @param WebRequest $currentRequest
71 * @param bool $applyIpBlocksToXff
72 * @param bool $cookieSetOnAutoblock
73 * @param bool $cookieSetOnIpBlock
74 * @param array $dnsBlacklistUrls
75 * @param bool $enableDnsBlacklist
76 * @param array $proxyList
77 * @param array $proxyWhitelist
78 * @param array $softBlockRanges
80 public function __construct(
84 $cookieSetOnAutoblock,
92 $this->currentUser
= $currentUser;
93 $this->currentRequest
= $currentRequest;
94 $this->applyIpBlocksToXff
= $applyIpBlocksToXff;
95 $this->cookieSetOnAutoblock
= $cookieSetOnAutoblock;
96 $this->cookieSetOnIpBlock
= $cookieSetOnIpBlock;
97 $this->dnsBlacklistUrls
= $dnsBlacklistUrls;
98 $this->enableDnsBlacklist
= $enableDnsBlacklist;
99 $this->proxyList
= $proxyList;
100 $this->proxyWhitelist
= $proxyWhitelist;
101 $this->softBlockRanges
= $softBlockRanges;
105 * Get the blocks that apply to a user and return the most relevant one.
107 * TODO: $user should be UserIdentity instead of User
109 * @internal This should only be called by User::getBlockedStatus
111 * @param bool $fromReplica Whether to check the replica DB first.
112 * To improve performance, non-critical checks are done against replica DBs.
113 * Check when actually saving should be done against master.
114 * @return Block|null The most relevant block, or null if there is no block.
116 public function getUserBlock( User
$user, $fromReplica ) {
117 $isAnon = $user->getId() === 0;
119 // TODO: If $user is the current user, we should use the current request. Otherwise,
120 // we should not look for XFF or cookie blocks.
121 $request = $user->getRequest();
123 # We only need to worry about passing the IP address to the Block generator if the
124 # user is not immune to autoblocks/hardblocks, and they are the current user so we
125 # know which IP address they're actually coming from
127 $sessionUser = $this->currentUser
;
128 // the session user is set up towards the end of Setup.php. Until then,
129 // assume it's a logged-out user.
130 $globalUserName = $sessionUser->isSafeToLoad()
131 ?
$sessionUser->getName()
132 : IP
::sanitizeIP( $this->currentRequest
->getIP() );
133 if ( $user->getName() === $globalUserName && !$user->isAllowed( 'ipblock-exempt' ) ) {
134 $ip = $this->currentRequest
->getIP();
138 // TODO: remove dependency on Block
139 $block = Block
::newFromTarget( $user, $ip, !$fromReplica );
142 if ( !$block instanceof AbstractBlock
) {
143 $block = $this->getBlockFromCookieValue( $user, $request );
147 if ( !$block instanceof AbstractBlock
149 && !in_array( $ip, $this->proxyWhitelist
)
152 if ( $this->isLocallyBlockedProxy( $ip ) ) {
153 $block = new SystemBlock( [
154 'byText' => wfMessage( 'proxyblocker' )->text(),
155 'reason' => wfMessage( 'proxyblockreason' )->plain(),
157 'systemBlock' => 'proxy',
159 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
160 $block = new SystemBlock( [
161 'byText' => wfMessage( 'sorbs' )->text(),
162 'reason' => wfMessage( 'sorbsreason' )->plain(),
164 'systemBlock' => 'dnsbl',
169 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
170 if ( !$block instanceof AbstractBlock
171 && $this->applyIpBlocksToXff
173 && !in_array( $ip, $this->proxyWhitelist
)
175 $xff = $request->getHeader( 'X-Forwarded-For' );
176 $xff = array_map( 'trim', explode( ',', $xff ) );
177 $xff = array_diff( $xff, [ $ip ] );
178 // TODO: remove dependency on Block
179 $xffblocks = Block
::getBlocksForIPList( $xff, $isAnon, !$fromReplica );
180 // TODO: remove dependency on Block
181 $block = Block
::chooseBlock( $xffblocks, $xff );
182 if ( $block instanceof AbstractBlock
) {
183 # Mangle the reason to alert the user that the block
184 # originated from matching the X-Forwarded-For header.
185 $block->setReason( wfMessage( 'xffblockreason', $block->getReason() )->plain() );
189 if ( !$block instanceof AbstractBlock
192 && IP
::isInRanges( $ip, $this->softBlockRanges
)
194 $block = new SystemBlock( [
196 'byText' => 'MediaWiki default',
197 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
199 'systemBlock' => 'wgSoftBlockRanges',
207 * Try to load a Block from an ID given in a cookie value.
209 * @param UserIdentity $user
210 * @param WebRequest $request
211 * @return Block|bool The Block object, or false if none could be loaded.
213 private function getBlockFromCookieValue(
217 $blockCookieVal = $request->getCookie( 'BlockID' );
218 $response = $request->response();
220 // Make sure there's something to check. The cookie value must start with a number.
221 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
224 // Load the Block from the ID in the cookie.
225 // TODO: remove dependency on Block
226 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
227 if ( $blockCookieId !== null ) {
228 // An ID was found in the cookie.
229 // TODO: remove dependency on Block
230 $tmpBlock = Block
::newFromID( $blockCookieId );
231 if ( $tmpBlock instanceof Block
) {
232 switch ( $tmpBlock->getType() ) {
233 case Block
::TYPE_USER
:
234 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
235 $useBlockCookie = ( $this->cookieSetOnAutoblock
=== true );
238 case Block
::TYPE_RANGE
:
239 // If block is type IP or IP range, load only if user is not logged in (T152462)
240 $blockIsValid = !$tmpBlock->isExpired() && $user->getId() === 0;
241 $useBlockCookie = ( $this->cookieSetOnIpBlock
=== true );
244 $blockIsValid = false;
245 $useBlockCookie = false;
248 if ( $blockIsValid && $useBlockCookie ) {
253 // If the block is not valid, remove the cookie.
254 // TODO: remove dependency on Block
255 Block
::clearCookie( $response );
257 // If the block doesn't exist, remove the cookie.
258 // TODO: remove dependency on Block
259 Block
::clearCookie( $response );
266 * Check if an IP address is in the local proxy list
271 private function isLocallyBlockedProxy( $ip ) {
272 if ( !$this->proxyList
) {
276 if ( !is_array( $this->proxyList
) ) {
277 // Load values from the specified file
278 $this->proxyList
= array_map( 'trim', file( $this->proxyList
) );
281 $resultProxyList = [];
282 $deprecatedIPEntries = [];
284 // backward compatibility: move all ip addresses in keys to values
285 foreach ( $this->proxyList
as $key => $value ) {
286 $keyIsIP = IP
::isIPAddress( $key );
287 $valueIsIP = IP
::isIPAddress( $value );
288 if ( $keyIsIP && !$valueIsIP ) {
289 $deprecatedIPEntries[] = $key;
290 $resultProxyList[] = $key;
291 } elseif ( $keyIsIP && $valueIsIP ) {
292 $deprecatedIPEntries[] = $key;
293 $resultProxyList[] = $key;
294 $resultProxyList[] = $value;
296 $resultProxyList[] = $value;
300 if ( $deprecatedIPEntries ) {
302 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
303 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
306 $proxyListIPSet = new IPSet( $resultProxyList );
307 return $proxyListIPSet->match( $ip );
311 * Whether the given IP is in a DNS blacklist.
313 * @param string $ip IP to check
314 * @param bool $checkWhitelist Whether to check the whitelist first
315 * @return bool True if blacklisted.
317 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
318 if ( !$this->enableDnsBlacklist ||
319 ( $checkWhitelist && in_array( $ip, $this->proxyWhitelist
) )
324 return $this->inDnsBlacklist( $ip, $this->dnsBlacklistUrls
);
328 * Whether the given IP is in a given DNS blacklist.
330 * @param string $ip IP to check
331 * @param array $bases Array of Strings: URL of the DNS blacklist
332 * @return bool True if blacklisted.
334 private function inDnsBlacklist( $ip, array $bases ) {
336 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
337 if ( IP
::isIPv4( $ip ) ) {
338 // Reverse IP, T23255
339 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
341 foreach ( $bases as $base ) {
343 // If we have an access key, use that too (ProjectHoneypot, etc.)
345 if ( is_array( $base ) ) {
346 if ( count( $base ) >= 2 ) {
347 // Access key is 1, base URL is 0
348 $host = "{$base[1]}.$ipReversed.{$base[0]}";
350 $host = "$ipReversed.{$base[0]}";
352 $basename = $base[0];
354 $host = "$ipReversed.$base";
358 $ipList = gethostbynamel( $host );
361 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
366 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );