MediaWiki  1.27.2
Throttler.php
Go to the documentation of this file.
1 <?php
22 namespace MediaWiki\Auth;
23 
25 use Config;
31 use User;
32 
39 class Throttler implements LoggerAwareInterface {
41  protected $type;
48  protected $conditions;
50  protected $cache;
52  protected $logger;
54  protected $warningLimit;
55 
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  if ( $conditions === null ) {
74  $config = \ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
75  $conditions = $config->get( 'PasswordAttemptThrottle' );
76  $params += [
77  'type' => 'password',
79  'warningLimit' => 50,
80  ];
81  } else {
82  $params += [
83  'type' => 'custom',
85  'warningLimit' => INF,
86  ];
87  }
88 
89  $this->type = $params['type'];
90  $this->conditions = static::normalizeThrottleConditions( $conditions );
91  $this->cache = $params['cache'];
92  $this->warningLimit = $params['warningLimit'];
93 
94  $this->setLogger( LoggerFactory::getInstance( 'throttler' ) );
95  }
96 
97  public function setLogger( LoggerInterface $logger ) {
98  $this->logger = $logger;
99  }
100 
115  public function increase( $username = null, $ip = null, $caller = null ) {
116  if ( $username === null && $ip === null ) {
117  throw new \InvalidArgumentException( 'Either username or IP must be set for throttling' );
118  }
119 
120  $userKey = $username ? md5( $username ) : null;
121  foreach ( $this->conditions as $index => $throttleCondition ) {
122  $ipKey = isset( $throttleCondition['allIPs'] ) ? null : $ip;
123  $count = $throttleCondition['count'];
124  $expiry = $throttleCondition['seconds'];
125 
126  // a limit of 0 is used as a disable flag in some throttling configuration settings
127  // throttling the whole world is probably a bad idea
128  if ( !$count || $userKey === null && $ipKey === null ) {
129  continue;
130  }
131 
132  $throttleKey = wfGlobalCacheKey( 'throttler', $this->type, $index, $ipKey, $userKey );
133  $throttleCount = $this->cache->get( $throttleKey );
134 
135  if ( !$throttleCount ) { // counter not started yet
136  $this->cache->add( $throttleKey, 1, $expiry );
137  } elseif ( $throttleCount < $count ) { // throttle limited not yet reached
138  $this->cache->incr( $throttleKey );
139  } else { // throttled
140  $this->logRejection( [
141  'type' => $this->type,
142  'index' => $index,
143  'ip' => $ipKey,
144  'username' => $username,
145  'count' => $count,
146  'expiry' => $expiry,
147  // @codeCoverageIgnoreStart
148  'method' => $caller ?: __METHOD__,
149  // @codeCoverageIgnoreEnd
150  ] );
151 
152  return [
153  'throttleIndex' => $index,
154  'count' => $count,
155  'wait' => $expiry,
156  ];
157  }
158  }
159  return false;
160  }
161 
171  public function clear( $username = null, $ip = null ) {
172  $userKey = $username ? md5( $username ) : null;
173  foreach ( $this->conditions as $index => $specificThrottle ) {
174  $ipKey = isset( $specificThrottle['allIPs'] ) ? null : $ip;
175  $throttleKey = wfGlobalCacheKey( 'throttler', $this->type, $index, $ipKey, $userKey );
176  $this->cache->delete( $throttleKey );
177  }
178  }
179 
186  protected static function normalizeThrottleConditions( $throttleConditions ) {
187  if ( !is_array( $throttleConditions ) ) {
188  return [];
189  }
190  if ( isset( $throttleConditions['count'] ) ) { // old style
191  $throttleConditions = [ $throttleConditions ];
192  }
193  return $throttleConditions;
194  }
195 
196  protected function logRejection( array $context ) {
197  $logMsg = 'Throttle {type} hit, throttled for {expiry} seconds due to {count} attempts '
198  . 'from username {username} and IP {ip}';
199 
200  // If we are hitting a throttle for >= warningLimit attempts, it is much more likely to be
201  // an attack than someone simply forgetting their password, so log it at a higher level.
202  $level = $context['count'] >= $this->warningLimit ? LogLevel::WARNING : LogLevel::INFO;
203 
204  // It should be noted that once the throttle is hit, every attempt to login will
205  // generate the log message until the throttle expires, not just the attempt that
206  // puts the throttle over the top.
207  $this->logger->log( $level, $logMsg, $context );
208  }
209 
210 }
Config $config
Definition: MediaWiki.php:37
the array() calling protocol came about after MediaWiki 1.4rc1.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static getInstance($channel)
Get a named logger instance from the currently configured logger factory.
static getLocalClusterInstance()
Get the main cluster-local cache object.
get($name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
LoggerInterface $logger
Definition: Throttler.php:52
wfGlobalCacheKey()
Make a cache key with database-agnostic prefix.
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
logRejection(array $context)
Definition: Throttler.php:196
IContextSource $context
Definition: MediaWiki.php:32
__construct(array $conditions=null, array $params=[])
Definition: Throttler.php:65
$params
array $conditions
See documentation of $wgPasswordAttemptThrottle for format.
Definition: Throttler.php:48
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this submitted means any form of or written communication sent to the Licensor or its including but not limited to communication on electronic mailing source code control and issue tracking systems that are managed or on behalf the Licensor for the purpose of discussing and improving the but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as Not a Contribution Contributor shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work Grant of Copyright License Subject to the terms and conditions of this each Contributor hereby grants to You a non no royalty irrevocable copyright license to prepare Derivative Works publicly publicly and distribute the Work and such Derivative Works in Source or Object form Grant of Patent License Subject to the terms and conditions of this each Contributor hereby grants to You a non no royalty have offer to and otherwise transfer the where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed Redistribution You may reproduce and distribute copies of the Work or Derivative Works thereof in any with or without and in Source or Object provided that You meet the following conditions
to add to the query
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static getDefaultInstance()
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:762
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
Definition: postgres.txt:22
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
$count
increase($username=null, $ip=null, $caller=null)
Increase the throttle counter and return whether the attempt should be throttled. ...
Definition: Throttler.php:115
setLogger(LoggerInterface $logger)
Definition: Throttler.php:97
static normalizeThrottleConditions($throttleConditions)
Handles B/C for $wgPasswordAttemptThrottle.
Definition: Throttler.php:186
clear($username=null, $ip=null)
Clear the throttle counter.
Definition: Throttler.php:171