Race condition.
[platal.git] / classes / xorgsession.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2008 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 public function __construct()
25 {
26 parent::__construct();
27 }
28
29 public function startAvailableAuth()
30 {
31 if (!S::logged()) {
32 $cookie = $this->tryCookie();
33 if ($cookie == 0) {
34 return $this->start(AUTH_COOKIE);
35 } else if ($cookie == 1 || $cookie == -2) {
36 return false;
37 }
38 }
39 if ((check_ip('dangerous') && S::has('uid')) || check_account()) {
40 $_SESSION['log']->log("view_page", $_SERVER['REQUEST_URI']);
41 }
42 return true;
43 }
44
45 /** Check the cookie and set the associated user_id in the auth_by_cookie session variable.
46 */
47 private function tryCookie()
48 {
49 S::kill('auth_by_cookie');
50 if (Cookie::v('ORGaccess') == '' || !Cookie::has('ORGuid')) {
51 return -1;
52 }
53
54 $res = XDB::query('SELECT user_id, password
55 FROM auth_user_md5
56 WHERE user_id = {?} AND perms IN(\'admin\', \'user\')',
57 Cookie::i('ORGuid'));
58 if ($res->numRows() != 0) {
59 list($uid, $password) = $res->fetchOneRow();
60 require_once 'secure_hash.inc.php';
61 $expected_value = hash_encrypt($password);
62 if ($expected_value == Cookie::v('ORGaccess')) {
63 S::set('auth_by_cookie', $uid);
64 return 0;
65 } else {
66 return 1;
67 }
68 }
69 return -2;
70 }
71
72 private function checkPassword($uname, $login, $response, $login_type)
73 {
74 $res = XDB::query('SELECT u.user_id, u.password
75 FROM auth_user_md5 AS u
76 INNER JOIN aliases AS a ON (a.id = u.user_id AND type != \'homonyme\')
77 WHERE a.' . $login_type . ' = {?} AND u.perms IN(\'admin\', \'user\')',
78 $login);
79 if (list($uid, $password) = $res->fetchOneRow()) {
80 require_once 'secure_hash.inc.php';
81 $expected_response = hash_encrypt("$uname:$password:" . S::v('challenge'));
82 if ($response != $expected_response) {
83 $new_password = hash_xor(Env::v('xorpass'), $password);
84 $expected_response = hash_encrypt("$uname:$new_password:" . S::v('challenge'));
85 if ($response == $expected_response) {
86 XDB::execute('UPDATE auth_user_md5
87 SET password = {?}
88 WHERE user_id = {?}',
89 $new_password, $uid);
90 }
91 }
92 if ($response != $expected_response) {
93 S::logger($uid)->log('auth_fail', 'bad password');
94 return null;
95 }
96 return $uid;
97 }
98 return null;
99 }
100
101
102 /** Check auth.
103 */
104 protected function doAuth($level)
105 {
106 global $globals;
107
108 /* Cookie authentication
109 */
110 if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
111 $this->tryCookie();
112 }
113 if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
114 if (!S::logged()) {
115 S::set('auth', AUTH_COOKIE);
116 }
117 return S::i('auth_by_cookie');
118 }
119
120
121 /* We want to do auth... we must have infos from a form.
122 */
123 if (!Post::has('username') || !Post::has('response') || !S::has('challenge')) {
124 return null;
125 }
126
127 /** We come from an authentication form.
128 */
129 if (S::has('suid')) {
130 $suid = S::v('suid');
131 $login = $uname = $suid['forlife'];
132 $redirect = false;
133 } else {
134 $uname = Env::v('username');
135
136 if (Env::v('domain') == "alias") {
137 $res = XDB::query('SELECT redirect
138 FROM virtual
139 INNER JOIN virtual_redirect USING(vid)
140 WHERE alias LIKE {?}',
141 $uname . '@' . $globals->mail->alias_dom);
142 $redirect = $res->fetchOneCell();
143 if ($redirect) {
144 $login = substr($redirect, 0, strpos($redirect, '@'));
145 } else {
146 $login = '';
147 }
148 } else {
149 $login = $uname;
150 $redirect = false;
151 }
152 }
153
154 $uid = $this->checkPassword($uname, $login, Post::v('response'), (!$redirect && preg_match('/^\d*$/', $uname)) ? 'id' : 'alias');
155 if (!is_null($uid)) {
156 S::set('auth', AUTH_MDP);
157 if (Post::has('domain')) {
158 if (($domain = Post::v('domain', 'login')) == 'alias') {
159 setcookie('ORGdomain', "alias", (time() + 25920000), '/', '', 0);
160 } else {
161 setcookie('ORGdomain', '', (time() - 3600), '/', '', 0);
162 }
163 // pour que la modification soit effective dans le reste de la page
164 $_COOKIE['ORGdomain'] = $domain;
165 }
166 S::kill('challenge');
167 S::logger($uid)->log('auth_ok');
168 }
169 return $uid;
170 }
171
172 protected function startSessionAs($uid, $level)
173 {
174 if ((!is_null(S::v('user')) && S::i('user') != $uid) || (S::has('uid') && S::i('uid') != $uid)) {
175 return false;
176 } else if (S::has('uid')) {
177 return true;
178 }
179 if ($level == -1) {
180 S::set('auth', AUTH_COOKIE);
181 }
182 unset($_SESSION['log']);
183
184 // Retrieves main user properties.
185 $res = XDB::query('SELECT u.user_id AS uid, prenom, prenom_ini, nom, nom_ini, nom_usage, perms, promo, promo_sortie,
186 matricule, password, FIND_IN_SET(\'femme\', u.flags) AS femme,
187 a.alias AS forlife, a2.alias AS bestalias,
188 q.core_mail_fmt AS mail_fmt, UNIX_TIMESTAMP(q.banana_last) AS banana_last, q.watch_last, q.core_rss_hash,
189 FIND_IN_SET(\'watch\', u.flags) AS watch_account, q.last_version, g.g_account_name IS NOT NULL AS googleapps
190 FROM auth_user_md5 AS u
191 INNER JOIN auth_user_quick AS q USING(user_id)
192 INNER JOIN aliases AS a ON (u.user_id = a.id AND a.type = \'a_vie\')
193 INNER JOIN aliases AS a2 ON (u.user_id = a2.id AND FIND_IN_SET(\'bestalias\', a2.flags))
194 LEFT JOIN gapps_accounts AS g ON (u.user_id = g.l_userid AND g.g_status = \'active\')
195 WHERE u.user_id = {?} AND u.perms IN(\'admin\', \'user\')', $uid);
196 $sess = $res->fetchOneAssoc();
197 $perms = $sess['perms'];
198 unset($sess['perms']);
199
200 // Retrieves account usage information (last login, last host).
201 $res = XDB::query('SELECT UNIX_TIMESTAMP(s.start) AS lastlogin, s.host
202 FROM logger.sessions AS s
203 WHERE s.uid = {?} AND s.suid = 0
204 ORDER BY s.start DESC
205 LIMIT 1', $uid);
206 if ($res->numRows()) {
207 $sess = array_merge($sess, $res->fetchOneAssoc());
208 }
209
210 // Loads the data into the real session.
211 $_SESSION = array_merge($_SESSION, $sess);
212
213 // Starts the session's logger, and sets up the permanent cookie.
214 if (S::has('suid')) {
215 $suid = S::v('suid');
216 $logger = S::logger($uid);
217 $logger->log("suid_start", S::v('forlife') . " by " . $suid['uid']);
218 } else {
219 $logger = S::logger($uid);
220 setcookie('ORGuid', $uid, (time() + 25920000), '/', '', 0);
221
222 if (S::i('auth_by_cookie') == $uid || Post::v('remember', 'false') == 'true') {
223 $cookie = hash_encrypt($sess['password']);
224 setcookie('ORGaccess', $cookie, (time() + 25920000), '/', '', 0);
225 if ($logger && S::i('auth_by_cookie') != $uid) {
226 $logger->log("cookie_on");
227 }
228 } else {
229 setcookie('ORGaccess', '', time() - 3600, '/', '', 0);
230 if ($logger) {
231 $logger->log("cookie_off");
232 }
233 }
234 }
235
236 // Finalizes the session setup.
237 $this->makePerms($perms);
238 $this->securityChecks();
239 $this->setSkin();
240 $this->updateNbNotifs();
241 check_redirect();
242
243 // We should not have to use this private data anymore
244 S::kill('auth_by_cookie');
245 return true;
246 }
247
248 private function securityChecks()
249 {
250 $mail_subject = array();
251 if (check_account()) {
252 $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
253 }
254 if (check_ip('unsafe')) {
255 $mail_subject[] = 'Une IP surveillee a tente de se connecter';
256 if (check_ip('ban')) {
257 send_warning_mail(implode(' - ', $mail_subject));
258 $this->destroy();
259 Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. '
260 . 'Merci de contacter au plus vite '
261 . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>');
262 return false;
263 }
264 }
265 if (count($mail_subject)) {
266 send_warning_mail(implode(' - ', $mail_subject));
267 }
268 }
269
270 public function tokenAuth($login, $token)
271 {
272 // FIXME: we broke the session here because some RSS feeds (mainly wiki feeds) require
273 // a valid nome and checks the permissions. When the PlUser object will be ready, we'll
274 // be able to return a simple 'PlUser' object here without trying to alterate the
275 // session.
276 $res = XDB::query('SELECT u.user_id AS uid, u.perms, u.nom, u.nom_usage, u.prenom, u.promo, FIND_IN_SET(\'femme\', u.flags) AS sexe
277 FROM aliases AS a
278 INNER JOIN auth_user_md5 AS u ON (a.id = u.user_id AND u.perms IN ("admin", "user"))
279 INNER JOIN auth_user_quick AS q ON (a.id = q.user_id AND q.core_rss_hash = {?})
280 WHERE a.alias = {?} AND a.type != "homonyme"', $token, $login);
281 if ($res->numRows() == 1) {
282 $sess = $res->fetchOneAssoc();
283 if (!S::has('uid')) {
284 $_SESSION = $sess;
285 $this->makePerms($sess['perms']);
286 return S::i('uid');
287 } else if (S::i('uid') == $sess['uid']) {
288 return S::i('uid');
289 } else {
290 Platal::page()->kill('Invalid state. To be fixed when hruid is ready');
291 }
292 }
293 return null;
294 }
295
296 public function makePerms($perm)
297 {
298 $flags = new PlFlagSet();
299 if ($perm == 'disabled' || $perm == 'ext') {
300 S::set('perms', $flags);
301 return;
302 }
303 $flags->addFlag(PERMS_USER);
304 if ($perm == 'admin') {
305 $flags->addFlag(PERMS_ADMIN);
306 }
307 S::set('perms', $flags);
308 }
309
310 public function setSkin()
311 {
312 global $globals;
313 if (S::logged() && (!S::has('skin') || S::has('suid'))) {
314 $uid = S::v('uid');
315 $res = XDB::query("SELECT skin_tpl
316 FROM auth_user_quick AS a
317 INNER JOIN skins AS s ON a.skin = s.id
318 WHERE user_id = {?} AND skin_tpl != ''", $uid);
319 S::set('skin', $res->fetchOneCell());
320 }
321 }
322
323 public function loggedLevel()
324 {
325 return AUTH_COOKIE;
326 }
327
328 public function sureLevel()
329 {
330 return AUTH_MDP;
331 }
332
333
334 public function updateNbNotifs()
335 {
336 require_once 'notifs.inc.php';
337 $n = select_notifs(false, S::i('uid'), S::v('watch_last'), false);
338 S::set('notifs', $n->numRows());
339 }
340 }
341
342 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
343 ?>