From: Florent Bruneau Date: Sat, 21 Jun 2008 23:21:09 +0000 (+0200) Subject: Port X.org session management to the new session format. X-Git-Tag: core/1.0.0~83 X-Git-Url: http://git.polytechnique.org/?a=commitdiff_plain;h=c0799142273fa2dc68697e71e156aaed1fef4d6e;p=platal.git Port X.org session management to the new session format. Signed-off-by: Florent Bruneau --- diff --git a/classes/platal.php b/classes/platal.php index 60c7902..aed33a8 100644 --- a/classes/platal.php +++ b/classes/platal.php @@ -38,12 +38,15 @@ class Platal public function __construct() { - global $platal, $globals, $session; + global $platal, $session, $globals; $platal =& $this; $globalclass = PL_GLOBALS_CLASS; $globals = new $globalclass(); $sessionclass = PL_SESSION_CLASS; $session = new $sessionclass(); + if (!$session->startAvailableAuth()) { + Platal::page()->trigError('Données d\'authentification invalide.'); + } $modules = func_get_args(); if (is_array($modules[0])) { @@ -61,7 +64,6 @@ class Platal $this->__hooks += $m->handlers(); } - global $globals; if ($globals->mode == '') { pl_redirect('index.html'); } @@ -256,7 +258,7 @@ class Platal if ($hook['auth'] > S::v('auth', AUTH_PUBLIC)) { if ($hook['type'] & DO_AUTH) { - if (!$session->doAuth()) { + if (!$session->start($hook['auth'])) { $this->force_login($page); } } else { @@ -270,7 +272,7 @@ class Platal $val = call_user_func_array($hook['hook'], $args); if ($val == PL_DO_AUTH) { // The handler need a better auth with the current args - if (!$session->doAuth()) { + if (!$session->start($hook['auth'])) { $this->force_login($page); } $val = call_user_func_array($hook['hook'], $args); diff --git a/classes/plsession.php b/classes/plsession.php index af3e883..add2bd3 100644 --- a/classes/plsession.php +++ b/classes/plsession.php @@ -38,8 +38,7 @@ abstract class PlSession */ public function __construct() { - session_start(); - $this->fillSession(); + $this->create(); } /** Build the session structure with system fields. @@ -60,12 +59,21 @@ abstract class PlSession session_write_close(); } + /** Create a new session + */ + private function create() + { + session_start(); + $this->fillSession(); + } + /** Kill the current session. */ public function destroy() { session_destroy(); unset($_SESSION); + $this->create(); } /** Check if the user has at least the given authentication level. @@ -86,11 +94,16 @@ abstract class PlSession */ public function start($level) { + $backup = S::i($level); if ($this->checkAuth($level)) { return true; } $user = $this->doAuth($level); - if (is_null($user) || !$this->checkAuth($level)) { + if (is_null($user)) { + return false; + } + if (!$this->checkAuth($level)) { + $this->destroy(); return false; } if ($this->startSessionAs($user, $level)) { @@ -107,6 +120,19 @@ abstract class PlSession /*** Abstract methods ***/ + /** Function that check authentication at build time of the session object. + * This is useful to perform authentication from a cookie or when coming + * back from a authentication service. + * + * This function must NOT try to launch a new authenticatioin procedure. It + * just tests if the environment contains sufficient information to start + * a user session. + * + * This function return false if informations are available but lead to an + * authentication failure (invalid cookie, invalid service return data...) + */ + abstract public function startAvailableAuth(); + /** Run the effectively authentication procedure to reach the given user. * This method must return a user object (that will be used to fill the * $_SESSION['user'] field). diff --git a/classes/s.php b/classes/s.php index bcb8975..700fdf6 100644 --- a/classes/s.php +++ b/classes/s.php @@ -60,18 +60,31 @@ class S return array_map(array('S', 'v'), $keys); } - public static function set($key, &$value) + public static function set($key, $value) { $_SESSION[$key] =& $value; } - public static function bootstrap($key, &$value) + public static function bootstrap($key, $value) { if (!S::has($key)) { S::set($key, $value); } } + public static function logger($uid) + { + if (!S::has('log')) { + if (S::has('suid')) { + $suid = S::v('suid'); + S::set('log', new PlLogger(S::v('uid'), $suid['uid'])); + } else if (S::has('suid')) { + S::set('log', new PlLogger(S::v('uid', $uid))); + } + } + return S::v('log'); + } + public static function has_perms() { global $session; diff --git a/include/platal.inc.php b/include/platal.inc.php index afeef62..bb33ca8 100644 --- a/include/platal.inc.php +++ b/include/platal.inc.php @@ -107,11 +107,12 @@ function pl_clear_errors() function pl_dump_env() { echo "
";
-    echo "\nSESSION: "; var_export($_SESSION);
-    echo "\nPOST:    "; var_export($_POST);
-    echo "\nGET:     "; var_export($_GET);
-    echo "\nCOOKIE:  "; var_export($_COOKIE);
+    echo "\nSESSION: "; var_dump($_SESSION);
+    echo "\nPOST:    "; var_dump($_POST);
+    echo "\nGET:     "; var_dump($_GET);
+    echo "\nCOOKIE:  "; var_dump($_COOKIE);
     echo "
