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