Moving to GitHub.
[platal.git] / classes / xorgsession.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2014 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 const TEXT_INVALID_LOGIN = "Mot de passe ou nom d'utilisateur invalide";
81 const TEXT_INVALID_PASS = "Mot de passe invalide";
82
83 private function checkPassword($login, User $user, $response)
84 {
85 if ($user === null) {
86 Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
87 return false;
88 } else {
89 $password = $user->password();
90 $expected_response = sha1("$login:$password:" . S::v('challenge'));
91 /* Deprecates len(password) > 10 conversion. */
92 if ($response != $expected_response) {
93 if (!S::logged()) {
94 Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
95 } else {
96 Platal::page()->trigError(self::TEXT_INVALID_PASS);
97 }
98 S::logger($uid)->log('auth_fail', 'bad password');
99 return false;
100 }
101 return true;
102 }
103 }
104
105
106 /** Check auth.
107 */
108 protected function doAuth($level)
109 {
110 global $globals;
111
112 /* Cookie authentication
113 */
114 if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
115 $this->tryCookie();
116 }
117 if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
118 if (!S::logged()) {
119 S::set('auth', AUTH_COOKIE);
120 }
121 return User::getSilentWithUID(S::i('auth_by_cookie'));
122 }
123
124
125 /* We want to do auth... we must have infos from a form.
126 */
127 if (!Post::has('username') || !Post::has('response') || !S::has('challenge')) {
128 return null;
129 }
130
131 /** We come from an authentication form.
132 */
133 if (S::suid()) {
134 $login = S::suid('uid');
135 } else {
136 $login = Post::v('username');
137 }
138
139 $user = User::getSilent($login);
140
141 if (is_null($user)) {
142 Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
143 $success = false;
144 } else {
145 if (S::suid()) {
146 $success = (S::suid('uid') == $user->id());
147 } else {
148 $success = $this->checkPassword($login, $user, Post::v('response'));
149 }
150 }
151
152 if ($success) {
153 S::set('auth', AUTH_PASSWD);
154 S::kill('challenge');
155 S::logger($user->id())->log('auth_ok');
156 }
157 return $user;
158 }
159
160 protected function startSessionAs($user, $level)
161 {
162 if ((!is_null(S::user()) && S::user()->id() != $user->id())
163 || (S::has('uid') && S::i('uid') != $user->id())) {
164 return false;
165 } else if (S::has('uid')) {
166 return true;
167 }
168 if ($level == AUTH_SUID) {
169 S::set('auth', AUTH_PASSWD);
170 }
171
172 // Loads uid and hruid into the session for developement conveniance.
173 $_SESSION = array_merge($_SESSION, array('uid' => $user->id(), 'hruid' => $user->hruid, 'token' => $user->token, 'user' => $user));
174
175 // Starts the session's logger, and sets up the permanent cookie.
176 if (S::suid()) {
177 S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
178 } else {
179 S::logger()->saveLastSession();
180 Cookie::set('uid', $user->id(), 300);
181
182 if (S::i('auth_by_cookie') == $user->id() || Post::v('remember', 'false') == 'true') {
183 $this->setAccessCookie(false, S::i('auth_by_cookie') != $user->id());
184 } else {
185 $this->killAccessCookie();
186
187 // If login for an external website and not activating cookie,
188 // mark that we want to disconnect once external auth checks
189 // have been performed.
190 if (Post::b('external_auth')) {
191 S::set('external_auth_exit', true);
192 }
193 }
194 }
195
196 // Finalizes the session setup.
197 $this->makePerms($user->perms, $user->is_admin);
198 $this->securityChecks();
199 $this->setSkin();
200 $this->updateNbNotifs();
201 // Only check email redirection for 'internal' users.
202 if ($user->checkPerms(PERMS_USER)) {
203 check_redirect();
204 }
205
206 // We should not have to use this private data anymore
207 S::kill('auth_by_cookie');
208 return true;
209 }
210
211 private function securityChecks()
212 {
213 $mail_subject = array();
214 if (check_account()) {
215 $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
216 }
217 if (check_ip('unsafe')) {
218 $mail_subject[] = 'Une IP surveillee a tente de se connecter';
219 if (check_ip('ban')) {
220 send_warning_mail(implode(' - ', $mail_subject));
221 $this->destroy();
222 Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. '
223 . 'Merci de contacter au plus vite '
224 . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>');
225 return false;
226 }
227 }
228 if (count($mail_subject)) {
229 send_warning_mail(implode(' - ', $mail_subject));
230 }
231 }
232
233 /**
234 * The authentication schema is based on three query parameters:
235 * ?user=<hruid>&timestamp=<timestamp>&sig=<sig>
236 * where:
237 * - hruid is the hruid of the querying user
238 * - timestamp is the current UNIX timestamp, which has to be within a
239 * given distance of the server-side UNIX timestamp
240 * - sig is the HMAC of "<method>#<resource>#<payload>#<timestamp>" using
241 * a known secret of the user as the key.
242 *
243 * At the moment, the shared secret of the user is the sha1 hash of its
244 * password. This is temporary, though, until better support for tokens is
245 * implemented in plat/al.
246 * TODO(vzanotti): Switch to dedicated secrets for authentication.
247 */
248 public function apiAuth($method, $resource, $payload)
249 {
250 // Verify that the timestamp is within acceptable bounds.
251 $timestamp = Env::i('timestamp', 0);
252 if (abs($timestamp - time()) > Platal::globals()->api->timestamp_tolerance) {
253 return null;
254 }
255
256 // Retrieve the user corresponding to the forlife. Note that at the
257 // moment, other aliases are also accepted.
258 $user = User::getSilent(Env::s('user', ''));
259 if (is_null($user) || !$user->isActive()) {
260 return null;
261 }
262
263 // Determine the list of tokens associated with the user. At the moment,
264 // this is just the sha1 of the password.
265 $tokens = array($user->password());
266
267 // For each token, try to validate the signature.
268 $message = implode('#', array($method, $resource, $payload, $timestamp));
269 $signature = Env::s('sig');
270 foreach ($tokens as $token) {
271 $expected_signature = hash_hmac(
272 Platal::globals()->api->hmac_algo, $message, $token);
273 if ($signature == $expected_signature) {
274 return $user;
275 }
276 }
277
278 return null;
279 }
280
281 public function tokenAuth($login, $token)
282 {
283 $res = XDB::query('SELECT a.uid, a.hruid
284 FROM accounts AS a
285 WHERE a.token = {?} AND a.hruid = {?} AND a.state = \'active\'',
286 $token, $login);
287 if ($res->numRows() == 1) {
288 return new User(null, $res->fetchOneAssoc());
289 }
290 return null;
291 }
292
293 protected function makePerms($perm, $is_admin)
294 {
295 S::set('perms', User::makePerms($perm, $is_admin));
296 }
297
298 public function setSkin()
299 {
300 if (S::logged() && (!S::has('skin') || S::suid())) {
301 $res = XDB::query('SELECT skin_tpl
302 FROM accounts AS a
303 INNER JOIN skins AS s on (a.skin = s.id)
304 WHERE a.uid = {?} AND skin_tpl != \'\'', S::i('uid'));
305 S::set('skin', $res->fetchOneCell());
306 }
307 }
308
309 public function loggedLevel()
310 {
311 return AUTH_COOKIE;
312 }
313
314 public function sureLevel()
315 {
316 return AUTH_PASSWD;
317 }
318
319
320 public function updateNbNotifs()
321 {
322 require_once 'notifs.inc.php';
323 $user = S::user();
324 $n = Watch::getCount($user);
325 S::set('notifs', $n);
326 }
327
328 public function setAccessCookie($replace = false, $log = true) {
329 if (S::suid() || ($replace && !Cookie::blank('access'))) {
330 return;
331 }
332 Cookie::set('access', sha1(S::user()->password()), 300, true);
333 if ($log) {
334 S::logger()->log('cookie_on');
335 }
336 }
337
338 public function killAccessCookie($log = true) {
339 Cookie::kill('access');
340 if ($log) {
341 S::logger()->log('cookie_off');
342 }
343 }
344
345 public function killLoginFormCookies() {
346 Cookie::kill('uid');
347 Cookie::kill('domain');
348 }
349 }
350
351 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
352 ?>