Merge "Fix 'Tags' padding to keep it farther from the edge and document the source...
[lhc/web/wiklou.git] / includes / auth / ThrottlePreAuthenticationProvider.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 Config;
26
27 /**
28 * A pre-authentication provider to throttle authentication actions.
29 *
30 * Adding this provider will throttle account creations and primary authentication attempts
31 * (more specifically, any authentication that returns FAIL on failure). Secondary authentication
32 * cannot be easily throttled on a framework level (since it would typically return UI on failure);
33 * secondary providers are expected to do their own throttling.
34 * @ingroup Auth
35 * @since 1.27
36 */
37 class ThrottlePreAuthenticationProvider extends AbstractPreAuthenticationProvider {
38 /** @var array */
39 protected $throttleSettings;
40
41 /** @var Throttler */
42 protected $accountCreationThrottle;
43
44 /** @var Throttler */
45 protected $passwordAttemptThrottle;
46
47 /** @var BagOStuff */
48 protected $cache;
49
50 /**
51 * @param array $params
52 * - accountCreationThrottle: (array) Condition array for the account creation throttle; an array
53 * of arrays in a format like $wgPasswordAttemptThrottle, passed to the Throttler constructor.
54 * - passwordAttemptThrottle: (array) Condition array for the password attempt throttle, in the
55 * same format as accountCreationThrottle.
56 * - cache: (BagOStuff) Where to store the throttle, defaults to the local cluster instance.
57 */
58 public function __construct( $params = [] ) {
59 $this->throttleSettings = array_intersect_key( $params,
60 [ 'accountCreationThrottle' => true, 'passwordAttemptThrottle' => true ] );
61 $this->cache = $params['cache'] ?? \ObjectCache::getLocalClusterInstance();
62 }
63
64 public function setConfig( Config $config ) {
65 parent::setConfig( $config );
66
67 $accountCreationThrottle = $this->config->get( 'AccountCreationThrottle' );
68 // Handle old $wgAccountCreationThrottle format (number of attempts per 24 hours)
69 if ( !is_array( $accountCreationThrottle ) ) {
70 $accountCreationThrottle = [ [
71 'count' => $accountCreationThrottle,
72 'seconds' => 86400,
73 ] ];
74 }
75
76 // @codeCoverageIgnoreStart
77 $this->throttleSettings += [
78 // @codeCoverageIgnoreEnd
79 'accountCreationThrottle' => $accountCreationThrottle,
80 'passwordAttemptThrottle' => $this->config->get( 'PasswordAttemptThrottle' ),
81 ];
82
83 if ( !empty( $this->throttleSettings['accountCreationThrottle'] ) ) {
84 $this->accountCreationThrottle = new Throttler(
85 $this->throttleSettings['accountCreationThrottle'], [
86 'type' => 'acctcreate',
87 'cache' => $this->cache,
88 ]
89 );
90 }
91 if ( !empty( $this->throttleSettings['passwordAttemptThrottle'] ) ) {
92 $this->passwordAttemptThrottle = new Throttler(
93 $this->throttleSettings['passwordAttemptThrottle'], [
94 'type' => 'password',
95 'cache' => $this->cache,
96 ]
97 );
98 }
99 }
100
101 public function testForAccountCreation( $user, $creator, array $reqs ) {
102 if ( !$this->accountCreationThrottle || !$creator->isPingLimitable() ) {
103 return \StatusValue::newGood();
104 }
105
106 $ip = $this->manager->getRequest()->getIP();
107
108 if ( !\Hooks::run( 'ExemptFromAccountCreationThrottle', [ $ip ] ) ) {
109 $this->logger->debug( __METHOD__ . ": a hook allowed account creation w/o throttle\n" );
110 return \StatusValue::newGood();
111 }
112
113 $result = $this->accountCreationThrottle->increase( null, $ip, __METHOD__ );
114 if ( $result ) {
115 $message = wfMessage( 'acct_creation_throttle_hit' )->params( $result['count'] )
116 ->durationParams( $result['wait'] );
117 return \StatusValue::newFatal( $message );
118 }
119
120 return \StatusValue::newGood();
121 }
122
123 public function testForAuthentication( array $reqs ) {
124 if ( !$this->passwordAttemptThrottle ) {
125 return \StatusValue::newGood();
126 }
127
128 $ip = $this->manager->getRequest()->getIP();
129 try {
130 $username = AuthenticationRequest::getUsernameFromRequests( $reqs );
131 } catch ( \UnexpectedValueException $e ) {
132 $username = '';
133 }
134
135 // Get everything this username could normalize to, and throttle each one individually.
136 // If nothing uses usernames, just throttle by IP.
137 $usernames = $this->manager->normalizeUsername( $username );
138 $result = false;
139 foreach ( $usernames as $name ) {
140 $r = $this->passwordAttemptThrottle->increase( $name, $ip, __METHOD__ );
141 if ( $r && ( !$result || $result['wait'] < $r['wait'] ) ) {
142 $result = $r;
143 }
144 }
145
146 if ( $result ) {
147 $message = wfMessage( 'login-throttled' )->durationParams( $result['wait'] );
148 return \StatusValue::newFatal( $message );
149 } else {
150 $this->manager->setAuthenticationSessionData( 'LoginThrottle',
151 [ 'users' => $usernames, 'ip' => $ip ] );
152 return \StatusValue::newGood();
153 }
154 }
155
156 /**
157 * @param null|\User $user
158 * @param AuthenticationResponse $response
159 */
160 public function postAuthentication( $user, AuthenticationResponse $response ) {
161 if ( $response->status !== AuthenticationResponse::PASS ) {
162 return;
163 } elseif ( !$this->passwordAttemptThrottle ) {
164 return;
165 }
166
167 $data = $this->manager->getAuthenticationSessionData( 'LoginThrottle' );
168 if ( !$data ) {
169 // this can occur when login is happening via AuthenticationRequest::$loginRequest
170 // so testForAuthentication is skipped
171 $this->logger->info( 'throttler data not found for {user}', [ 'user' => $user->getName() ] );
172 return;
173 }
174
175 foreach ( $data['users'] as $name ) {
176 $this->passwordAttemptThrottle->clear( $name, $data['ip'] );
177 }
178 }
179 }