Debian Codegraph @

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