<?php
/***************************************************************************
- * Copyright (C) 2003-2008 Polytechnique.org *
+ * Copyright (C) 2003-2011 Polytechnique.org *
* http://opensource.polytechnique.org/ *
* *
* This program is free software; you can redistribute it and/or modify *
class XorgSession extends PlSession
{
+ const INVALID_USER = -2;
+ const NO_COOKIE = -1;
+ const COOKIE_SUCCESS = 0;
+ const INVALID_COOKIE = 1;
+
public function __construct()
{
parent::__construct();
public function startAvailableAuth()
{
if (!S::logged()) {
- $cookie = $this->tryCookie();
- if ($cookie == 0) {
- return $this->start(AUTH_COOKIE);
- } else if ($cookie == 1 || $cookie == -2) {
+ switch ($this->tryCookie()) {
+ case self::COOKIE_SUCCESS:
+ if (!$this->start(AUTH_COOKIE)) {
+ return false;
+ }
+ break;
+
+ case self::INVALID_USER:
+ case self::INVALID_COOKIE:
return false;
}
}
if ((check_ip('dangerous') && S::has('uid')) || check_account()) {
- $_SESSION['log']->log("view_page", $_SERVER['REQUEST_URI']);
+ S::logger()->log("view_page", $_SERVER['REQUEST_URI']);
}
return true;
}
- /** Check the cookie and set the associated user_id in the auth_by_cookie session variable.
+ /** Check the cookie and set the associated uid in the auth_by_cookie session variable.
*/
private function tryCookie()
{
S::kill('auth_by_cookie');
- if (Cookie::v('ORGaccess') == '' || !Cookie::has('ORGuid')) {
- return -1;
+ if (Cookie::v('access') == '' || !Cookie::has('uid')) {
+ return self::NO_COOKIE;
}
- $res = XDB::query('SELECT user_id, password
- FROM auth_user_md5
- WHERE user_id = {?} AND perms IN(\'admin\', \'user\')',
- Cookie::i('ORGuid'));
+ $res = XDB::query('SELECT uid, password
+ FROM accounts
+ WHERE uid = {?} AND state = \'active\'',
+ Cookie::i('uid'));
if ($res->numRows() != 0) {
list($uid, $password) = $res->fetchOneRow();
- require_once 'secure_hash.inc.php';
- $expected_value = hash_encrypt($password);
- if ($expected_value == Cookie::v('ORGaccess')) {
+ if (sha1($password) == Cookie::v('access')) {
S::set('auth_by_cookie', $uid);
- return 0;
+ return self::COOKIE_SUCCESS;
} else {
- return 1;
+ return self::INVALID_COOKIE;
}
}
- return -2;
+ return self::INVALID_USER;
}
- private function checkPassword($uname, $login, $response, $login_type)
+ const TEXT_INVALID_LOGIN = "Mot de passe ou nom d'utilisateur invalide";
+ const TEXT_INVALID_PASS = "Mot de passe invalide";
+
+ private function checkPassword($login, User $user, $response)
{
- $res = XDB::query('SELECT u.user_id, u.password
- FROM auth_user_md5 AS u
- INNER JOIN aliases AS a ON (a.id = u.user_id AND type != \'homonyme\')
- WHERE a.' . $login_type . ' = {?} AND u.perms IN(\'admin\', \'user\')',
- $login);
- if (list($uid, $password) = $res->fetchOneRow()) {
- require_once 'secure_hash.inc.php';
- $expected_response = hash_encrypt("$uname:$password:" . S::v('challenge'));
- if ($response != $expected_response && Env::has('xorpass')
- && !preg_match('/^0*$/', Env::v('xorpass'))) {
- $new_password = hash_xor(Env::v('xorpass'), $password);
- $expected_response = hash_encrypt("$uname:$new_password:" . S::v('challenge'));
- if ($response == $expected_response) {
- XDB::execute('UPDATE auth_user_md5
- SET password = {?}
- WHERE user_id = {?}',
- $new_password, $uid);
-
- // Update the GoogleApps password as well, if required.
- global $globals;
- if ($globals->mailstorage->googleapps_domain) {
- require_once 'googleapps.inc.php';
- $account = new GoogleAppsAccount($uid);
- if ($account->active() && $account->sync_password) {
- $account->set_password($new_password);
- }
- }
- }
- }
+ if ($user === null) {
+ Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
+ return false;
+ } else {
+ $password = $user->password();
+ $expected_response = sha1("$login:$password:" . S::v('challenge'));
+ /* Deprecates len(password) > 10 conversion. */
if ($response != $expected_response) {
+ if (!S::logged()) {
+ Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
+ } else {
+ Platal::page()->trigError(self::TEXT_INVALID_PASS);
+ }
S::logger($uid)->log('auth_fail', 'bad password');
- return null;
+ return false;
}
- return $uid;
+ return true;
}
- return null;
}
if (!S::logged()) {
S::set('auth', AUTH_COOKIE);
}
- return S::i('auth_by_cookie');
+ return User::getSilentWithUID(S::i('auth_by_cookie'));
}
/** We come from an authentication form.
*/
- if (S::has('suid')) {
- $suid = S::v('suid');
- $login = $uname = $suid['forlife'];
- $redirect = false;
+ if (S::suid()) {
+ $login = S::suid('uid');
} else {
- $uname = Env::v('username');
-
- if (Env::v('domain') == "alias") {
- $res = XDB::query('SELECT redirect
- FROM virtual
- INNER JOIN virtual_redirect USING(vid)
- WHERE alias LIKE {?}',
- $uname . '@' . $globals->mail->alias_dom);
- $redirect = $res->fetchOneCell();
- if ($redirect) {
- $login = substr($redirect, 0, strpos($redirect, '@'));
- } else {
- $login = '';
- }
+ $login = Post::v('username');
+ }
+
+ $user = User::getSilent($login);
+
+ if (is_null($user)) {
+ Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
+ $success = false;
+ } else {
+ if (S::suid()) {
+ $success = (S::suid('uid') == $user->id());
} else {
- $login = $uname;
- $redirect = false;
+ $success = $this->checkPassword($login, $user, Post::v('response'));
}
}
- $uid = $this->checkPassword($uname, $login, Post::v('response'), (!$redirect && preg_match('/^\d*$/', $uname)) ? 'id' : 'alias');
- if (!is_null($uid)) {
- S::set('auth', AUTH_MDP);
- if (Post::has('domain')) {
- if (($domain = Post::v('domain', 'login')) == 'alias') {
- setcookie('ORGdomain', "alias", (time() + 25920000), '/', '', 0);
- } else {
- setcookie('ORGdomain', '', (time() - 3600), '/', '', 0);
- }
- // pour que la modification soit effective dans le reste de la page
- $_COOKIE['ORGdomain'] = $domain;
- }
+ if ($success) {
+ S::set('auth', AUTH_PASSWD);
S::kill('challenge');
- S::logger($uid)->log('auth_ok');
+ S::logger($user->id())->log('auth_ok');
}
- return $uid;
+ return $user;
}
- protected function startSessionAs($uid, $level)
+ protected function startSessionAs($user, $level)
{
- if ((!is_null(S::v('user')) && S::i('user') != $uid) || (S::has('uid') && S::i('uid') != $uid)) {
+ if ((!is_null(S::user()) && S::user()->id() != $user->id())
+ || (S::has('uid') && S::i('uid') != $user->id())) {
return false;
} else if (S::has('uid')) {
return true;
}
- if ($level == -1) {
- S::set('auth', AUTH_COOKIE);
- }
- unset($_SESSION['log']);
-
- // Retrieves main user properties.
- $res = XDB::query('SELECT u.user_id AS uid, prenom, prenom_ini, nom, nom_ini, nom_usage, perms, promo, promo_sortie,
- matricule, password, FIND_IN_SET(\'femme\', u.flags) AS femme,
- a.alias AS forlife, a2.alias AS bestalias,
- q.core_mail_fmt AS mail_fmt, UNIX_TIMESTAMP(q.banana_last) AS banana_last, q.watch_last, q.core_rss_hash,
- FIND_IN_SET(\'watch\', u.flags) AS watch_account, q.last_version, g.g_account_name IS NOT NULL AS googleapps
- FROM auth_user_md5 AS u
- INNER JOIN auth_user_quick AS q USING(user_id)
- INNER JOIN aliases AS a ON (u.user_id = a.id AND a.type = \'a_vie\')
- INNER JOIN aliases AS a2 ON (u.user_id = a2.id AND FIND_IN_SET(\'bestalias\', a2.flags))
- LEFT JOIN gapps_accounts AS g ON (u.user_id = g.l_userid AND g.g_status = \'active\')
- WHERE u.user_id = {?} AND u.perms IN(\'admin\', \'user\')', $uid);
- $sess = $res->fetchOneAssoc();
- $perms = $sess['perms'];
- unset($sess['perms']);
-
- // Retrieves account usage information (last login, last host).
- $res = XDB::query('SELECT UNIX_TIMESTAMP(s.start) AS lastlogin, s.host
- FROM logger.sessions AS s
- WHERE s.uid = {?} AND s.suid = 0
- ORDER BY s.start DESC
- LIMIT 1', $uid);
- if ($res->numRows()) {
- $sess = array_merge($sess, $res->fetchOneAssoc());
+ if ($level == AUTH_SUID) {
+ S::set('auth', AUTH_PASSWD);
}
- // Loads the data into the real session.
- $_SESSION = array_merge($_SESSION, $sess);
+ // Loads uid and hruid into the session for developement conveniance.
+ $_SESSION = array_merge($_SESSION, array('uid' => $user->id(), 'hruid' => $user->hruid, 'token' => $user->token, 'user' => $user));
// Starts the session's logger, and sets up the permanent cookie.
- if (S::has('suid')) {
- $suid = S::v('suid');
- $logger = S::logger($uid);
- $logger->log("suid_start", S::v('forlife') . " by " . $suid['uid']);
+ if (S::suid()) {
+ S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
} else {
- $logger = S::logger($uid);
- setcookie('ORGuid', $uid, (time() + 25920000), '/', '', 0);
-
- if (S::i('auth_by_cookie') == $uid || Post::v('remember', 'false') == 'true') {
- $cookie = hash_encrypt($sess['password']);
- setcookie('ORGaccess', $cookie, (time() + 25920000), '/', '', 0);
- if ($logger && S::i('auth_by_cookie') != $uid) {
- $logger->log("cookie_on");
- }
+ S::logger()->saveLastSession();
+ Cookie::set('uid', $user->id(), 300);
+
+ if (S::i('auth_by_cookie') == $user->id() || Post::v('remember', 'false') == 'true') {
+ $this->setAccessCookie(false, S::i('auth_by_cookie') != $user->id());
} else {
- setcookie('ORGaccess', '', time() - 3600, '/', '', 0);
- if ($logger) {
- $logger->log("cookie_off");
- }
+ $this->killAccessCookie();
}
}
// Finalizes the session setup.
- $this->makePerms($perms);
+ $this->makePerms($user->perms, $user->is_admin);
$this->securityChecks();
$this->setSkin();
$this->updateNbNotifs();
- check_redirect();
+ // Only check email redirection for 'internal' users.
+ if ($user->checkPerms(PERMS_USER)) {
+ check_redirect();
+ }
// We should not have to use this private data anymore
S::kill('auth_by_cookie');
}
}
- public function tokenAuth($login, $token)
+ /**
+ * The authentication schema is based on three query parameters:
+ * ?user=<hruid>×tamp=<timestamp>&sig=<sig>
+ * where:
+ * - hruid is the hruid of the querying user
+ * - timestamp is the current UNIX timestamp, which has to be within a
+ * given distance of the server-side UNIX timestamp
+ * - sig is the HMAC of "<method>#<resource>#<payload>#<timestamp>" using
+ * a known secret of the user as the key.
+ *
+ * At the moment, the shared secret of the user is the sha1 hash of its
+ * password. This is temporary, though, until better support for tokens is
+ * implemented in plat/al.
+ * TODO(vzanotti): Switch to dedicated secrets for authentication.
+ */
+ public function apiAuth($method, $resource, $payload)
{
- // FIXME: we broke the session here because some RSS feeds (mainly wiki feeds) require
- // a valid nome and checks the permissions. When the PlUser object will be ready, we'll
- // be able to return a simple 'PlUser' object here without trying to alterate the
- // session.
- $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
- FROM aliases AS a
- INNER JOIN auth_user_md5 AS u ON (a.id = u.user_id AND u.perms IN ("admin", "user"))
- INNER JOIN auth_user_quick AS q ON (a.id = q.user_id AND q.core_rss_hash = {?})
- WHERE a.alias = {?} AND a.type != "homonyme"', $token, $login);
- if ($res->numRows() == 1) {
- $sess = $res->fetchOneAssoc();
- if (!S::has('uid')) {
- $_SESSION = $sess;
- $this->makePerms($sess['perms']);
- return S::i('uid');
- } else if (S::i('uid') == $sess['uid']) {
- return S::i('uid');
- } else {
- Platal::page()->kill('Invalid state. To be fixed when hruid is ready');
+ // Verify that the timestamp is within acceptable bounds.
+ $timestamp = Env::i('timestamp', 0);
+ if (abs($timestamp - time()) > Platal::globals()->api->timestamp_tolerance) {
+ return null;
+ }
+
+ // Retrieve the user corresponding to the forlife. Note that at the
+ // moment, other aliases are also accepted.
+ $user = User::getSilent(Env::s('user', ''));
+ if (is_null($user) || !$user->isActive()) {
+ return null;
+ }
+
+ // Determine the list of tokens associated with the user. At the moment,
+ // this is just the sha1 of the password.
+ $tokens = array($user->password());
+
+ // For each token, try to validate the signature.
+ $message = implode('#', array($method, $resource, $payload, $timestamp));
+ $signature = Env::s('sig');
+ foreach ($tokens as $token) {
+ $expected_signature = hash_hmac(
+ Platal::globals()->api->hmac_algo, $message, $token);
+ if ($signature == $expected_signature) {
+ return $user;
}
}
+
return null;
}
- public function makePerms($perm)
+ public function tokenAuth($login, $token)
{
- $flags = new PlFlagSet();
- if ($perm == 'disabled' || $perm == 'ext') {
- S::set('perms', $flags);
- return;
- }
- $flags->addFlag(PERMS_USER);
- if ($perm == 'admin') {
- $flags->addFlag(PERMS_ADMIN);
+ $res = XDB::query('SELECT a.uid, a.hruid
+ FROM accounts AS a
+ WHERE a.token = {?} AND a.hruid = {?} AND a.state = \'active\'',
+ $token, $login);
+ if ($res->numRows() == 1) {
+ return new User(null, $res->fetchOneAssoc());
}
- S::set('perms', $flags);
+ return null;
+ }
+
+ protected function makePerms($perm, $is_admin)
+ {
+ S::set('perms', User::makePerms($perm, $is_admin));
}
public function setSkin()
{
- global $globals;
- if (S::logged() && (!S::has('skin') || S::has('suid'))) {
- $uid = S::v('uid');
- $res = XDB::query("SELECT skin_tpl
- FROM auth_user_quick AS a
- INNER JOIN skins AS s ON a.skin = s.id
- WHERE user_id = {?} AND skin_tpl != ''", $uid);
+ if (S::logged() && (!S::has('skin') || S::suid())) {
+ $res = XDB::query('SELECT skin_tpl
+ FROM accounts AS a
+ INNER JOIN skins AS s on (a.skin = s.id)
+ WHERE a.uid = {?} AND skin_tpl != \'\'', S::i('uid'));
S::set('skin', $res->fetchOneCell());
}
}
public function sureLevel()
{
- return AUTH_MDP;
+ return AUTH_PASSWD;
}
public function updateNbNotifs()
{
require_once 'notifs.inc.php';
- $n = select_notifs(false, S::i('uid'), S::v('watch_last'), false);
- S::set('notifs', $n->numRows());
+ $user = S::user();
+ $n = Watch::getCount($user);
+ S::set('notifs', $n);
+ }
+
+ public function setAccessCookie($replace = false, $log = true) {
+ if (S::suid() || ($replace && !Cookie::blank('access'))) {
+ return;
+ }
+ Cookie::set('access', sha1(S::user()->password()), 300, true);
+ if ($log) {
+ S::logger()->log('cookie_on');
+ }
+ }
+
+ public function killAccessCookie($log = true) {
+ Cookie::kill('access');
+ if ($log) {
+ S::logger()->log('cookie_off');
+ }
+ }
+
+ public function killLoginFormCookies() {
+ Cookie::kill('uid');
+ Cookie::kill('domain');
}
}