Debian Codegraph @

extensions/ConfirmEdit/includes/Auth/CaptchaPreAuthenticationProvider.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\ConfirmEdit\Auth;
4
5 use MediaWiki\Auth\AbstractPreAuthenticationProvider;
6 use MediaWiki\Auth\AuthenticationRequest;
7 use MediaWiki\Auth\AuthenticationResponse;
8 use MediaWiki\Auth\AuthManager;
9 use MediaWiki\Extension\ConfirmEdit\CaptchaTriggers;
10 use MediaWiki\Extension\ConfirmEdit\Hooks;
11 use MediaWiki\Extension\ConfirmEdit\SimpleCaptcha\SimpleCaptcha;
12 use MediaWiki\Logger\LoggerFactory;
13 use MediaWiki\Status\Status;
14 use MediaWiki\User\User;
15
16 class CaptchaPreAuthenticationProvider extends AbstractPreAuthenticationProvider {
17 /**
18 * @inheritDoc
19 */
20 public function getAuthenticationRequests( $action, array $options ) {
21 $captcha = Hooks::getInstance();
22 $user = User::newFromName( $options['username'] );
23
24 $needed = false;
25 switch ( $action ) {
26 case AuthManager::ACTION_CREATE:
27 $u = $user ?: new User();
28 $needed = $captcha->needCreateAccountCaptcha( $u );
29 if ( $needed ) {
30 $captcha->setAction( 'createaccount' );
31 // This is debug level simply because generally
32 // captchas are either always or never triggered on
33 // view of create account, so it gets pretty noisy
34 LoggerFactory::getInstance( 'captcha' )
35 ->debug( 'Captcha shown on account creation for {user}', [
36 'event' => 'captcha.display',
37 'eventType' => 'accountcreation',
38 'user' => $u->getName()
39 ] );
40 }
41 break;
42 case AuthManager::ACTION_LOGIN:
43 // Captcha is shown on login when there were too many failed attempts from the current IP
44 // or using a given username, or if a hook handler says that a CAPTCHA should be shown.
45 // The varying on username is a bit awkward because we don't know the
46 // username yet. The username from the last successful login is stored in a cookie,
47 // but we still must make sure to not lock out other usernames, so after the first
48 // failed login attempt using a username that needs a captcha, set a session flag
49 // to display a captcha on login from that point on. This will result in confusing
50 // error messages if the browser cannot persist the session (because we'll never show
51 // a required captcha field), but then login would be impossible anyway so no big deal.
52
53 // If the username ends to be one that does not trigger the captcha, that will
54 // result in weird behavior (if the user leaves the captcha field empty, they get
55 // a required field error; if they fill it with an invalid answer, it will pass)
56 // - again, not a huge deal.
57 $session = $this->manager->getRequest()->getSession();
58 $suggestedUsername = $session->suggestLoginUsername();
59 if ( $captcha->triggersCaptcha( CaptchaTriggers::LOGIN_ATTEMPT ) ) {
60 $captcha->setAction( 'loginattempt' );
61 LoggerFactory::getInstance( 'captcha' )
62 ->info( 'Captcha shown on login attempt by {clientip} for {suggestedUser}', [
63 'event' => 'captcha.display',
64 'eventType' => 'loginattempt',
65 'suggestedUser' => $suggestedUsername,
66 'clientip' => $this->manager->getRequest()->getIP(),
67 'ua' => $this->manager->getRequest()->getHeader( 'User-Agent' )
68 ] );
69 $needed = true;
70 break;
71 }
72 $loginCounter = $this->getLoginAttemptCounter( $captcha );
73
74 $userProbablyNeedsCaptcha = $session->get( 'ConfirmEdit:loginCaptchaPerUserTriggered' );
75 if (
76 $loginCounter->isBadLoginTriggered()
77 || $userProbablyNeedsCaptcha
78 || ( $suggestedUsername && $loginCounter->isBadLoginPerUserTriggered( $suggestedUsername ) )
79 ) {
80 $needed = true;
81 $captcha->setAction( 'badlogin' );
82 LoggerFactory::getInstance( 'captcha' )
83 ->info( 'Captcha shown on login by {clientip} for {suggestedUser}', [
84 'event' => 'captcha.display',
85 'eventType' => 'badlogin',
86 'suggestedUser' => $suggestedUsername,
87 'clientip' => $this->manager->getRequest()->getIP(),
88 'ua' => $this->manager->getRequest()->getHeader( 'User-Agent' )
89 ] );
90 break;
91 }
92 break;
93 }
94
95 if ( $needed ) {
96 return [ $captcha->createAuthenticationRequest() ];
97 } else {
98 return [];
99 }
100 }
101
102 /**
103 * @inheritDoc
104 */
105 public function testForAuthentication( array $reqs ) {
106 $captcha = Hooks::getInstance();
107 $username = AuthenticationRequest::getUsernameFromRequests( $reqs );
108 $loginCounter = $this->getLoginAttemptCounter( $captcha );
109 $success = true;
110 $isBadLoginPerUserTriggered = $username ?
111 $loginCounter->isBadLoginPerUserTriggered( $username ) : false;
112 $loginTriggersCaptcha = $captcha->triggersCaptcha( CaptchaTriggers::LOGIN_ATTEMPT );
113
114 if (
115 $isBadLoginPerUserTriggered ||
116 $loginCounter->isBadLoginTriggered() ||
117 $loginTriggersCaptcha
118 ) {
119
120 if ( $loginTriggersCaptcha ) {
121 $captcha->setAction( 'loginattempt' );
122 $captcha->setTrigger( "loginattempt login '$username'" );
123 } else {
124 $captcha->setAction( 'badlogin' );
125 $captcha->setTrigger( "post-badlogin login '$username'" );
126 }
127 $success = $this->verifyCaptcha( $captcha, $reqs, new User() );
128 $ip = $this->manager->getRequest()->getIP();
129 $action = $loginTriggersCaptcha ? 'login page' : 'bad login';
130 LoggerFactory::getInstance( 'captcha' )->info( "Captcha shown on $action for {user}", [
131 'event' => 'captcha.submit',
132 'eventType' => $loginTriggersCaptcha ? 'loginattempt' : 'badlogin',
133 'successful' => $success,
134 'user' => $username ?? 'unknown',
135 'clientip' => $ip,
136 'ua' => $this->manager->getRequest()->getHeader( 'User-Agent' )
137 ] );
138 }
139
140 if ( $isBadLoginPerUserTriggered ) {
141 $session = $this->manager->getRequest()->getSession();
142 // A captcha is needed to log in with this username, so display it on the next attempt.
143 $session->set( 'ConfirmEdit:loginCaptchaPerUserTriggered', true );
144 }
145
146 // Make brute force attacks harder by not telling whether the password or the
147 // captcha failed.
148 return $success ? Status::newGood() : $this->makeError( 'wrongpassword', $captcha );
149 }
150
151 /**
152 * @inheritDoc
153 */
154 public function testForAccountCreation( $user, $creator, array $reqs ) {
155 $captcha = Hooks::getInstance();
156
157 if ( $captcha->needCreateAccountCaptcha( $creator ) ) {
158 $username = $user->getName();
159 $captcha->setAction( 'createaccount' );
160 $captcha->setTrigger( "new account '$username'" );
161 $success = $this->verifyCaptcha( $captcha, $reqs, $user );
162 $ip = $this->manager->getRequest()->getIP();
163 LoggerFactory::getInstance( 'captcha' )->info(
164 'Captcha submitted on account creation for {user}', [
165 'event' => 'captcha.submit',
166 'eventType' => 'accountcreation',
167 'successful' => $success,
168 'user' => $username,
169 'clientip' => $ip,
170 'ua' => $this->manager->getRequest()->getHeader( 'User-Agent' )
171 ]
172 );
173 if ( !$success ) {
174 return $this->makeError( 'captcha-createaccount-fail', $captcha );
175 }
176 }
177 return Status::newGood();
178 }
179
180 /**
181 * @inheritDoc
182 */
183 public function postAuthentication( $user, AuthenticationResponse $response ) {
184 $captcha = Hooks::getInstance();
185 $loginCounter = $this->getLoginAttemptCounter( $captcha );
186 switch ( $response->status ) {
187 case AuthenticationResponse::PASS:
188 case AuthenticationResponse::RESTART:
189 $session = $this->manager->getRequest()->getSession();
190 $session->remove( 'ConfirmEdit:loginCaptchaPerUserTriggered' );
191 $loginCounter->resetBadLoginCounter( $user ? $user->getName() : null );
192 break;
193 case AuthenticationResponse::FAIL:
194 $loginCounter->increaseBadLoginCounter( $user ? $user->getName() : null );
195 break;
196 }
197 }
198
199 /**
200 * Verify submitted captcha.
201 * Assumes that the user has to pass the capctha (permission checks are caller's responsibility).
202 * @param SimpleCaptcha $captcha
203 * @param AuthenticationRequest[] $reqs
204 * @param User $user
205 * @return bool
206 */
207 protected function verifyCaptcha( SimpleCaptcha $captcha, array $reqs, User $user ) {
208 /** @var CaptchaAuthenticationRequest $req */
209 $req = AuthenticationRequest::getRequestByClass( $reqs,
210 CaptchaAuthenticationRequest::class, true );
211 if ( !$req ) {
212 return false;
213 }
214 return $captcha->passCaptchaLimited( $req->captchaId, $req->captchaWord, $user );
215 }
216
217 /**
218 * @param string $message Message key
219 * @param SimpleCaptcha $captcha
220 * @return Status
221 */
222 protected function makeError( $message, SimpleCaptcha $captcha ) {
223 $error = $captcha->getError();
224 if ( $error ) {
225 return Status::newFatal( wfMessage( 'captcha-error', $error ) );
226 }
227 return Status::newFatal( $message );
228 }
229
230 protected function getLoginAttemptCounter( SimpleCaptcha $captcha ): LoginAttemptCounter {
231 // Overridable for testing
232 return new LoginAttemptCounter( $captcha );
233 }
234 }