Debian Codegraph @

includes/auth/Throttler.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 * @ingroup Auth
20 */
21
22 namespace MediaWiki\Auth;
23
24 use InvalidArgumentException;
25 use MediaWiki\Logger\LoggerFactory;
26 use MediaWiki\MainConfigNames;
27 use MediaWiki\MediaWikiServices;
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\LoggerInterface;
30 use Psr\Log\LogLevel;
31 use Wikimedia\ObjectCache\BagOStuff;
32
33 /**
34 * A helper class for throttling authentication attempts.
35 * @package MediaWiki\Auth
36 * @ingroup Auth
37 * @since 1.27
38 */
39 class Throttler implements LoggerAwareInterface {
40 /** @var string */
41 protected $type;
42 /**
43 * See documentation of $wgPasswordAttemptThrottle for format. Old (pre-1.27) format is not
44 * allowed here.
45 * @var array[]
46 * @see https://www.mediawiki.org/wiki/Manual:$wgPasswordAttemptThrottle
47 */
48 protected $conditions;
49 /** @var BagOStuff */
50 protected $cache;
51 /** @var LoggerInterface */
52 protected $logger;
53 /** @var int|float */
54 protected $warningLimit;
55
56 /**
57 * @param array|null $conditions An array of arrays describing throttling conditions.
58 * Defaults to $wgPasswordAttemptThrottle. See documentation of that variable for format.
59 * @param array $params Parameters (all optional):
60 * - type: throttle type, used as a namespace for counters,
61 * - cache: a BagOStuff object where throttle counters are stored.
62 * - warningLimit: the log level will be raised to warning when rejecting an attempt after
63 * no less than this many failures.
64 */
65 public function __construct( ?array $conditions = null, array $params = [] ) {
66 $invalidParams = array_diff_key( $params,
67 array_fill_keys( [ 'type', 'cache', 'warningLimit' ], true ) );
68 if ( $invalidParams ) {
69 throw new InvalidArgumentException( 'unrecognized parameters: '
70 . implode( ', ', array_keys( $invalidParams ) ) );
71 }
72
73 $services = MediaWikiServices::getInstance();
74 $objectCacheFactory = $services->getObjectCacheFactory();
75
76 if ( $conditions === null ) {
77 $config = $services->getMainConfig();
78 $conditions = $config->get( MainConfigNames::PasswordAttemptThrottle );
79 $params += [
80 'type' => 'password',
81 'cache' => $objectCacheFactory->getLocalClusterInstance(),
82 'warningLimit' => 50,
83 ];
84 } else {
85 $params += [
86 'type' => 'custom',
87 'cache' => $objectCacheFactory->getLocalClusterInstance(),
88 'warningLimit' => INF,
89 ];
90 }
91
92 $this->type = $params['type'];
93 $this->conditions = static::normalizeThrottleConditions( $conditions );
94 $this->cache = $params['cache'];
95 $this->warningLimit = $params['warningLimit'];
96
97 $this->setLogger( LoggerFactory::getInstance( 'throttler' ) );
98 }
99
100 public function setLogger( LoggerInterface $logger ) {
101 $this->logger = $logger;
102 }
103
104 /**
105 * Increase the throttle counter and return whether the attempt should be throttled.
106 *
107 * Should be called before an authentication attempt.
108 *
109 * @param string|null $username
110 * @param string|null $ip
111 * @param string|null $caller The authentication method from which we were called.
112 * @return array|false False if the attempt should not be throttled, an associative array
113 * with three keys otherwise:
114 * - throttleIndex: which throttle condition was met (a key of the conditions array)
115 * - count: throttle count (ie. number of failed attempts)
116 * - wait: time in seconds until authentication can be attempted
117 */
118 public function increase( $username = null, $ip = null, $caller = null ) {
119 if ( $username === null && $ip === null ) {
120 throw new InvalidArgumentException( 'Either username or IP must be set for throttling' );
121 }
122
123 $userKey = $username ? md5( $username ) : null;
124 foreach ( $this->conditions as $index => $throttleCondition ) {
125 $ipKey = isset( $throttleCondition['allIPs'] ) ? null : $ip;
126 $count = $throttleCondition['count'];
127 $expiry = $throttleCondition['seconds'];
128
129 // a limit of 0 is used as a disable flag in some throttling configuration settings
130 // throttling the whole world is probably a bad idea
131 if ( !$count || ( $userKey === null && $ipKey === null ) ) {
132 continue;
133 }
134
135 $throttleKey = $this->getThrottleKey( $this->type, $index, $ipKey, $userKey );
136 $throttleCount = $this->cache->get( $throttleKey );
137 if ( $throttleCount && $throttleCount >= $count ) {
138 // Throttle limited reached
139 $this->logRejection( [
140 'throttle' => $this->type,
141 'index' => $index,
142 'ipKey' => $ipKey,
143 'username' => $username,
144 'count' => $count,
145 'expiry' => $expiry,
146 // @codeCoverageIgnoreStart
147 'method' => $caller ?: __METHOD__,
148 // @codeCoverageIgnoreEnd
149 ] );
150
151 return [ 'throttleIndex' => $index, 'count' => $count, 'wait' => $expiry ];
152 } else {
153 $this->cache->incrWithInit( $throttleKey, $expiry, 1 );
154 }
155 }
156
157 return false;
158 }
159
160 /**
161 * Clear the throttle counter.
162 *
163 * Should be called after a successful authentication attempt.
164 *
165 * @param string|null $username
166 * @param string|null $ip
167 */
168 public function clear( $username = null, $ip = null ) {
169 $userKey = $username ? md5( $username ) : null;
170 foreach ( $this->conditions as $index => $specificThrottle ) {
171 $ipKey = isset( $specificThrottle['allIPs'] ) ? null : $ip;
172 $throttleKey = $this->getThrottleKey( $this->type, $index, $ipKey, $userKey );
173 $this->cache->delete( $throttleKey );
174 }
175 }
176
177 /**
178 * Construct a cache key for the throttle counter
179 * @param string $type
180 * @param int $index
181 * @param string|null $ipKey
182 * @param string|null $userKey
183 * @return string
184 */
185 private function getThrottleKey( string $type, int $index, ?string $ipKey, ?string $userKey ): string {
186 return $this->cache->makeGlobalKey(
187 'throttler',
188 $type,
189 $index,
190 $ipKey ?? '',
191 $userKey ?? ''
192 );
193 }
194
195 /**
196 * Handles B/C for $wgPasswordAttemptThrottle.
197 * @param array $throttleConditions
198 * @return array[]
199 * @see $wgPasswordAttemptThrottle for structure
200 */
201 protected static function normalizeThrottleConditions( $throttleConditions ) {
202 if ( !is_array( $throttleConditions ) ) {
203 return [];
204 }
205 if ( isset( $throttleConditions['count'] ) ) { // old style
206 $throttleConditions = [ $throttleConditions ];
207 }
208 return $throttleConditions;
209 }
210
211 protected function logRejection( array $context ) {
212 $logMsg = 'Throttle {throttle} hit, throttled for {expiry} seconds due to {count} attempts '
213 . 'from username {username} and IP {ipKey}';
214
215 // If we are hitting a throttle for >= warningLimit attempts, it is much more likely to be
216 // an attack than someone simply forgetting their password, so log it at a higher level.
217 $level = $context['count'] >= $this->warningLimit ? LogLevel::WARNING : LogLevel::INFO;
218
219 // It should be noted that once the throttle is hit, every attempt to login will
220 // generate the log message until the throttle expires, not just the attempt that
221 // puts the throttle over the top.
222 $this->logger->log( $level, $logMsg, $context );
223 }
224
225 }