8578a61384eb4552f3e0282a454b1963ab4c6336
[platal.git] / classes / xorgsession.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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 *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class XorgSession extends PlSession
23 {
24 const INVALID_USER = -2;
25 const NO_COOKIE = -1;
26 const COOKIE_SUCCESS = 0;
27 const INVALID_COOKIE = 1;
28
29 public function __construct()
30 {
31 parent::__construct();
32 }
33
34 public function startAvailableAuth()
35 {
36 if (!S::logged()) {
37 switch ($this->tryCookie()) {
38 case self::COOKIE_SUCCESS:
39 if (!$this->start(AUTH_COOKIE)) {
40 return false;
41 }
42 break;
43
44 case self::INVALID_USER:
45 case self::INVALID_COOKIE:
46 return false;
47 }
48 }
49 if ((check_ip('dangerous') && S::has('uid')) || check_account()) {
50 S::logger()->log("view_page", $_SERVER['REQUEST_URI']);
51 }
52 return true;
53 }
54
55 /** Check the cookie and set the associated uid in the auth_by_cookie session variable.
56 */
57 private function tryCookie()
58 {
59 S::kill('auth_by_cookie');
60 if (Cookie::v('access') == '' || !Cookie::has('uid')) {
61 return self::NO_COOKIE;
62 }
63
64 $res = XDB::query('SELECT uid, password
65 FROM accounts
66 WHERE uid = {?} AND state = \'active\'',
67 Cookie::i('uid'));
68 if ($res->numRows() != 0) {
69 list($uid, $password) = $res->fetchOneRow();
70 if (sha1($password) == Cookie::v('access')) {
71 S::set('auth_by_cookie', $uid);
72 return self::COOKIE_SUCCESS;
73 } else {
74 return self::INVALID_COOKIE;
75 }
76 }
77 return self::INVALID_USER;
78 }
79
80 private function checkPassword($uname, $login, $response, $login_type)
81 {
82 if ($login_type == 'alias') {
83 $res = XDB::query('SELECT a.uid, a.password
84 FROM accounts AS a
85 INNER JOIN email_source_account AS e ON (e.uid = a.uid)
86 INNER JOIN email_virtual_domains AS d ON (e.domain = d.id)
87 WHERE e.email = {?} AND d.name = {?}',
88 $login, Platal::globals()->mail->domain);
89 } else {
90 $res = XDB::query('SELECT uid, password
91 FROM accounts
92 WHERE ' . $login_type . ' = {?}',
93 $login);
94 }
95 if (list($uid, $password) = $res->fetchOneRow()) {
96 $expected_response = sha1("$uname:$password:" . S::v('challenge'));
97 /* Deprecates len(password) > 10 conversion. */
98 if ($response != $expected_response) {
99 if (!S::logged()) {
100 Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
101 } else {
102 Platal::page()->trigError('Mot de passe invalide');
103 }
104 S::logger($uid)->log('auth_fail', 'bad password');
105 return null;
106 }
107 return $uid;
108 }
109 Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
110 return null;
111 }
112
113
114 /** Check auth.
115 */
116 protected function doAuth($level)
117 {
118 global $globals;
119
120 /* Cookie authentication
121 */
122 if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
123 $this->tryCookie();
124 }
125 if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
126 if (!S::logged()) {
127 S::set('auth', AUTH_COOKIE);
128 }
129 return User::getSilentWithUID(S::i('auth_by_cookie'));
130 }
131
132
133 /* We want to do auth... we must have infos from a form.
134 */
135 if (!Post::has('username') || !Post::has('response') || !S::has('challenge')) {
136 return null;
137 }
138
139 /** We come from an authentication form.
140 */
141 if (S::suid()) {
142 $login = $uname = S::suid('uid');
143 $loginType = 'uid';
144 } else {
145 $uname = Post::v('username');
146 if (Post::s('domain') == "alias") {
147 $login = XDB::fetchOneCell('SELECT uid
148 FROM email_source_account AS e
149 INNER JOIN email_virtual_domains AS d ON (e.domain = d.id)
150 WHERE e.email = {?} AND d.name = {?}',
151 $uname, Platal::globals()->mail->alias_dom);
152 $loginType = 'uid';
153 } else if (Post::s('domain') == "ax") {
154 $login = $uname;
155 $loginType = 'hruid';
156 } else {
157 $login = $uname;
158 $loginType = is_numeric($uname) ? 'uid' : 'alias';
159 }
160 }
161
162 $uid = $this->checkPassword($uname, $login, Post::v('response'), $loginType);
163 if (!is_null($uid) && S::suid()) {
164 if (S::suid('uid') == $uid) {
165 $uid = S::i('uid');
166 } else {
167 $uid = null;
168 }
169 }
170 if (!is_null($uid)) {
171 S::set('auth', AUTH_MDP);
172 if (!S::suid()) {
173 if (Post::has('domain')) {
174 $domain = Post::v('domain', 'login');
175 if ($domain == 'alias') {
176 Cookie::set('domain', 'alias', 300);
177 } else if ($domain == 'ax') {
178 Cookie::set('domain', 'ax', 300);
179 } else {
180 Cookie::kill('domain');
181 }
182 }
183 }
184 S::kill('challenge');
185 S::logger($uid)->log('auth_ok');
186 }
187 return User::getSilentWithUID($uid);
188 }
189
190 protected function startSessionAs($user, $level)
191 {
192 if ((!is_null(S::user()) && S::user()->id() != $user->id())
193 || (S::has('uid') && S::i('uid') != $user->id())) {
194 return false;
195 } else if (S::has('uid')) {
196 return true;
197 }
198 if ($level == AUTH_SUID) {
199 S::set('auth', AUTH_MDP);
200 }
201
202 // Loads uid and hruid into the session for developement conveniance.
203 $_SESSION = array_merge($_SESSION, array('uid' => $user->id(), 'hruid' => $user->hruid, 'token' => $user->token, 'user' => $user));
204
205 // Starts the session's logger, and sets up the permanent cookie.
206 if (S::suid()) {
207 S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
208 } else {
209 S::logger()->saveLastSession();
210 Cookie::set('uid', $user->id(), 300);
211
212 if (S::i('auth_by_cookie') == $user->id() || Post::v('remember', 'false') == 'true') {
213 $this->setAccessCookie(false, S::i('auth_by_cookie') != $user->id());
214 } else {
215 $this->killAccessCookie();
216 }
217 }
218
219 // Finalizes the session setup.
220 $this->makePerms($user->perms, $user->is_admin);
221 $this->securityChecks();
222 $this->setSkin();
223 $this->updateNbNotifs();
224 check_redirect();
225
226 // We should not have to use this private data anymore
227 S::kill('auth_by_cookie');
228 return true;
229 }
230
231 private function securityChecks()
232 {
233 $mail_subject = array();
234 if (check_account()) {
235 $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
236 }
237 if (check_ip('unsafe')) {
238 $mail_subject[] = 'Une IP surveillee a tente de se connecter';
239 if (check_ip('ban')) {
240 send_warning_mail(implode(' - ', $mail_subject));
241 $this->destroy();
242 Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. '
243 . 'Merci de contacter au plus vite '
244 . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>');
245 return false;
246 }
247 }
248 if (count($mail_subject)) {
249 send_warning_mail(implode(' - ', $mail_subject));
250 }
251 }
252
253 /**
254 * The authentication schema is based on three query parameters:
255 * ?user=<hruid>&timestamp=<timestamp>&sig=<sig>
256 * where:
257 * - hruid is the hruid of the querying user
258 * - timestamp is the current UNIX timestamp, which has to be within a
259 * given distance of the server-side UNIX timestamp
260 * - sig is the HMAC of "<method>#<resource>#<payload>#<timestamp>" using
261 * a known secret of the user as the key.
262 *
263 * At the moment, the shared secret of the user is the sha1 hash of its
264 * password. This is temporary, though, until better support for tokens is
265 * implemented in plat/al.
266 * TODO(vzanotti): Switch to dedicated secrets for authentication.
267 */
268 public function apiAuth($method, $resource, $payload)
269 {
270 // Verify that the timestamp is within acceptable bounds.
271 $timestamp = Env::i('timestamp', 0);
272 if (abs($timestamp - time()) > Platal::globals()->api->timestamp_tolerance) {
273 return null;
274 }
275
276 // Retrieve the user corresponding to the forlife. Note that at the
277 // moment, other aliases are also accepted.
278 $user = User::getSilent(Env::s('user', ''));
279 if (is_null($user) || !$user->isActive()) {
280 return null;
281 }
282
283 // Determine the list of tokens associated with the user. At the moment,
284 // this is just the sha1 of the password.
285 $tokens = array($user->password());
286
287 // For each token, try to validate the signature.
288 $message = implode('#', array($method, $resource, $payload, $timestamp));
289 $signature = Env::s('sig');
290 foreach ($tokens as $token) {
291 $expected_signature = hash_hmac(
292 Platal::globals()->api->hmac_algo, $message, $token);
293 if ($signature == $expected_signature) {
294 return $user;
295 }
296 }
297
298 return null;
299 }
300
301 public function tokenAuth($login, $token)
302 {
303 $res = XDB::query('SELECT a.uid, a.hruid
304 FROM accounts AS a
305 WHERE a.token = {?} AND a.hruid = {?} AND a.state = \'active\'',
306 $token, $login);
307 if ($res->numRows() == 1) {
308 return new User(null, $res->fetchOneAssoc());
309 }
310 return null;
311 }
312
313 protected function makePerms($perm, $is_admin)
314 {
315 S::set('perms', User::makePerms($perm, $is_admin));
316 }
317
318 public function setSkin()
319 {
320 if (S::logged() && (!S::has('skin') || S::suid())) {
321 $res = XDB::query('SELECT skin_tpl
322 FROM accounts AS a
323 INNER JOIN skins AS s on (a.skin = s.id)
324 WHERE a.uid = {?} AND skin_tpl != \'\'', S::i('uid'));
325 S::set('skin', $res->fetchOneCell());
326 }
327 }
328
329 public function loggedLevel()
330 {
331 return AUTH_COOKIE;
332 }
333
334 public function sureLevel()
335 {
336 return AUTH_MDP;
337 }
338
339
340 public function updateNbNotifs()
341 {
342 require_once 'notifs.inc.php';
343 $user = S::user();
344 $n = Watch::getCount($user);
345 S::set('notifs', $n);
346 }
347
348 public function setAccessCookie($replace = false, $log = true) {
349 if (S::suid() || ($replace && !Cookie::blank('access'))) {
350 return;
351 }
352 Cookie::set('access', sha1(S::user()->password()), 300, true);
353 if ($log) {
354 S::logger()->log('cookie_on');
355 }
356 }
357
358 public function killAccessCookie($log = true) {
359 Cookie::kill('access');
360 if ($log) {
361 S::logger()->log('cookie_off');
362 }
363 }
364
365 public function killLoginFormCookies() {
366 Cookie::kill('uid');
367 Cookie::kill('domain');
368 }
369 }
370
371 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
372 ?>