"; + pl_print_errors(); } function pl_print_errors() @@ -122,8 +123,8 @@ function pl_print_errors() } set_error_handler('pl_error_handler', E_ALL | E_STRICT); -register_shutdown_function('pl_print_errors'); -// register_shutdown_function('pl_dump_env'); +//register_shutdown_function('pl_print_errors'); +register_shutdown_function('pl_dump_env'); /** Check if the string is utf8 */ diff --git a/include/xorg/session.inc.php b/include/xorg/session.inc.php index e9b98b7..22dd632 100644 --- a/include/xorg/session.inc.php +++ b/include/xorg/session.inc.php @@ -19,72 +19,139 @@ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ***************************************************************************/ -require_once 'xorg.misc.inc.php'; - -class XorgSession +class XorgSession extends PlSession { - public function __construct() { - XorgSession::init(); + public function __construct() + { + parent::__construct(); + S::bootstrap('perms_backup', new PlFlagSet()); } - // {{{ public static function init - - public static function init() + public function startAvailableAuth() { - S::init(); - if (!S::has('uid')) { - try_cookie(); + if (!(S::v('perms') instanceof PlFlagSet)) { + S::set('perms', S::v('perms_backup')); + } + if (!S::logged()) { + $cookie = $this->tryCookie(); + if ($cookie == 0) { + return $this->start(AUTH_COOKIE); + } else if ($cookie == 1 || $cooke == -2) { + return false; + } } if ((check_ip('dangerous') && S::has('uid')) || check_account()) { $_SESSION['log']->log("view_page", $_SERVER['REQUEST_URI']); } + return true; } - // }}} - // {{{ public static function destroy() + /** Check the cookie and set the associated user_id in the auth_by_cookie session variable. + */ + private function tryCookie() + { + S::kill('auth_by_cookie'); + if (Cookie::v('ORGaccess') == '' || !Cookie::has('ORGuid')) { + return -1; + } - public static function destroy() + $res = XDB::query('SELECT user_id, password + FROM auth_user_md5 + WHERE user_id = {?} AND perms IN(\'admin\', \'user\')', + Cookie::i('ORGuid')); + 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')) { + S::set('auth_by_cookie', $uid); + return 0; + } else { + return 1; + } + } + return -2; + } + + private function checkPassword($uname, $login, $response, $login_type) { - S::destroy(); - XorgSession::init(); + $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) { + $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); + } + } + if ($response != $expected_response) { + echo $response . '
'; + echo $expected_response . '
'; + echo $uname . '
' . $password . '
'; +// $logger = S::logger($uid); +// $logger->log('auth_fail', 'bad password'); + return null; + } + return $uid; + } + return null; } - // }}} - // {{{ public static function doAuth() - public static function doAuth($new_name = false) + /** Check auth. + */ + protected function doAuth($level) { global $globals; - if (S::identified()) { // ok, c'est bon, on n'a rien à faire - return true; + + /* Cookie authentication + */ + if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) { + $this->tryCookie(); + } + if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) { + if (!S::logged()) { + S::set('auth', AUTH_COOKIE); + } + return S::i('auth_by_cookie'); } - if (!Env::has('username') || !Env::has('response') - || !S::has('challenge')) - { - return false; + + /* We want to do auth... we must have infos from a form. + */ + if (!Env::has('username') || !Env::has('response') || !S::has('challenge')) { + return null; } - // si on vient de recevoir une identification par passwordpromptscreen.tpl - // ou passwordpromptscreenlogged.tpl + /** We come from an authentication form. + */ if (S::has('suid')) { - $suid = S::v('suid'); + $suid = S::v('suid'); $login = $uname = $suid['forlife']; $redirect = false; } 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); + $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 = ''; } } else { $login = $uname; @@ -92,97 +159,115 @@ class XorgSession } } - $field = (!$redirect && preg_match('/^\d*$/', $uname)) ? 'id' : 'alias'; - $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.$field = {?} AND u.perms IN('admin','user')", $login); - - $logger = S::v('log'); - if (list($uid, $password) = $res->fetchOneRow()) { - require_once('secure_hash.inc.php'); - $expected_response = hash_encrypt("$uname:$password:".S::v('challenge')); - // le password de la base est peut-être encore encodé en md5 - if (Env::v('response') != $expected_response) { - $new_password = hash_xor(Env::v('xorpass'), $password); - $expected_response = hash_encrypt("$uname:$new_password:".S::v('challenge')); - if (Env::v('response') == $expected_response) { - XDB::execute("UPDATE auth_user_md5 SET password = {?} WHERE user_id = {?}", - $new_password, $uid); + $logger = S::logger(); + $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 (Env::v('response') == $expected_response) { - if (Env::has('domain')) { - if (($domain = Env::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; - } + S::kill('challenge'); + if ($logger) { + $logger->log('auth_ok'); + } + } + return $uid; + } - S::kill('challenge'); + protected function startSessionAs($uid, $level) + { + if ((!is_null(S::v('user')) && S::i('user') != $uid) || (S::has('uid') && S::i('uid') != $uid)) { + return false; + } else if (S::has('uid')) { + return true; + } + if ($level == -1) { + S::set('auth', AUTH_COOKIE); + } + unset($_SESSION['log']); + $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 + 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)) + WHERE u.user_id = {?} AND u.perms IN(\'admin\', \'user\')', $uid); + $sess = $res->fetchOneAssoc(); + $perms = $sess['perms']; + unset($sess['perms']); + $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()); + } + $suid = S::v('suid'); + + if ($suid) { + $logger = S::logger(); + $logger->log("suid_start", S::v('forlife')." by {$suid['uid']}"); + $sess['suid'] = $suid; + } else { + $logger = S::logger(); + //$logger->log("connexion", Env::v('n')); + setcookie('ORGuid', $uid, (time() + 25920000), '/', '', 0); + if (Post::v('remember', 'false') == 'true') { + $cookie = hash_encrypt($sess['password']); + setcookie('ORGaccess', $cookie, (time() + 25920000), '/', '', 0); if ($logger) { - $logger->log('auth_ok'); + $logger->log("cookie_on"); } - if (!start_connexion($uid, true)) { - return false; - } - if (Env::v('remember', 'false') == 'true') { - $cookie = hash_encrypt(S::v('password')); - setcookie('ORGaccess',$cookie,(time()+25920000),'/','',0); - if ($logger) { - $logger->log("cookie_on"); - } - } else { - setcookie('ORGaccess', '', time() - 3600, '/', '', 0); - - if ($logger) { - $logger->log("cookie_off"); - } + } else { + setcookie('ORGaccess', '', time() - 3600, '/', '', 0); + if ($logger) { + $logger->log("cookie_off"); } - return true; - } elseif ($logger) { - $logger->log('auth_fail','bad password'); } - } elseif ($logger) { - $logger->log('auth_fail','bad login'); } - return false; + $_SESSION = array_merge($_SESSION, $sess); + $this->makePerms($perms); + $this->securityChecks(); + $this->setSkin(); + update_NbNotifs(); + check_redirect(); + return true; } - // }}} - // {{{ public static function doAuthCookie() - - /** Try to do a cookie-based authentication. - * - * @param page the calling page (by reference) - */ - public static function doAuthCookie() - + private function securityChecks() { - if (S::logged()) { - return true; + $mail_subject = array(); + if (check_account()) { + $mail_subject[] = 'Connexion d\'un utilisateur surveillé'; } - - if (Env::has('username') and Env::has('response')) { - return XorgSession::doAuth(); + if (check_ip('unsafe')) { + $mail_subject[] = 'Une IP surveillee a tente de se connecter'; + if (check_ip('ban')) { + send_warning_mail(implode(' - ', $mail_subject)); + $this->destroy(); + Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. ' + . 'Merci de contacter au plus vite ' + . 'support@polytechnique.org'); + return false; + } } - - if ($r = try_cookie()) { - return XorgSession::doAuth(($r > 0)); + if (count($mail_subject)) { + send_warning_mail(implode(' - ', $mail_subject)); } - - return false; } - // }}} - // {{{ public static function make_perms() - - public static function &make_perms($perm) + private function makePerms($perm) { $flags = new PlFlagSet(); if ($perm == 'disabled' || $perm == 'ext') { @@ -192,143 +277,26 @@ class XorgSession if ($perm == 'admin') { $flags->addFlag(PERMS_ADMIN); } - return $flags; + S::set('perms', $flags); + S::set('perms_backup', $flags); } - // }}} -} - -// {{{ function try_cookie() - -/** réalise la récupération de $_SESSION pour qqn avec cookie - * @return int 0 if all OK, -1 if no cookie, 1 if cookie with bad hash, - * -2 should not happen - */ -function try_cookie() -{ - if (Cookie::v('ORGaccess') == '' or !Cookie::has('ORGuid')) { - return -1; - } - - $res = @XDB::query( - "SELECT user_id,password FROM auth_user_md5 - WHERE user_id = {?} AND perms IN('admin','user')", - Cookie::i('ORGuid')); - - 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 (!start_connexion($uid, false)) { - return -3; - } - return 0; - } else { - return 1; - } - } - - return -2; -} - -// }}} -// {{{ function start_connexion() - -/** place les variables de session dépendants de auth_user_md5 - * et met à jour les dates de dernière connexion si nécessaire - * @return void - * @see controlpermanent.inc.php controlauthentication.inc.php - */ -function start_connexion ($uid, $identified) -{ - $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 - 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)) - WHERE u.user_id = {?} AND u.perms IN('admin','user')", $uid); - $sess = $res->fetchOneAssoc(); - $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()); - } - $suid = S::v('suid'); - - if ($suid) { - $logger = new PlLogger($uid, $suid['uid']); - $logger->log("suid_start", S::v('forlife')." by {$suid['uid']}"); - $sess['suid'] = $suid; - } else { - $logger = S::v('log', new PlLogger($uid)); - $logger->log("connexion", Env::v('n')); - setcookie('ORGuid', $uid, (time()+25920000), '/', '', 0); - } - - $_SESSION = array_merge($_SESSION, $sess); - $_SESSION['log'] = $logger; - $_SESSION['auth'] = ($identified ? AUTH_MDP : AUTH_COOKIE); - $_SESSION['perms'] =& XorgSession::make_perms($_SESSION['perms']); - $mail_subject = null; - if (check_account()) { - $mail_subject = "Connexion d'un utilisateur surveillé"; - } - if (check_ip('unsafe')) { - if ($mail_subject) { - $mail_subject .= ' - '; - } - $mail_subject .= "Une IP surveillee a tente de se connecter"; - if (check_ip('ban')) { - send_warning_mail($mail_subject); - $_SESSION = array(); - $_SESSION['perms'] = new PlFlagSet(); - global $page; - $newpage = false; - if (!$page) { - $page =& Platal::page(); - $newpage = true; - } - $page->trigError("Une erreur est survenue lors de la procédure d'authentification. " - ."Merci de contacter au plus vite " - ."support@polytechnique.org"); - if ($newpage) { - $page->run(); - } - return false; + 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); + S::set('skin', $res->fetchOneCell()); } } - if ($mail_subject) { - send_warning_mail($mail_subject); - } - set_skin(); - update_NbNotifs(); - check_redirect(); - return true; -} - -// }}} -function set_skin() -{ - 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 ($_SESSION['skin'] = $res->fetchOneCell()) { - return; - } + public function sureLevel() + { + return AUTH_MDP; } } diff --git a/modules/platal.php b/modules/platal.php index 2a57123..2dd4e08 100644 --- a/modules/platal.php +++ b/modules/platal.php @@ -410,13 +410,13 @@ Adresse de secours : " . Post::v('email') : "")); function handler_exit(&$page, $level = null) { + global $session; if (S::has('suid')) { $a4l = S::v('forlife'); $suid = S::v('suid'); $log = S::v('log'); $log->log("suid_stop", S::v('forlife') . " by " . $suid['forlife']); - $_SESSION = $suid; - S::kill('suid'); + $session->stopSUID(); pl_redirect('admin/user/' . $a4l); } @@ -438,8 +438,7 @@ Adresse de secours : " . Post::v('email') : "")); $ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''; $_SESSION['log']->log('deconnexion',$ref); } - - XorgSession::destroy(); + $session->destroy(); if (Get::has('redirect')) { http_redirect(rawurldecode(Get::v('redirect')));