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