Provide some info on which case value was not handled in ApiLogin
[lhc/web/wiklou.git] / includes / api / ApiLogin.php
1 <?php
2
3 /*
4 * Created on Sep 19, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006-2007 Yuri Astrakhan <Firstname><Lastname>@gmail.com,
9 * Daniel Cannon (cannon dot danielc at gmail dot com)
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * http://www.gnu.org/copyleft/gpl.html
25 */
26
27 if (!defined('MEDIAWIKI')) {
28 // Eclipse helper - will be ignored in production
29 require_once ('ApiBase.php');
30 }
31
32 /**
33 * Unit to authenticate log-in attempts to the current wiki.
34 *
35 * @ingroup API
36 */
37 class ApiLogin extends ApiBase {
38
39 /**
40 * Time (in seconds) a user must wait after submitting
41 * a bad login (will be multiplied by the THROTTLE_FACTOR for each bad attempt)
42 */
43 const THROTTLE_TIME = 5;
44
45 /**
46 * The factor by which the wait-time in between authentication
47 * attempts is increased every failed attempt.
48 */
49 const THROTTLE_FACTOR = 2;
50
51 /**
52 * The maximum number of failed logins after which the wait increase stops.
53 */
54 const THOTTLE_MAX_COUNT = 10;
55
56 public function __construct($main, $action) {
57 parent :: __construct($main, $action, 'lg');
58 }
59
60 /**
61 * Executes the log-in attempt using the parameters passed. If
62 * the log-in succeeeds, it attaches a cookie to the session
63 * and outputs the user id, username, and session token. If a
64 * log-in fails, as the result of a bad password, a nonexistant
65 * user, or any other reason, the host is cached with an expiry
66 * and no log-in attempts will be accepted until that expiry
67 * is reached. The expiry is $this->mLoginThrottle.
68 *
69 * @access public
70 */
71 public function execute() {
72 $name = $password = $domain = null;
73 extract($this->extractRequestParams());
74
75 $result = array ();
76
77 // Make sure noone is trying to guess the password brut-force
78 $nextLoginIn = $this->getNextLoginTimeout();
79 if ($nextLoginIn > 0) {
80 $result['result'] = 'NeedToWait';
81 $result['details'] = "Please wait $nextLoginIn seconds before next log-in attempt";
82 $result['wait'] = $nextLoginIn;
83 $this->getResult()->addValue(null, 'login', $result);
84 return;
85 }
86
87 $params = new FauxRequest(array (
88 'wpName' => $name,
89 'wpPassword' => $password,
90 'wpDomain' => $domain,
91 'wpRemember' => ''
92 ));
93
94 // Init session if necessary
95 if( session_id() == '' ) {
96 wfSetupSession();
97 }
98
99 $loginForm = new LoginForm($params);
100 switch ($authRes = $loginForm->authenticateUserData()) {
101 case LoginForm :: SUCCESS :
102 global $wgUser, $wgCookiePrefix;
103
104 $wgUser->setOption('rememberpassword', 1);
105 $wgUser->setCookies();
106
107 // Run hooks. FIXME: split back and frontend from this hook.
108 // FIXME: This hook should be placed in the backend
109 $injected_html = '';
110 wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
111
112 $result['result'] = 'Success';
113 $result['lguserid'] = $wgUser->getId();
114 $result['lgusername'] = $wgUser->getName();
115 $result['lgtoken'] = $wgUser->getToken();
116 $result['cookieprefix'] = $wgCookiePrefix;
117 $result['sessionid'] = session_id();
118 break;
119
120 case LoginForm :: NO_NAME :
121 $result['result'] = 'NoName';
122 break;
123 case LoginForm :: ILLEGAL :
124 $result['result'] = 'Illegal';
125 break;
126 case LoginForm :: WRONG_PLUGIN_PASS :
127 $result['result'] = 'WrongPluginPass';
128 break;
129 case LoginForm :: NOT_EXISTS :
130 $result['result'] = 'NotExists';
131 break;
132 case LoginForm :: WRONG_PASS :
133 $result['result'] = 'WrongPass';
134 break;
135 case LoginForm :: EMPTY_PASS :
136 $result['result'] = 'EmptyPass';
137 break;
138 case LoginForm :: CREATE_BLOCKED :
139 $result['result'] = 'CreateBlocked';
140 $result['details'] = 'Your IP address is blocked from account creation';
141 break;
142 case LoginForm :: THROTTLED :
143 $result['result'] = 'Throttled';
144 break;
145 default :
146 ApiBase :: dieDebug(__METHOD__, "Unhandled case value: {$authRes}");
147 }
148
149 if ($result['result'] != 'Success' && !isset( $result['details'] ) ) {
150 $delay = $this->cacheBadLogin();
151 $result['wait'] = $delay;
152 $result['details'] = "Please wait " . $delay . " seconds before next log-in attempt";
153 }
154 // if we were allowed to try to login, memcache is fine
155
156 $this->getResult()->addValue(null, 'login', $result);
157 }
158
159
160 /**
161 * Caches a bad-login attempt associated with the host and with an
162 * expiry of $this->mLoginThrottle. These are cached by a key
163 * separate from that used by the captcha system--as such, logging
164 * in through the standard interface will get you a legal session
165 * and cookies to prove it, but will not remove this entry.
166 *
167 * Returns the number of seconds until next login attempt will be allowed.
168 *
169 * @access private
170 */
171 private function cacheBadLogin() {
172 global $wgMemc;
173
174 $key = $this->getMemCacheKey();
175 $val = $wgMemc->get( $key );
176
177 $val['lastReqTime'] = time();
178 if (!isset($val['count'])) {
179 $val['count'] = 1;
180 } else {
181 $val['count'] = 1 + $val['count'];
182 }
183
184 $delay = ApiLogin::calculateDelay($val['count']);
185
186 $wgMemc->delete($key);
187 // Cache expiration should be the maximum timeout - to prevent a "try and wait" attack
188 $wgMemc->add( $key, $val, ApiLogin::calculateDelay(ApiLogin::THOTTLE_MAX_COUNT) );
189
190 return $delay;
191 }
192
193 /**
194 * How much time the client must wait before it will be
195 * allowed to try to log-in next.
196 * The return value is 0 if no wait is required.
197 */
198 private function getNextLoginTimeout() {
199 global $wgMemc;
200
201 $val = $wgMemc->get($this->getMemCacheKey());
202
203 $elapse = (time() - $val['lastReqTime']); // in seconds
204 $canRetryIn = ApiLogin::calculateDelay($val['count']) - $elapse;
205
206 return $canRetryIn < 0 ? 0 : $canRetryIn;
207 }
208
209 /**
210 * Based on the number of previously attempted logins, returns
211 * the delay (in seconds) when the next login attempt will be allowed.
212 */
213 private static function calculateDelay($count) {
214 // Defensive programming
215 $count = intval($count);
216 $count = $count < 1 ? 1 : $count;
217 $count = $count > self::THOTTLE_MAX_COUNT ? self::THOTTLE_MAX_COUNT : $count;
218
219 return self::THROTTLE_TIME + self::THROTTLE_TIME * ($count - 1) * self::THROTTLE_FACTOR;
220 }
221
222 /**
223 * Internal cache key for badlogin checks. Robbed from the
224 * ConfirmEdit extension and modified to use a key unique to the
225 * API login.3
226 *
227 * @return string
228 * @access private
229 */
230 private function getMemCacheKey() {
231 return wfMemcKey( 'apilogin', 'badlogin', 'ip', wfGetIP() );
232 }
233
234 public function mustBePosted() { return true; }
235
236 public function getAllowedParams() {
237 return array (
238 'name' => null,
239 'password' => null,
240 'domain' => null
241 );
242 }
243
244 public function getParamDescription() {
245 return array (
246 'name' => 'User Name',
247 'password' => 'Password',
248 'domain' => 'Domain (optional)'
249 );
250 }
251
252 public function getDescription() {
253 return array (
254 'This module is used to login and get the authentication tokens. ',
255 'In the event of a successful log-in, a cookie will be attached',
256 'to your session. In the event of a failed log-in, you will not ',
257 'be able to attempt another log-in through this method for 5 seconds.',
258 'This is to prevent password guessing by automated password crackers.'
259 );
260 }
261
262 protected function getExamples() {
263 return array(
264 'api.php?action=login&lgname=user&lgpassword=password'
265 );
266 }
267
268 public function getVersion() {
269 return __CLASS__ . ': $Id$';
270 }
271 }