3 * FusionForge session management
5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2001-2002, 2009, Roland Mas
7 * Copyright 2004-2005, GForge, LLC
8 * Copyright 2013, Franck Villaume - TrivialDev
10 * Thorsten “mirabilos” Glaser <t.glaser@tarent.de>
12 * This file is part of FusionForge. FusionForge is free software;
13 * you can redistribute it and/or modify it under the terms of the
14 * GNU General Public License as published by the Free Software
15 * Foundation; either version 2 of the Licence, or (at your option)
18 * FusionForge is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 require_once $gfcommon.'include/account.php';
29 require_once $gfcommon.'include/utils.php';
30 require_once $gfcommon.'include/escapingUtils.php';
33 * A User object if user is logged in
35 * @var constant $G_SESSION
42 $session_ser = getStringFromCookie('session_ser');
45 * session_build_session_token() - Construct session token for the user
47 * @param int User_id of the logged in user
48 * @return string token value
50 function session_build_session_token($user_id) {
54 return session_build_session_cookie($user_id);
57 function session_build_session_cookie($user_id) {
58 $nonce = md5(util_randbytes());
59 $session_cookie_data = array(
61 getStringFromServer('REMOTE_ADDR'),
63 getStringFromServer('HTTP_USER_AGENT')
65 $session_cookie = "" . time();
66 foreach ($session_cookie_data as $s) {
67 /* for escaping; this is not really HTML */
68 $session_cookie .= '<' . util_html_encode($s);
70 $session_cookie_hmac = hash_hmac("sha256", $session_cookie,
71 forge_get_config('session_key'), true);
72 $session_serial_cookie = base64_encode($session_cookie) . '!' .
73 base64_encode($session_cookie_hmac);
74 return $session_serial_cookie;
78 * session_get_hash_from_token() - Get hash of session token
80 * This hash can be used as a key to identify session, e.g. in DB.
82 * @param string Value of the session token
85 function session_get_hash_from_token($session_token) {
86 return session_get_session_cookie_hash($session_token);
88 function session_get_session_cookie_hash($session_cookie) {
90 * we cannot just use the HMAC as that may be longer than
91 * the database fields, and this code used to return a
92 * string of the size of an md5(), so just md5 it
94 return md5($session_cookie);
98 * session_check_session_token() - Check that session token passed from user is ok
100 * @param string Value of the session token
101 * @return user_id if token is ok, false otherwise
103 function session_check_session_token($session_token) {
104 if ($session_token == '') {
107 return session_check_session_cookie($session_token);
109 function session_check_session_cookie($session_cookie) {
110 if (!preg_match('#^[A-Za-z0-9+/=]*![A-Za-z0-9+/=]*$#',
113 * does not match basic format, off; recommended by
114 * http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html
115 * to protect the below code from malformed strings
120 list($session_cookie, $session_cookie_hmac) = explode('!',
122 $session_cookie = base64_decode($session_cookie);
123 $session_cookie_hmac = base64_decode($session_cookie_hmac);
124 if (hash_hmac("sha256", $session_cookie,
125 forge_get_config('session_key'), true) !== $session_cookie_hmac) {
130 list($time, $user_id, $ip, $nonce, $user_agent) = explode('<', $session_cookie);
131 $user_id = util_unconvert_htmlspecialchars($user_id);
132 $ip = util_unconvert_htmlspecialchars($ip);
133 $user_agent = util_unconvert_htmlspecialchars($user_agent);
135 if (!session_check_ip($ip, getStringFromServer('REMOTE_ADDR'))) {
138 if (trim($user_agent) != getStringFromServer('HTTP_USER_AGENT')) {
141 if ((forge_get_config('session_expire') > 0) &&
142 ($time - time() >= forge_get_config('session_expire'))) {
150 * session_logout() - Log the user off the system.
152 * This function destroys object associated with the current session,
153 * making user "logged out". Deletes both user and session cookies.
158 function session_logout() {
159 plugin_hook('close_auth_session');
161 // delete both session and username cookies
162 // NB: cookies must be deleted with the same scope parameters they were set with
164 session_cookie('session_ser', '');
166 RBACEngine::getInstance()->invalidateRoleCaches();
171 * session_login_valid() - Log the user to the system.
173 * High-level function for user login. Check credentials, and if they
174 * are valid, open new session.
176 * @param string User name
177 * @param string User password (in clear text)
178 * @param bool Allow login to non-confirmed user account (only for confirmation of the very account)
179 * @return true/false, if false reason is in global $feedback
183 function session_login_valid($loginname, $passwd, $allowpending=0) {
184 global $feedback, $error_msg, $warning_msg;
186 if (!$loginname || !$passwd) {
187 $warning_msg = _('Missing Password Or Users Name');
191 $hook_params = array();
192 $hook_params['loginname'] = $loginname;
193 $hook_params['passwd'] = $passwd;
194 $result = plugin_hook("session_before_login", $hook_params);
196 // Refuse login if not all the plugins are ok.
198 if (!util_ifsetor($feedback)) {
199 $warning_msg = _('Invalid Password Or User Name');
204 return session_login_valid_dbonly($loginname, $passwd, $allowpending);
207 function session_check_credentials_in_database($loginname, $passwd, $allowpending=false) {
208 return session_login_valid_dbonly($loginname, $passwd, $allowpending);
210 function session_login_valid_dbonly($loginname, $passwd, $allowpending) {
211 global $feedback, $userstatus;
213 // Try to get the users from the database using user_id and (MD5) user_pw
214 if (forge_get_config('require_unique_email')) {
215 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE (user_name=$1 OR email=$1) AND user_pw=$2',
219 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1 AND user_pw=$2',
223 if (!$res || db_numrows($res) < 1) {
224 // No user whose MD5 passwd matches the MD5 of the provided passwd
225 // Selecting by user_name/email only
226 if (forge_get_config('require_unique_email')) {
227 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1 OR email=$1',
228 array ($loginname)) ;
230 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1',
231 array ($loginname)) ;
233 if (!$res || db_numrows($res) < 1) {
234 // No user by that name
235 $warning_msg = _('Invalid Password Or User Name');
238 // There is a user with the provided user_name/email, but the MD5 passwds do not match
239 // We'll have to try checking the (crypt) unix_pw
240 $usr = db_fetch_array($res);
241 $userstatus = $usr['status'] ;
243 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
244 // Even the (crypt) unix_pw does not patch
245 // This one has clearly typed a bad passwd
246 $warning_msg = _('Invalid Password Or User Name');
249 // User exists, (crypt) unix_pw matches
250 // Update the (MD5) user_pw and retry authentication
251 // It should work, except for status errors
252 $res = db_query_params ('UPDATE users SET user_pw=$1 WHERE user_id=$2',
255 return session_check_credentials_in_database($loginname, $passwd, $allowpending) ;
258 // If we're here, then the user has typed a password matching the (MD5) user_pw
259 // Let's check whether it also matches the (crypt) unix_pw
260 $usr = db_fetch_array($res);
262 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
263 // The (crypt) unix_pw does not match
264 if ($usr['unix_pw'] == '') {
265 // Empty unix_pw, we'll take the MD5 as authoritative
266 // Update the (crypt) unix_pw and retry authentication
267 // It should work, except for status errors
268 $res = db_query_params ('UPDATE users SET unix_pw=$1 WHERE user_id=$2',
269 array (account_genunixpw($passwd),
271 return session_check_credentials_in_database($loginname, $passwd, $allowpending) ;
273 // Invalidate (MD5) user_pw, refuse authentication
274 $res = db_query_params ('UPDATE users SET user_pw=$1 WHERE user_id=$2',
275 array ('OUT OF DATE',
277 $warning_msg =_('Invalid Password Or User Name');
282 // Yay. The provided password matches both fields in the database.
283 // Let's check the status of this user
285 // if allowpending (for verify.php) then allow
286 $userstatus=$usr['status'];
287 if ($allowpending && ($usr['status'] == 'P')) {
290 if ($usr['status'] == 'S') {
292 $warning_msg = _('Account Suspended');
295 if ($usr['status'] == 'P') {
297 $warning_msg = _('Account Pending');
300 if ($usr['status'] == 'D') {
302 $warning_msg = _('Account Deleted');
305 if ($usr['status'] != 'A') {
306 //unacceptable account flag
307 $warning_msg = _('Account Not Active');
311 // create a new session
312 session_set_new(db_result($res, 0, 'user_id'));
319 * session_check_ip() - Check 2 IP addresses for match
321 * This function checks that IP addresses match
323 * IPv4 addresses are allowed to match with some
324 * fuzz factor (within 255.255.0.0 subnet).
326 * For IPv6 addresses, no fuzz is needed since there's
327 * usually no NAT in IPv6.
329 * @param string The old IP address
330 * @param string The new IP address
334 function session_check_ip($oldip, $newip) {
335 if (strstr($oldip, ':')) {
337 if (strstr($newip, ':')) {
338 // New IP is IPv6 too
339 return ($oldip == $newip);
344 if (strstr($newip, ':')) {
348 $eoldip = explode(".", $oldip);
349 $enewip = explode(".", $newip);
351 // require same Class B subnet
352 return (($eoldip[0] == $enewip[0]) && ($eoldip[1] == $enewip[1]));
356 * session_issecure() - Check if current session is secure
361 function session_issecure() {
362 return (strtoupper(getStringFromServer('HTTPS')) == "ON");
366 * session_set_cookie() - Set a session cookie
368 * Set a cookie with default temporal scope of the current browser session
369 * and URL space of the current webserver
371 * @param string Name of cookie
372 * @param string Value of cookie
373 * @param string Domain scope (default '')
374 * @param string Expiration time in UNIX seconds (default 0)
376 function session_set_cookie($name, $value, $domain='', $expiration=0) {
377 return session_cookie($name, $value, $domain, $expiration);
379 function session_cookie($name, $value, $domain='', $expiration=0) {
380 if (php_sapi_name() == 'cli') {
384 $expiration = time() + $expiration;
386 /* evolvis: force secure (SSL-only) session cookies */
387 //$force_secure = true;
388 /* not (yet?) in FusionForge */
389 $force_secure = false;
390 if ($force_secure && !session_issecure()) {
393 if (PHP_MAJOR_VERSION < 5 || PHP_MINOR_VERSION < 2) {
394 // In PHP < 5.2, setcookie accepts at most 6 parameters
395 setcookie($name, $value, $expiration, '/', $domain, $force_secure);
397 setcookie($name, $value, $expiration, '/', $domain, $force_secure, true);
402 * session_redirect_uri() - Redirect browser
404 * @param string Absolute URI
405 * @return never returns
407 function session_redirect_uri($loc) {
408 util_save_messages();
409 sysdebug_off("Status: 301 Moved Permanently", true, 301);
410 header("Location: ${loc}", true);
411 echo "\nPlease go to ${loc} instead!\n";
416 * session_redirect() - Redirect browser within the site and exit.
418 * @param string $loc Absolute path within the site
420 function session_redirect($loc) {
421 session_redirect_uri(util_make_url($loc));
426 * session_redirect_external() - Redirect browser to a (potentially external) URL
428 * @param string Absolute URL, not necessarily within the site
429 * @return never returns
431 function session_redirect_external($url) {
432 util_save_messages();
433 header('Location: '.$url);
439 * session_redirect404() - Redirect browser to 404 error page
441 * @return never returns
443 function session_redirect404() {
444 global $HTML, $gfwww, $gfcommon;
446 header("HTTP/1.0 404 Not Found");
447 require_once $gfwww.'404.php';
453 * session_require() - DEPRECATED Convenience function to easily enforce permissions
455 * Calling page will terminate with error message if current user
458 * @param array Associative array specifying criteria
459 * @return does not return if check is failed
462 function session_require($req, $reason='') {
463 if (!session_loggedin()) {
464 exit_not_logged_in();
467 $user =& user_get_object(user_getid());
468 if (!$user->isActive()) {
470 exit_error(_('Your account is no longer active; you have been disconnected'), '');
473 if (!array_key_exists('group', $req)) {
474 exit_permission_denied($reason, '');
477 $group = group_get_object($req['group']);
478 if (!$group || !is_object($group)) {
480 } elseif ($group->isError()) {
481 exit_error($reason ? $reason : $group->getErrorMessage(), '');
484 $perm =& $group->getPermission();
485 if (!$perm || !is_object($perm) || $perm->isError()) {
486 exit_permission_denied($reason, '');
489 if (isset($req['admin_flags']) && $req['admin_flags']) {
490 if (!$perm->isAdmin()) {
491 exit_permission_denied($reason, '');
494 if (!$perm->isMember()) {
495 exit_permission_denied($reason, '');
501 * session_require_perm() - Convenience function to easily enforce permissions
503 * Calling page will terminate with error message if current user
507 function session_require_perm($section, $reference, $action=NULL, $reason='') {
508 if (!forge_check_perm($section, $reference, $action)) {
509 exit_permission_denied($reason, $section);
514 * session_require_global_perm() - Convenience function to easily enforce permissions
516 * Calling page will terminate with error message if current user
520 function session_require_global_perm($section, $action=NULL, $reason='') {
521 if (!forge_check_global_perm($section, $action)) {
523 $reason = sprintf(_('Permission denied. The %s administrators will have to grant you permission to view this page.'),
524 forge_get_config('forge_name'));
526 exit_permission_denied($reason, $section);
531 * session_require_login() - Convenience function to easily enforce permissions
533 * Calling page will terminate with error message if current user
537 function session_require_login() {
538 if (!session_loggedin()) {
539 exit_not_logged_in();
544 * session_set_new() - Setup session for the given user
546 * This function sets up SourceForge session for the given user,
547 * making one be "logged in".
549 * @param int The user ID
552 function session_set_new($user_id) {
553 $token = session_build_session_token($user_id);
555 // set session cookie
557 $cookie = session_build_session_cookie($user_id);
558 // session_cookie("session_ser", $cookie, "", forge_get_config('session_expire'));
559 // $session_ser = $cookie;
561 $res = db_query_params('SELECT count(*) as c FROM user_session
562 WHERE session_hash=$1',
563 array(($shash = session_get_session_cookie_hash($cookie))));
564 if (!$res || db_result($res, 0, 'c') < 1) {
565 db_query_params('INSERT INTO user_session
566 (session_hash,ip_addr,time,user_id)
567 VALUES ($1,$2,$3,$4)',
570 getStringFromServer('REMOTE_ADDR'),
576 // check uniqueness of the session_hash in the database
577 $res = session_getdata($user_id);
580 exit_error(db_error(), '');
581 } elseif (db_numrows($res) < 1) {
582 exit_error(_('Could not fetch user session data'), '');
584 session_set_internal($user_id, $res);
588 function session_set_internal($user_id, $res=false) {
591 $G_SESSION = user_get_object($user_id, $res);
593 $G_SESSION->setLoggedIn(true);
596 RBACEngine::getInstance()->invalidateRoleCaches();
600 * session_set_admin() - Setup session for the admin user
602 * This function sets up a session for the administrator
606 function session_set_admin() {
607 $admins = RBACEngine::getInstance()->getUsersByAllowedAction('forge_admin', -1);
608 if (count($admins) == 0) {
609 exit_error(_('No admin users ?'), '');
612 * Use the user with the lowest numerical user ID.
613 * This is to prevent complaints from real humans
614 * if the system is doing something in their stead
615 * (for example by populate_template_project.php).
616 * Usually, “admin” has the ID 101.
618 $admin_ids = array();
619 foreach ($admins as $admin) {
620 $admin_ids[] = $admin->getID();
623 session_set_new($admin_ids[0]);
627 * Private optimization function for logins - fetches user data, language, and session
630 * @param int The user ID
633 function session_getdata($user_id) {
634 return db_query_params('SELECT u.*, sl.language_id, sl.name,
635 sl.filename, sl.classname, sl.language_code,
636 t.dirname, t.fullname
637 FROM users u, supported_languages sl, themes t
638 WHERE u.language=sl.language_id
639 AND u.theme_id=t.theme_id
645 * session_set() - Re-initialize session for the logged in user
647 * This function checks that the user is logged in and if so, initialize
648 * internal session environment.
652 function session_set() {
656 // assume bad session_hash and session. If all checks work, then allow
657 // otherwise make new session
661 // pass the session_ser from cookie to the auth plugins
662 // (see AuthBuiltinPlugin::checkAuthSession() or likes)
663 // expect FORGE_AUTH_AUTHORITATIVE_ACCEPT, FORGE_AUTH_AUTHORITATIVE_REJECT or FORGE_AUTH_NOT_AUTHORITATIVE
665 $params['auth_token'] = $session_ser;
666 $params['results'] = array();
667 plugin_hook_by_reference('check_auth_session', $params);
671 foreach ($params['results'] as $p => $r) {
672 if ($r == FORGE_AUTH_AUTHORITATIVE_ACCEPT) {
674 } elseif ($r == FORGE_AUTH_AUTHORITATIVE_REJECT) {
678 if ($seen_yes && !$seen_no) {
679 // see AuthBuiltinPlugin::fetchAuthUser() or likes
680 // expect user object in results
682 $params['results'] = NULL;
683 plugin_hook_by_reference('fetch_authenticated_user', $params);
684 $user = $params['results'];
688 $params['username'] = $user->getUnixName();
689 $params['event'] = 'every-page';
690 plugin_hook('sync_account_info', $params);
692 $user->setLoggedIn(true);
698 // TODO: else... what ?
700 $re = RBACEngine::getInstance();
701 $re->invalidateRoleCaches() ;
705 * Re initializes a session, trusting a non-sufficient plugin only temporarily
707 * The checkAuthSession of the Auth plugin will have to acknowledge the 'sufficient_forced' param in 'check_auth_session' hook
708 * @param string $authpluginname
710 function session_set_for_authplugin($authpluginname) {
714 // assume bad session_hash and session. If all checks work, then allow
715 // otherwise make new session
719 // pass the session_ser from cookie to the auth plugins
720 // (see AuthBuiltinPlugin::checkAuthSession() or likes)
721 // expect FORGE_AUTH_AUTHORITATIVE_ACCEPT, FORGE_AUTH_AUTHORITATIVE_REJECT or FORGE_AUTH_NOT_AUTHORITATIVE
723 $params['sufficient_forced'] = $authpluginname;
725 $params['auth_token'] = $session_ser;
726 $params['results'] = array();
728 plugin_hook_by_reference('check_auth_session', $params);
731 foreach ($params['results'] as $p => $r) {
732 if ($r == FORGE_AUTH_AUTHORITATIVE_ACCEPT) {
739 // see AuthBuiltinPlugin::fetchAuthUser() or likes
740 // expect user object in results
742 $params['results'] = NULL;
744 plugin_hook_by_reference('fetch_authenticated_user', $params);
746 $user = $params['results'];
750 $params['username'] = $user->getUnixName();
751 $params['event'] = 'every-page';
752 plugin_hook('sync_account_info', $params);
754 $user->setLoggedIn(true);echo "user:".$user->getUnixName();
761 // TODO: else... what ?
763 $re = RBACEngine::getInstance();
764 //print_r($re->getGlobalRoles());
765 //print_r($re->getPublicRoles());
766 $re->invalidateRoleCaches() ;
767 //print_r($re->getAvailableRoles());
770 //TODO - this should be generalized and used for pre.php,
771 //SOAP, forum_gateway.php, tracker_gateway.php, etc to
773 function session_continue($sessionKey) {
775 $session_ser = $sessionKey;
777 setup_gettext_from_context();
778 setup_tz_from_context();
779 $LUSER =& session_get_user();
780 if (!is_object($LUSER) || $LUSER->isError()) {
786 function setup_tz_from_context() {
787 $LUSER =& session_get_user();
788 if (!is_object($LUSER) || $LUSER->isError()) {
789 $tz = forge_get_config('default_timezone');
791 $tz = $LUSER->getTimeZone();
794 date_default_timezone_set($tz);
798 * session_get_user() - Wrapper function to return the User object for the logged in user.
803 function &session_get_user() {
810 * Get user_id of logged in user
812 function user_getid() {
815 return $G_SESSION->getID();
822 * See if user is logged in
824 function session_loggedin() {
828 return $G_SESSION->isLoggedIn();
835 // c-file-style: "bsd"