Merge "Print chained exceptions when maintenance script fails."
[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 IP;
24 use MediaWiki\User\UserIdentity;
25 use User;
26 use WebRequest;
27 use Wikimedia\IPSet;
28
29 /**
30 * A service class for checking blocks.
31 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
32 *
33 * @since 1.34 Refactored from User and Block.
34 */
35 class BlockManager {
36 // TODO: This should be UserIdentity instead of User
37 /** @var User */
38 private $currentUser;
39
40 /** @var WebRequest */
41 private $currentRequest;
42
43 /** @var bool */
44 private $applyIpBlocksToXff;
45
46 /** @var bool */
47 private $cookieSetOnAutoblock;
48
49 /** @var bool */
50 private $cookieSetOnIpBlock;
51
52 /** @var array */
53 private $dnsBlacklistUrls;
54
55 /** @var bool */
56 private $enableDnsBlacklist;
57
58 /** @var array */
59 private $proxyList;
60
61 /** @var array */
62 private $proxyWhitelist;
63
64 /** @var array */
65 private $softBlockRanges;
66
67 /**
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
78 */
79 public function __construct(
80 $currentUser,
81 $currentRequest,
82 $applyIpBlocksToXff,
83 $cookieSetOnAutoblock,
84 $cookieSetOnIpBlock,
85 $dnsBlacklistUrls,
86 $enableDnsBlacklist,
87 $proxyList,
88 $proxyWhitelist,
89 $softBlockRanges
90 ) {
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;
101 }
102
103 /**
104 * Get the blocks that apply to a user and return the most relevant one.
105 *
106 * TODO: $user should be UserIdentity instead of User
107 *
108 * @internal This should only be called by User::getBlockedStatus
109 * @param User $user
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.
114 */
115 public function getUserBlock( User $user, $fromReplica ) {
116 $isAnon = $user->getId() === 0;
117
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();
121
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
125 $ip = null;
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();
134 }
135
136 // User/IP blocking
137 // TODO: remove dependency on DatabaseBlock
138 $block = DatabaseBlock::newFromTarget( $user, $ip, !$fromReplica );
139
140 // Cookie blocking
141 if ( !$block instanceof AbstractBlock ) {
142 $block = $this->getBlockFromCookieValue( $user, $request );
143 }
144
145 // Proxy blocking
146 if ( !$block instanceof AbstractBlock
147 && $ip !== null
148 && !in_array( $ip, $this->proxyWhitelist )
149 ) {
150 // Local list
151 if ( $this->isLocallyBlockedProxy( $ip ) ) {
152 $block = new SystemBlock( [
153 'byText' => wfMessage( 'proxyblocker' )->text(),
154 'reason' => wfMessage( 'proxyblockreason' )->plain(),
155 'address' => $ip,
156 'systemBlock' => 'proxy',
157 ] );
158 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
159 $block = new SystemBlock( [
160 'byText' => wfMessage( 'sorbs' )->text(),
161 'reason' => wfMessage( 'sorbsreason' )->plain(),
162 'address' => $ip,
163 'systemBlock' => 'dnsbl',
164 ] );
165 }
166 }
167
168 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
169 if ( !$block instanceof AbstractBlock
170 && $this->applyIpBlocksToXff
171 && $ip !== null
172 && !in_array( $ip, $this->proxyWhitelist )
173 ) {
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() );
185 }
186 }
187
188 if ( !$block instanceof AbstractBlock
189 && $ip !== null
190 && $isAnon
191 && IP::isInRanges( $ip, $this->softBlockRanges )
192 ) {
193 $block = new SystemBlock( [
194 'address' => $ip,
195 'byText' => 'MediaWiki default',
196 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
197 'anonOnly' => true,
198 'systemBlock' => 'wgSoftBlockRanges',
199 ] );
200 }
201
202 return $block;
203 }
204
205 /**
206 * Try to load a block from an ID given in a cookie value.
207 *
208 * @param UserIdentity $user
209 * @param WebRequest $request
210 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
211 */
212 private function getBlockFromCookieValue(
213 UserIdentity $user,
214 WebRequest $request
215 ) {
216 $blockCookieVal = $request->getCookie( 'BlockID' );
217 $response = $request->response();
218
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 ) ) ) {
221 return false;
222 }
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 );
235 break;
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 );
241 break;
242 default:
243 $blockIsValid = false;
244 $useBlockCookie = false;
245 }
246
247 if ( $blockIsValid && $useBlockCookie ) {
248 // Use the block.
249 return $tmpBlock;
250 }
251
252 // If the block is not valid, remove the cookie.
253 // TODO: remove dependency on DatabaseBlock
254 DatabaseBlock::clearCookie( $response );
255 } else {
256 // If the block doesn't exist, remove the cookie.
257 // TODO: remove dependency on DatabaseBlock
258 DatabaseBlock::clearCookie( $response );
259 }
260 }
261 return false;
262 }
263
264 /**
265 * Check if an IP address is in the local proxy list
266 *
267 * @param string $ip
268 * @return bool
269 */
270 private function isLocallyBlockedProxy( $ip ) {
271 if ( !$this->proxyList ) {
272 return false;
273 }
274
275 if ( !is_array( $this->proxyList ) ) {
276 // Load values from the specified file
277 $this->proxyList = array_map( 'trim', file( $this->proxyList ) );
278 }
279
280 $resultProxyList = [];
281 $deprecatedIPEntries = [];
282
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;
294 } else {
295 $resultProxyList[] = $value;
296 }
297 }
298
299 if ( $deprecatedIPEntries ) {
300 wfDeprecated(
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' );
303 }
304
305 $proxyListIPSet = new IPSet( $resultProxyList );
306 return $proxyListIPSet->match( $ip );
307 }
308
309 /**
310 * Whether the given IP is in a DNS blacklist.
311 *
312 * @param string $ip IP to check
313 * @param bool $checkWhitelist Whether to check the whitelist first
314 * @return bool True if blacklisted.
315 */
316 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
317 if ( !$this->enableDnsBlacklist ||
318 ( $checkWhitelist && in_array( $ip, $this->proxyWhitelist ) )
319 ) {
320 return false;
321 }
322
323 return $this->inDnsBlacklist( $ip, $this->dnsBlacklistUrls );
324 }
325
326 /**
327 * Whether the given IP is in a given DNS blacklist.
328 *
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.
332 */
333 private function inDnsBlacklist( $ip, array $bases ) {
334 $found = false;
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 ) ) );
339
340 foreach ( $bases as $base ) {
341 // Make hostname
342 // If we have an access key, use that too (ProjectHoneypot, etc.)
343 $basename = $base;
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]}";
348 } else {
349 $hostname = "$ipReversed.{$base[0]}";
350 }
351 $basename = $base[0];
352 } else {
353 $hostname = "$ipReversed.$base";
354 }
355
356 // Send query
357 $ipList = $this->checkHost( $hostname );
358
359 if ( $ipList ) {
360 wfDebugLog(
361 'dnsblacklist',
362 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
363 );
364 $found = true;
365 break;
366 }
367
368 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
369 }
370 }
371
372 return $found;
373 }
374
375 /**
376 * Wrapper for mocking in tests.
377 *
378 * @param string $hostname DNSBL query
379 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
380 */
381 protected function checkHost( $hostname ) {
382 return gethostbynamel( $hostname );
383 }
384
385 }