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
22 namespace MediaWiki\Auth
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
31 * A helper class for throttling authentication attempts.
32 * @package MediaWiki\Auth
36 class Throttler
implements LoggerAwareInterface
{
40 * See documentation of $wgPasswordAttemptThrottle for format. Old (pre-1.27) format is not
43 * @see https://www.mediawiki.org/wiki/Manual:$wgPasswordAttemptThrottle
45 protected $conditions;
48 /** @var LoggerInterface */
51 protected $warningLimit;
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.
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 ) ) );
70 if ( $conditions === null ) {
71 $config = \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
72 $conditions = $config->get( 'PasswordAttemptThrottle' );
75 'cache' => \ObjectCache
::getLocalClusterInstance(),
81 'cache' => \ObjectCache
::getLocalClusterInstance(),
82 'warningLimit' => INF
,
86 $this->type
= $params['type'];
87 $this->conditions
= static::normalizeThrottleConditions( $conditions );
88 $this->cache
= $params['cache'];
89 $this->warningLimit
= $params['warningLimit'];
91 $this->setLogger( LoggerFactory
::getInstance( 'throttler' ) );
94 public function setLogger( LoggerInterface
$logger ) {
95 $this->logger
= $logger;
99 * Increase the throttle counter and return whether the attempt should be throttled.
101 * Should be called before an authentication attempt.
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
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' );
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'];
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 ) {
129 $throttleKey = wfGlobalCacheKey( 'throttler', $this->type
, $index, $ipKey, $userKey );
130 $throttleCount = $this->cache
->get( $throttleKey );
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
,
141 'username' => $username,
144 // @codeCoverageIgnoreStart
145 'method' => $caller ?
: __METHOD__
,
146 // @codeCoverageIgnoreEnd
150 'throttleIndex' => $index,
160 * Clear the throttle counter.
162 * Should be called after a successful authentication attempt.
164 * @param string|null $username
165 * @param string|null $ip
166 * @throws \MWException
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 );
178 * Handles B/C for $wgPasswordAttemptThrottle.
179 * @param array $throttleConditions
181 * @see $wgPasswordAttemptThrottle for structure
183 protected static function normalizeThrottleConditions( $throttleConditions ) {
184 if ( !is_array( $throttleConditions ) ) {
187 if ( isset( $throttleConditions['count'] ) ) { // old style
188 $throttleConditions = [ $throttleConditions ];
190 return $throttleConditions;
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}';
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
;
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 );