Debian Codegraph @

includes/api/ApiLogin.php

raw symbols SCIP
1 <?php
2 /**
3 * Copyright © 2006-2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com",
4 * Daniel Cannon (cannon dot danielc at gmail dot com)
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 */
23
24 namespace MediaWiki\Api;
25
26 use MediaWiki\Auth\AuthenticationRequest;
27 use MediaWiki\Auth\AuthenticationResponse;
28 use MediaWiki\Auth\AuthManager;
29 use MediaWiki\Logger\LoggerFactory;
30 use MediaWiki\MainConfigNames;
31 use MediaWiki\Message\Message;
32 use MediaWiki\Session\SessionManager;
33 use MediaWiki\User\BotPassword;
34 use Wikimedia\ParamValidator\ParamValidator;
35
36 /**
37 * Unit to authenticate log-in attempts to the current wiki.
38 *
39 * @ingroup API
40 */
41 class ApiLogin extends ApiBase {
42
43 private AuthManager $authManager;
44
45 public function __construct(
46 ApiMain $main,
47 string $action,
48 AuthManager $authManager
49 ) {
50 parent::__construct( $main, $action, 'lg' );
51 $this->authManager = $authManager;
52 }
53
54 protected function getExtendedDescription() {
55 if ( $this->getConfig()->get( MainConfigNames::EnableBotPasswords ) ) {
56 return 'apihelp-login-extended-description';
57 } else {
58 return 'apihelp-login-extended-description-nobotpasswords';
59 }
60 }
61
62 /**
63 * Format a message for the response
64 * @param Message|string|array $message
65 * @return string|array
66 */
67 private function formatMessage( $message ) {
68 $message = Message::newFromSpecifier( $message );
69 $errorFormatter = $this->getErrorFormatter();
70 if ( $errorFormatter instanceof ApiErrorFormatter_BackCompat ) {
71 return ApiErrorFormatter::stripMarkup(
72 $message->useDatabase( false )->inLanguage( 'en' )->text()
73 );
74 } else {
75 return $errorFormatter->formatMessage( $message );
76 }
77 }
78
79 /**
80 * Executes the log-in attempt using the parameters passed. If
81 * the log-in succeeds, it attaches a cookie to the session
82 * and outputs the user id, username, and session token. If a
83 * log-in fails, as the result of a bad password, a nonexistent
84 * user, or any other reason, the host is cached with an expiry
85 * and no log-in attempts will be accepted until that expiry
86 * is reached. The expiry is $this->mLoginThrottle.
87 */
88 public function execute() {
89 // If we're in a mode that breaks the same-origin policy, no tokens can
90 // be obtained
91 if ( $this->lacksSameOriginSecurity() ) {
92 $this->getResult()->addValue( null, 'login', [
93 'result' => 'Aborted',
94 'reason' => $this->formatMessage( 'api-login-fail-sameorigin' ),
95 ] );
96
97 return;
98 }
99
100 $this->requirePostedParameters( [ 'password', 'token' ] );
101
102 $params = $this->extractRequestParams();
103
104 $result = [];
105
106 // Make sure session is persisted
107 $session = SessionManager::getGlobalSession();
108 $session->persist();
109
110 // Make sure it's possible to log in
111 if ( !$session->canSetUser() ) {
112 $this->getResult()->addValue( null, 'login', [
113 'result' => 'Aborted',
114 'reason' => $this->formatMessage( [
115 'api-login-fail-badsessionprovider',
116 $session->getProvider()->describe( $this->getErrorFormatter()->getLanguage() ),
117 ] )
118 ] );
119
120 return;
121 }
122
123 $authRes = false;
124 $loginType = 'N/A';
125
126 // Check login token
127 $token = $session->getToken( '', 'login' );
128 if ( !$params['token'] ) {
129 $authRes = 'NeedToken';
130 } elseif ( $token->wasNew() ) {
131 $authRes = 'Failed';
132 $message = ApiMessage::create( 'authpage-cannot-login-continue', 'sessionlost' );
133 } elseif ( !$token->match( $params['token'] ) ) {
134 $authRes = 'WrongToken';
135 }
136
137 // Try bot passwords
138 if ( $authRes === false && $this->getConfig()->get( MainConfigNames::EnableBotPasswords ) ) {
139 $botLoginData = BotPassword::canonicalizeLoginData( $params['name'] ?? '', $params['password'] ?? '' );
140 if ( $botLoginData ) {
141 $status = BotPassword::login(
142 $botLoginData[0], $botLoginData[1], $this->getRequest()
143 );
144 if ( $status->isOK() ) {
145 $session = $status->getValue();
146 $authRes = 'Success';
147 $loginType = 'BotPassword';
148 } elseif (
149 $status->hasMessage( 'login-throttled' ) ||
150 $status->hasMessage( 'botpasswords-needs-reset' ) ||
151 $status->hasMessage( 'botpasswords-locked' )
152 ) {
153 $authRes = 'Failed';
154 $message = $status->getMessage();
155 LoggerFactory::getInstance( 'authentication' )->info(
156 'BotPassword login failed: ' . $status->getWikiText( false, false, 'en' )
157 );
158 }
159 }
160 // For other errors, let's see if it's a valid non-bot login
161 }
162
163 if ( $authRes === false ) {
164 // Simplified AuthManager login, for backwards compatibility
165 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
166 $this->authManager->getAuthenticationRequests(
167 AuthManager::ACTION_LOGIN,
168 $this->getUser()
169 ),
170 [
171 'username' => $params['name'],
172 'password' => $params['password'],
173 'domain' => $params['domain'],
174 'rememberMe' => true,
175 ]
176 );
177 $res = $this->authManager->beginAuthentication( $reqs, 'null:' );
178 switch ( $res->status ) {
179 case AuthenticationResponse::PASS:
180 if ( $this->getConfig()->get( MainConfigNames::EnableBotPasswords ) ) {
181 $this->addDeprecation( 'apiwarn-deprecation-login-botpw', 'main-account-login' );
182 } else {
183 $this->addDeprecation( 'apiwarn-deprecation-login-nobotpw', 'main-account-login' );
184 }
185 $authRes = 'Success';
186 $loginType = 'AuthManager';
187 break;
188
189 case AuthenticationResponse::FAIL:
190 // Hope it's not a PreAuthenticationProvider that failed...
191 $authRes = 'Failed';
192 $message = $res->message;
193 LoggerFactory::getInstance( 'authentication' )
194 ->info( __METHOD__ . ': Authentication failed: '
195 . $message->inLanguage( 'en' )->plain() );
196 break;
197
198 default:
199 LoggerFactory::getInstance( 'authentication' )
200 ->info( __METHOD__ . ': Authentication failed due to unsupported response type: '
201 . $res->status, $this->getAuthenticationResponseLogData( $res ) );
202 $authRes = 'Aborted';
203 break;
204 }
205 }
206
207 $result['result'] = $authRes;
208 switch ( $authRes ) {
209 case 'Success':
210 $user = $session->getUser();
211
212 // Deprecated hook
213 $injected_html = '';
214 $this->getHookRunner()->onUserLoginComplete( $user, $injected_html, true );
215
216 $result['lguserid'] = $user->getId();
217 $result['lgusername'] = $user->getName();
218 break;
219
220 case 'NeedToken':
221 $result['token'] = $token->toString();
222 $this->addDeprecation( 'apiwarn-deprecation-login-token', 'action=login&!lgtoken' );
223 break;
224
225 case 'WrongToken':
226 break;
227
228 case 'Failed':
229 // @phan-suppress-next-next-line PhanTypeMismatchArgumentNullable,PhanPossiblyUndeclaredVariable
230 // message set on error
231 $result['reason'] = $this->formatMessage( $message );
232 break;
233
234 case 'Aborted':
235 $result['reason'] = $this->formatMessage(
236 $this->getConfig()->get( MainConfigNames::EnableBotPasswords )
237 ? 'api-login-fail-aborted'
238 : 'api-login-fail-aborted-nobotpw'
239 );
240 break;
241
242 // @codeCoverageIgnoreStart
243 // Unreachable
244 default:
245 ApiBase::dieDebug( __METHOD__, "Unhandled case value: {$authRes}" );
246 // @codeCoverageIgnoreEnd
247 }
248
249 $this->getResult()->addValue( null, 'login', $result );
250
251 LoggerFactory::getInstance( 'authevents' )->info( 'Login attempt', [
252 'event' => 'login',
253 'successful' => $authRes === 'Success',
254 'loginType' => $loginType,
255 'status' => $authRes,
256 ] );
257 }
258
259 public function isDeprecated() {
260 return !$this->getConfig()->get( MainConfigNames::EnableBotPasswords );
261 }
262
263 public function mustBePosted() {
264 return true;
265 }
266
267 public function isReadMode() {
268 return false;
269 }
270
271 public function isWriteMode() {
272 // (T283394) Logging in triggers some database writes, so should be marked appropriately.
273 return true;
274 }
275
276 public function getAllowedParams() {
277 return [
278 'name' => null,
279 'password' => [
280 ParamValidator::PARAM_TYPE => 'password',
281 ],
282 'domain' => null,
283 'token' => [
284 ParamValidator::PARAM_TYPE => 'string',
285 ParamValidator::PARAM_REQUIRED => false, // for BC
286 ParamValidator::PARAM_SENSITIVE => true,
287 ApiBase::PARAM_HELP_MSG => [ 'api-help-param-token', 'login' ],
288 ],
289 ];
290 }
291
292 protected function getExamplesMessages() {
293 return [
294 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
295 => 'apihelp-login-example-login',
296 ];
297 }
298
299 public function getHelpUrls() {
300 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Login';
301 }
302
303 /**
304 * Turns an AuthenticationResponse into a hash suitable for passing to Logger
305 * @param AuthenticationResponse $response
306 * @return array
307 */
308 protected function getAuthenticationResponseLogData( AuthenticationResponse $response ) {
309 $ret = [
310 'status' => $response->status,
311 ];
312 if ( $response->message ) {
313 $ret['responseMessage'] = $response->message->inLanguage( 'en' )->plain();
314 }
315 $reqs = [
316 'neededRequests' => $response->neededRequests,
317 'createRequest' => $response->createRequest,
318 'linkRequest' => $response->linkRequest,
319 ];
320 foreach ( $reqs as $k => $v ) {
321 if ( $v ) {
322 $v = is_array( $v ) ? $v : [ $v ];
323 $reqClasses = array_unique( array_map( 'get_class', $v ) );
324 sort( $reqClasses );
325 $ret[$k] = implode( ', ', $reqClasses );
326 }
327 }
328 return $ret;
329 }
330 }
331
332 /** @deprecated class alias since 1.43 */
333 class_alias( ApiLogin::class, 'ApiLogin' );