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 $session_cookie_data = array(
60 getStringFromServer('REMOTE_ADDR'),
61 getStringFromServer('HTTP_USER_AGENT'),
63 $session_cookie = "" . time();
64 foreach ($session_cookie_data as $s) {
65 /* for escaping; this is not really HTML */
66 $session_cookie .= '<' . util_html_encode($s);
68 $session_cookie_hmac = hash_hmac("sha256", $session_cookie,
69 forge_get_config('session_key'), true);
70 $session_serial_cookie = base64_encode($session_cookie) . '!' .
71 base64_encode($session_cookie_hmac);
72 return $session_serial_cookie;
76 * session_get_hash_from_token() - Get hash of session token
78 * This hash can be used as a key to identify session, e.g. in DB.
80 * @param string Value of the session token
83 function session_get_hash_from_token($session_token) {
84 return session_get_session_cookie_hash($session_token);
86 function session_get_session_cookie_hash($session_cookie) {
88 * we cannot just use the HMAC as that may be longer than
89 * the database fields, and this code used to return a
90 * string of the size of an md5(), so just md5 it
92 return md5($session_cookie);
96 * session_check_session_token() - Check that session token passed from user is ok
98 * @param string Value of the session token
99 * @return user_id if token is ok, false otherwise
101 function session_check_session_token($session_token) {
102 if ($session_token == '') {
105 return session_check_session_cookie($session_token);
107 function session_check_session_cookie($session_cookie) {
108 if (!preg_match('#^[A-Za-z0-9+/=]*![A-Za-z0-9+/=]*$#',
111 * does not match basic format, off; recommended by
112 * http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html
113 * to protect the below code from malformed strings
118 list($session_cookie, $session_cookie_hmac) = explode('!',
120 $session_cookie = base64_decode($session_cookie);
121 $session_cookie_hmac = base64_decode($session_cookie_hmac);
122 if (hash_hmac("sha256", $session_cookie,
123 forge_get_config('session_key'), true) !== $session_cookie_hmac) {
128 list($time, $user_id, $ip, $user_agent) = explode('<', $session_cookie);
129 $user_id = util_unconvert_htmlspecialchars($user_id);
130 $ip = util_unconvert_htmlspecialchars($ip);
131 $user_agent = util_unconvert_htmlspecialchars($user_agent);
133 if (!session_check_ip($ip, getStringFromServer('REMOTE_ADDR'))) {
136 if (trim($user_agent) != getStringFromServer('HTTP_USER_AGENT')) {
139 if ((forge_get_config('session_expire') > 0) &&
140 ($time - time() >= forge_get_config('session_expire'))) {
148 * session_logout() - Log the user off the system.
150 * This function destroys object associated with the current session,
151 * making user "logged out". Deletes both user and session cookies.
156 function session_logout() {
157 plugin_hook('close_auth_session');
159 // delete both session and username cookies
160 // NB: cookies must be deleted with the same scope parameters they were set with
162 session_cookie('session_ser', '');
164 RBACEngine::getInstance()->invalidateRoleCaches();
169 * session_login_valid() - Log the user to the system.
171 * High-level function for user login. Check credentials, and if they
172 * are valid, open new session.
174 * @param string User name
175 * @param string User password (in clear text)
176 * @param bool Allow login to non-confirmed user account (only for confirmation of the very account)
177 * @return true/false, if false reason is in global $feedback
181 function session_login_valid($loginname, $passwd, $allowpending=0) {
182 global $feedback, $error_msg, $warning_msg;
184 if (!$loginname || !$passwd) {
185 $warning_msg = _('Missing Password Or Users Name');
189 $hook_params = array();
190 $hook_params['loginname'] = $loginname;
191 $hook_params['passwd'] = $passwd;
192 $result = plugin_hook("session_before_login", $hook_params);
194 // Refuse login if not all the plugins are ok.
196 if (!util_ifsetor($feedback)) {
197 $warning_msg = _('Invalid Password Or User Name');
202 return session_login_valid_dbonly($loginname, $passwd, $allowpending);
205 function session_check_credentials_in_database($loginname, $passwd, $allowpending=false) {
206 return session_login_valid_dbonly($loginname, $passwd, $allowpending);
208 function session_login_valid_dbonly($loginname, $passwd, $allowpending) {
209 global $feedback, $userstatus;
211 // Try to get the users from the database using user_id and (MD5) user_pw
212 if (forge_get_config('require_unique_email')) {
213 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE (user_name=$1 OR email=$1) AND user_pw=$2',
217 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1 AND user_pw=$2',
221 if (!$res || db_numrows($res) < 1) {
222 // No user whose MD5 passwd matches the MD5 of the provided passwd
223 // Selecting by user_name/email only
224 if (forge_get_config('require_unique_email')) {
225 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1 OR email=$1',
226 array ($loginname)) ;
228 $res = db_query_params ('SELECT user_id,status,unix_pw FROM users WHERE user_name=$1',
229 array ($loginname)) ;
231 if (!$res || db_numrows($res) < 1) {
232 // No user by that name
233 $warning_msg = _('Invalid Password Or User Name');
236 // There is a user with the provided user_name/email, but the MD5 passwds do not match
237 // We'll have to try checking the (crypt) unix_pw
238 $usr = db_fetch_array($res);
239 $userstatus = $usr['status'] ;
241 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
242 // Even the (crypt) unix_pw does not patch
243 // This one has clearly typed a bad passwd
244 $warning_msg = _('Invalid Password Or User Name');
247 // User exists, (crypt) unix_pw matches
248 // Update the (MD5) user_pw and retry authentication
249 // It should work, except for status errors
250 $res = db_query_params ('UPDATE users SET user_pw=$1 WHERE user_id=$2',
253 return session_check_credentials_in_database($loginname, $passwd, $allowpending) ;
256 // If we're here, then the user has typed a password matching the (MD5) user_pw
257 // Let's check whether it also matches the (crypt) unix_pw
258 $usr = db_fetch_array($res);
260 if (crypt ($passwd, $usr['unix_pw']) != $usr['unix_pw']) {
261 // The (crypt) unix_pw does not match
262 if ($usr['unix_pw'] == '') {
263 // Empty unix_pw, we'll take the MD5 as authoritative
264 // Update the (crypt) unix_pw and retry authentication
265 // It should work, except for status errors
266 $res = db_query_params ('UPDATE users SET unix_pw=$1 WHERE user_id=$2',
267 array (account_genunixpw($passwd),
269 return session_check_credentials_in_database($loginname, $passwd, $allowpending) ;
271 // Invalidate (MD5) user_pw, refuse authentication
272 $res = db_query_params ('UPDATE users SET user_pw=$1 WHERE user_id=$2',
273 array ('OUT OF DATE',
275 $warning_msg =_('Invalid Password Or User Name');
280 // Yay. The provided password matches both fields in the database.
281 // Let's check the status of this user
283 // if allowpending (for verify.php) then allow
284 $userstatus=$usr['status'];
285 if ($allowpending && ($usr['status'] == 'P')) {
288 if ($usr['status'] == 'S') {
290 $warning_msg = _('Account Suspended');
293 if ($usr['status'] == 'P') {
295 $warning_msg = _('Account Pending');
298 if ($usr['status'] == 'D') {
300 $warning_msg = _('Account Deleted');
303 if ($usr['status'] != 'A') {
304 //unacceptable account flag
305 $warning_msg = _('Account Not Active');
309 // create a new session
310 session_set_new(db_result($res, 0, 'user_id'));
317 * session_check_ip() - Check 2 IP addresses for match
319 * This function checks that IP addresses match
321 * IPv4 addresses are allowed to match with some
322 * fuzz factor (within 255.255.0.0 subnet).
324 * For IPv6 addresses, no fuzz is needed since there's
325 * usually no NAT in IPv6.
327 * @param string The old IP address
328 * @param string The new IP address
332 function session_check_ip($oldip, $newip) {
333 if (strstr($oldip, ':')) {
335 if (strstr($newip, ':')) {
336 // New IP is IPv6 too
337 return ($oldip == $newip);
342 if (strstr($newip, ':')) {
346 $eoldip = explode(".", $oldip);
347 $enewip = explode(".", $newip);
349 // require same Class B subnet
350 return (($eoldip[0] == $enewip[0]) && ($eoldip[1] == $enewip[1]));
354 * session_issecure() - Check if current session is secure
359 function session_issecure() {
360 return (strtoupper(getStringFromServer('HTTPS')) == "ON");
364 * session_set_cookie() - Set a session cookie
366 * Set a cookie with default temporal scope of the current browser session
367 * and URL space of the current webserver
369 * @param string Name of cookie
370 * @param string Value of cookie
371 * @param string Domain scope (default '')
372 * @param string Expiration time in UNIX seconds (default 0)
374 function session_set_cookie($name, $value, $domain='', $expiration=0) {
375 return session_cookie($name, $value, $domain, $expiration);
377 function session_cookie($name, $value, $domain='', $expiration=0) {
378 if (php_sapi_name() == 'cli') {
382 $expiration = time() + $expiration;
384 /* evolvis: force secure (SSL-only) session cookies */
385 //$force_secure = true;
386 /* not (yet?) in FusionForge */
387 $force_secure = false;
388 if ($force_secure && !session_issecure()) {
391 if (PHP_MAJOR_VERSION < 5 || PHP_MINOR_VERSION < 2) {
392 // In PHP < 5.2, setcookie accepts at most 6 parameters
393 setcookie($name, $value, $expiration, '/', $domain, $force_secure);
395 setcookie($name, $value, $expiration, '/', $domain, $force_secure, true);
400 * session_redirect_uri() - Redirect browser
402 * @param string Absolute URI
403 * @return never returns
405 function session_redirect_uri($loc) {
406 util_save_messages();
407 sysdebug_off("Status: 301 Moved Permanently", true, 301);
408 header("Location: ${loc}", true);
409 echo "\nPlease go to ${loc} instead!\n";
414 * session_redirect() - Redirect browser within the site and exit.
416 * @param string $loc Absolute path within the site
418 function session_redirect($loc) {
419 session_redirect_uri(util_make_url($loc));
424 * session_redirect_external() - Redirect browser to a (potentially external) URL
426 * @param string Absolute URL, not necessarily within the site
427 * @return never returns
429 function session_redirect_external($url) {
430 util_save_messages();
431 header('Location: '.$url);
437 * session_redirect404() - Redirect browser to 404 error page
439 * @return never returns
441 function session_redirect404() {
442 global $HTML, $gfwww, $gfcommon;
444 header("HTTP/1.0 404 Not Found");
445 require_once $gfwww.'404.php';
451 * session_require() - DEPRECATED Convenience function to easily enforce permissions
453 * Calling page will terminate with error message if current user
456 * @param array Associative array specifying criteria
457 * @return does not return if check is failed
460 function session_require($req, $reason='') {
461 if (!session_loggedin()) {
462 exit_not_logged_in();
465 $user =& user_get_object(user_getid());
466 if (!$user->isActive()) {
468 exit_error(_('Your account is no longer active; you have been disconnected'), '');
471 if (!array_key_exists('group', $req)) {
472 exit_permission_denied($reason, '');
475 $group = group_get_object($req['group']);
476 if (!$group || !is_object($group)) {
478 } elseif ($group->isError()) {
479 exit_error($reason ? $reason : $group->getErrorMessage(), '');
482 $perm =& $group->getPermission();
483 if (!$perm || !is_object($perm) || $perm->isError()) {
484 exit_permission_denied($reason, '');
487 if (isset($req['admin_flags']) && $req['admin_flags']) {
488 if (!$perm->isAdmin()) {
489 exit_permission_denied($reason, '');
492 if (!$perm->isMember()) {
493 exit_permission_denied($reason, '');
499 * session_require_perm() - Convenience function to easily enforce permissions
501 * Calling page will terminate with error message if current user
505 function session_require_perm($section, $reference, $action=NULL, $reason='') {
506 if (!forge_check_perm($section, $reference, $action)) {
507 exit_permission_denied($reason, $section);
512 * session_require_global_perm() - Convenience function to easily enforce permissions
514 * Calling page will terminate with error message if current user
518 function session_require_global_perm($section, $action=NULL, $reason='') {
519 if (!forge_check_global_perm($section, $action)) {
521 $reason = sprintf(_('Permission denied. The %s administrators will have to grant you permission to view this page.'),
522 forge_get_config('forge_name'));
524 exit_permission_denied($reason, $section);
529 * session_require_login() - Convenience function to easily enforce permissions
531 * Calling page will terminate with error message if current user
535 function session_require_login() {
536 if (!session_loggedin()) {
537 exit_not_logged_in();
542 * session_set_new() - Setup session for the given user
544 * This function sets up SourceForge session for the given user,
545 * making one be "logged in".
547 * @param int The user ID
550 function session_set_new($user_id) {
551 $token = session_build_session_token($user_id);
553 // set session cookie
555 $cookie = session_build_session_cookie($user_id);
556 // session_cookie("session_ser", $cookie, "", forge_get_config('session_expire'));
557 // $session_ser = $cookie;
559 $res = db_query_params('SELECT count(*) as c FROM user_session
560 WHERE session_hash=$1',
561 array(($shash = session_get_session_cookie_hash($cookie))));
562 if (!$res || db_result($res, 0, 'c') < 1) {
563 db_query_params('INSERT INTO user_session
564 (session_hash,ip_addr,time,user_id)
565 VALUES ($1,$2,$3,$4)',
568 getStringFromServer('REMOTE_ADDR'),
574 // check uniqueness of the session_hash in the database
575 $res = session_getdata($user_id);
578 exit_error(db_error(), '');
579 } elseif (db_numrows($res) < 1) {
580 exit_error(_('Could not fetch user session data'), '');
582 session_set_internal($user_id, $res);
586 function session_set_internal($user_id, $res=false) {
589 $G_SESSION = user_get_object($user_id, $res);
591 $G_SESSION->setLoggedIn(true);
594 RBACEngine::getInstance()->invalidateRoleCaches();
598 * session_set_admin() - Setup session for the admin user
600 * This function sets up a session for the administrator
604 function session_set_admin() {
605 $admins = RBACEngine::getInstance()->getUsersByAllowedAction('forge_admin', -1);
606 if (count($admins) == 0) {
607 exit_error(_('No admin users ?'), '');
610 * Use the user with the lowest numerical user ID.
611 * This is to prevent complaints from real humans
612 * if the system is doing something in their stead
613 * (for example by populate_template_project.php).
614 * Usually, “admin” has the ID 101.
616 $admin_ids = array();
617 foreach ($admins as $admin) {
618 $admin_ids[] = $admin->getID();
621 session_set_new($admin_ids[0]);
625 * Private optimization function for logins - fetches user data, language, and session
628 * @param int The user ID
631 function session_getdata($user_id) {
632 return db_query_params('SELECT u.*, sl.language_id, sl.name,
633 sl.filename, sl.classname, sl.language_code,
634 t.dirname, t.fullname
635 FROM users u, supported_languages sl, themes t
636 WHERE u.language=sl.language_id
637 AND u.theme_id=t.theme_id
643 * session_set() - Re-initialize session for the logged in user
645 * This function checks that the user is logged in and if so, initialize
646 * internal session environment.
650 function session_set() {
654 // assume bad session_hash and session. If all checks work, then allow
655 // otherwise make new session
659 // pass the session_ser from cookie to the auth plugins
660 // (see AuthBuiltinPlugin::checkAuthSession() or likes)
661 // expect FORGE_AUTH_AUTHORITATIVE_ACCEPT, FORGE_AUTH_AUTHORITATIVE_REJECT or FORGE_AUTH_NOT_AUTHORITATIVE
663 $params['auth_token'] = $session_ser;
664 $params['results'] = array();
665 plugin_hook_by_reference('check_auth_session', $params);
669 foreach ($params['results'] as $p => $r) {
670 if ($r == FORGE_AUTH_AUTHORITATIVE_ACCEPT) {
672 } elseif ($r == FORGE_AUTH_AUTHORITATIVE_REJECT) {
676 if ($seen_yes && !$seen_no) {
677 // see AuthBuiltinPlugin::fetchAuthUser() or likes
678 // expect user object in results
680 $params['results'] = NULL;
681 plugin_hook_by_reference('fetch_authenticated_user', $params);
682 $user = $params['results'];
686 $params['username'] = $user->getUnixName();
687 $params['event'] = 'every-page';
688 plugin_hook('sync_account_info', $params);
690 $user->setLoggedIn(true);
696 // TODO: else... what ?
698 $re = RBACEngine::getInstance();
699 $re->invalidateRoleCaches() ;
703 * Re initializes a session, trusting a non-sufficient plugin only temporarily
705 * The checkAuthSession of the Auth plugin will have to acknowledge the 'sufficient_forced' param in 'check_auth_session' hook
706 * @param string $authpluginname
708 function session_set_for_authplugin($authpluginname) {
712 // assume bad session_hash and session. If all checks work, then allow
713 // otherwise make new session
717 // pass the session_ser from cookie to the auth plugins
718 // (see AuthBuiltinPlugin::checkAuthSession() or likes)
719 // expect FORGE_AUTH_AUTHORITATIVE_ACCEPT, FORGE_AUTH_AUTHORITATIVE_REJECT or FORGE_AUTH_NOT_AUTHORITATIVE
721 $params['sufficient_forced'] = $authpluginname;
723 $params['auth_token'] = $session_ser;
724 $params['results'] = array();
726 plugin_hook_by_reference('check_auth_session', $params);
729 foreach ($params['results'] as $p => $r) {
730 if ($r == FORGE_AUTH_AUTHORITATIVE_ACCEPT) {
737 // see AuthBuiltinPlugin::fetchAuthUser() or likes
738 // expect user object in results
740 $params['results'] = NULL;
742 plugin_hook_by_reference('fetch_authenticated_user', $params);
744 $user = $params['results'];
748 $params['username'] = $user->getUnixName();
749 $params['event'] = 'every-page';
750 plugin_hook('sync_account_info', $params);
752 $user->setLoggedIn(true);echo "user:".$user->getUnixName();
759 // TODO: else... what ?
761 $re = RBACEngine::getInstance();
762 //print_r($re->getGlobalRoles());
763 //print_r($re->getPublicRoles());
764 $re->invalidateRoleCaches() ;
765 //print_r($re->getAvailableRoles());
768 //TODO - this should be generalized and used for pre.php,
769 //SOAP, forum_gateway.php, tracker_gateway.php, etc to
771 function session_continue($sessionKey) {
773 $session_ser = $sessionKey;
775 setup_gettext_from_context();
776 setup_tz_from_context();
777 $LUSER =& session_get_user();
778 if (!is_object($LUSER) || $LUSER->isError()) {
784 function setup_tz_from_context() {
785 $LUSER =& session_get_user();
786 if (!is_object($LUSER) || $LUSER->isError()) {
787 $tz = forge_get_config('default_timezone');
789 $tz = $LUSER->getTimeZone();
792 date_default_timezone_set($tz);
796 * session_get_user() - Wrapper function to return the User object for the logged in user.
801 function &session_get_user() {
808 * Get user_id of logged in user
810 function user_getid() {
813 return $G_SESSION->getID();
820 * See if user is logged in
822 function session_loggedin() {
826 return $G_SESSION->isLoggedIn();
833 // c-file-style: "bsd"