Moving to GitHub.
[platal.git] / modules / auth.php
index 4599ab2..0d09dce 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2009 Polytechnique.org                              *
+ *  Copyright (C) 2003-2014 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -24,29 +24,26 @@ class AuthModule extends PLModule
     function handlers()
     {
         return array(
-            'groupex/donne-chall.php'
-                                => $this->make_hook('chall',      AUTH_PUBLIC),
-            'groupex/export-econfiance.php'
-                                => $this->make_hook('econf',      AUTH_PUBLIC, 'user', NO_HTTPS),
-
-            'webservices/manageurs.php'
-                                => $this->make_hook('manageurs',  AUTH_PUBLIC, 'user', NO_HTTPS),
-
-            'auth-redirect.php' => $this->make_hook('redirect',   AUTH_COOKIE),
-            'auth-groupex.php'  => $this->make_hook('groupex_old',    AUTH_COOKIE),
-            'auth-groupex'      => $this->make_hook('groupex',    AUTH_COOKIE),
-            'admin/auth-groupes-x'         => $this->make_hook('admin_authgroupesx', AUTH_MDP, 'admin'),
+            'groupex/donne-chall.php'       => $this->make_hook('chall',              AUTH_PUBLIC),
+            'groupex/export-econfiance.php' => $this->make_hook('econf',              AUTH_PUBLIC, 'user', NO_HTTPS),
+
+            'webservices/manageurs.php'     => $this->make_hook('manageurs',          AUTH_PUBLIC, 'user', NO_HTTPS),
+
+            'auth-redirect.php'             => $this->make_hook('redirect',           AUTH_COOKIE, 'user'),
+            'auth-groupex.php'              => $this->make_hook('groupex_old',        AUTH_COOKIE, ''),
+            'auth-groupex'                  => $this->make_hook('groupex',            AUTH_PUBLIC, ''),
+            'admin/auth-groupes-x'          => $this->make_hook('admin_authgroupesx', AUTH_PASSWD, 'admin'),
         );
     }
 
-    function handler_chall(&$page)
+    function handler_chall($page)
     {
         $_SESSION["chall"] = uniqid(rand(), 1);
         echo $_SESSION["chall"] . "\n" . session_id();
         exit;
     }
 
-    function handler_econf(&$page)
+    function handler_econf($page)
     {
         global $globals;
 
@@ -54,7 +51,7 @@ class AuthModule extends PLModule
 
         $res = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<membres>\n\n";
 
-        if (S::v('chall') && $_GET['PASS'] == md5(S::v('chall').$cle)) {
+        if (S::v('chall') && Get::s('PASS') == md5(S::v('chall').$cle)) {
             $list = new MMList(User::getWithUID(10154), "x-econfiance.polytechnique.org");
             $members = $list->get_members('membres');
             if (is_array($members)) {
@@ -73,13 +70,13 @@ class AuthModule extends PLModule
             }
             $res .= "</membres>\n\n";
 
-            header('Content-Type: text/xml; charset="UTF-8"');
+            pl_content_headers("text/xml");
             echo $res;
         }
         exit;
     }
 
-    function handler_manageurs(&$page)
+    function handler_manageurs($page)
     {
         global $globals;
 
@@ -94,7 +91,7 @@ class AuthModule extends PLModule
 
             $request  = @$GLOBALS['HTTP_RAW_POST_DATA'];
             $response = xmlrpc_server_call_method($server, $request, null);
-            header('Content-Type: text/xml');
+            pl_content_headers("text/xml");
             print $response;
             xmlrpc_server_destroy($server);
         }
@@ -102,71 +99,168 @@ class AuthModule extends PLModule
         exit;
     }
 
-    function handler_redirect(&$page)
+    function handler_redirect($page)
     {
         http_redirect(Env::v('dest', '/'));
     }
 
-    function handler_groupex_old(&$page)
+    function handler_groupex_old($page)
     {
         return $this->handler_groupex($page, 'iso-8859-1');
     }
 
-    function handler_groupex(&$page, $charset = 'utf8')
+    /** Handles the 'auth-groupe-x' authentication.
+     * Expects the following GET parameters:
+     * - pass: the 'password' for the authentication
+     * - challenge: the authentication challenge
+     * - url: the return URL
+     * - session: the remote PHP session ID
+     */
+    function handler_groupex($page, $charset = 'utf8')
     {
+        $ext_url = urldecode(Get::s('url'));
+
+        if (!S::logged()) {
+            $page->assign('external_auth', true);
+            $page->assign('ext_url', $ext_url);
+            $page->setTitle('Authentification');
+            $page->setDefaultSkin('group_login');
+
+            if (Get::has('group')) {
+                $res = XDB::query('SELECT  nom
+                                     FROM  groups
+                                    WHERE  diminutif = {?}', Get::s('group'));
+                $page->assign('group', $res->fetchOneCell());
+            } else {
+                $page->assign('group', null);
+            }
+            // Add a P3P header for compatibility with IE in iFrames (http://www.w3.org/TR/P3P11/#compact_policies)
+            header('P3P: CP="CAO COR CURa ADMa DEVa OUR IND PHY ONL COM NAV DEM CNT STA PRE"');
+            return PL_DO_AUTH;
+        }
+
+        if (!S::user()->checkPerms('groups')) {
+            return PL_FORBIDDEN;
+        }
+
         $this->load('auth.inc.php');
-        $page->assign('referer', true);
 
-        $gpex_pass = $_GET["pass"];
-        $gpex_url  = urldecode($_GET["url"]);
-        if (strpos($gpex_url, '?') === false) {
-            $gpex_url .= "?PHPSESSID=" . $_GET["session"];
-        } else {
-            $gpex_url .= "&PHPSESSID=" . $_GET["session"];
+        $gpex_pass = Get::s('pass');
+        if (Get::has('session')) {
+            if (strpos($ext_url, '?') === false) {
+                $ext_url .= "?PHPSESSID=" . Get::s('session');
+            } else {
+                $ext_url .= "&PHPSESSID=" . Get::s('session');
+            }
         }
 
-        /* a-t-on besoin d'ajouter le http:// ? */
-        if (!preg_match("/^(http|https):\/\/.*/",$gpex_url)) {
-            $gpex_url = "http://$gpex_url";
+        // Normalize the return URL.
+        if (!preg_match("/^(http|https):\/\/.*/",$ext_url)) {
+            $ext_url = "http://$ext_url";
         }
-        $gpex_challenge = $_GET["challenge"];
+        $gpex_challenge = Get::s('challenge');
 
-        // mise à jour de l'heure et de la machine de dernier login sauf quand on est en suid
+        // Update the last login information (unless the user is in SUID).
         $uid = S::i('uid');
         if (!S::suid()) {
             global $platal;
-            S::logger($uid)->log('connexion_auth_ext', $platal->path);
+            S::logger($uid)->log('connexion_auth_ext', $platal->path.' '.urldecode($_GET['url']));
         }
 
-        /* on parcourt les entrees de groupes_auth */
-        $res = XDB::iterRow('SELECT privkey, name, datafields, returnurls FROM groupesx_auth');
+        if (Get::has('group')) {
+            $req_group_id = XDB::fetchOneCell('SELECT  id
+                                                 FROM  groups
+                                                WHERE  diminutif = {?}',
+                                              Get::s('group'));
+        } else {
+            $req_group_id = null;
+        }
+
+        // Iterate over the auth token to find which one did sign the request.
+        $res = XDB::iterRow(
+            'SELECT  ga.privkey, ga.name, ga.datafields, ga.returnurls,
+                     ga.group_id, ga.flags, g.nom
+               FROM  group_auth AS ga
+          LEFT JOIN  groups AS g ON (g.id = ga.group_id)');
 
-        while (list($privkey,$name,$datafields,$returnurls) = $res->next()) {
+        while (list($privkey, $name, $datafields, $returnurls, $group_id, $group_flags, $group_name) = $res->next()) {
             if (md5($gpex_challenge.$privkey) == $gpex_pass) {
                 $returnurls = trim($returnurls);
-                if (empty($returnurls) || @preg_match($returnurls, $gpex_url)) {
-                    $returl = $gpex_url . gpex_make_params($gpex_challenge, $privkey, $datafields, $charset);
+                // We check that the return url matches a per-key regexp to prevent
+                // replay attacks (more exactly to force replay attacks to redirect
+                // the user to the real GroupeX website, which defeats the attack).
+                if (empty($returnurls) || @preg_match($returnurls, $ext_url)) {
+                    $returl = $ext_url . gpex_make_params($gpex_challenge, $privkey, $datafields, $charset);
+                    XDB::execute('UPDATE  group_auth
+                                     SET  last_used = DATE(NOW())
+                                   WHERE  name = {?}',
+                                 $name);
+
+                    // Two conditions control access to the return URL:
+                    // - If that URL is attached to a group:
+                    //   - If the user belongs to the group, OK
+                    //   - If the user is 'xnet' and doesn't belong, NOK
+                    //   - If the user is not 'xnet' and the group is not 'strict', OK
+                    //   - If the user is not 'xnet' and the group is 'strict', NOK
+                    // - Otherwise, all but 'xnet' accounts may access the URL.
+                    $user_is_xnet = S::user()->type == 'xnet';
+                    $group_flags = new PlFlagSet($group_flags);
+
+                    // If this key is not attached to a group, but a group was
+                    // requested (e.g query from wiki / blogs / ...), use the
+                    // requested group_id.
+                    if (!$group_id && $req_group_id) {
+                        $group_id = $req_group_id;
+                    }
+
+                    if ($group_id) {
+                        // Check group permissions
+                        $is_member = XDB::fetchOneCell('SELECT  COUNT(*)
+                                                          FROM  group_members
+                                                         WHERE  uid = {?} AND asso_id = {?}',
+                                                         S::user()->id(), $group_id);
+                        if (!$is_member && ($user_is_xnet || $group_flags->hasFlag('group_only'))) {
+                            $page->kill("Le site demandé est réservé aux membres du groupe $group_name.");
+                        }
+
+                    } else if ($user_is_xnet && !$group_flags->hasFlag('allow_xnet')) {
+                        $page->kill("Le site demandé est réservé aux polytechniciens.");
+                    }
+
+                    // If we logged in specifically for this 'external_auth' request
+                    // and didn't want to "keep access to services", we kill the session
+                    // just before returning.
+                    // See classes/xorgsession.php:startSessionAs
+                    if (S::b('external_auth_exit')) {
+                        S::logger()->log('decconnexion', @$_SERVER['HTTP_REFERER']);
+                        Platal::session()->killAccessCookie();
+                        Platal::session()->destroy();
+                    }
                     http_redirect($returl);
+                } else if (S::admin()) {
+                    $page->kill("La requête d'authentification a échoué (url de retour invalide).");
                 }
             }
         }
 
-        /* si on n'a pas trouvé, on renvoit sur x.org */
-        http_redirect('https://www.polytechnique.org/');
+        // Otherwise (if no valid request was found, or if the return URL is not
+        // acceptable), the user is redirected back to our homepage.
+        pl_redirect('/');
     }
 
-    function handler_admin_authgroupesx(&$page, $action = 'list', $id = null)
+    function handler_admin_authgroupesx($page, $action = 'list', $id = null)
     {
         $page->setTitle('Administration - Auth groupes X');
         $page->assign('title', 'Gestion de l\'authentification centralisée');
-        $table_editor = new PLTableEditor('admin/auth-groupes-x','groupesx_auth','id');
+        $table_editor = new PLTableEditor('admin/auth-groupes-x','group_auth','id');
         $table_editor->describe('name','nom',true);
-        $table_editor->describe('privkey','clé privée',false);
+        $table_editor->describe('privkey','clé privée',false, true);
         $table_editor->describe('datafields','champs renvoyés',true);
         $table_editor->describe('returnurls','urls de retour',true);
+        $table_editor->describe('last_used', 'dernière utilisation', true);
         $table_editor->apply($page, $action, $id);
     }
 }
 
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
 ?>