diff -r de56132c008d -r bdac73ed481e includes/sessions.php
--- a/includes/sessions.php Sun Mar 28 21:49:26 2010 -0400
+++ b/includes/sessions.php Sun Mar 28 23:10:46 2010 -0400
@@ -21,4132 +21,4132 @@
*/
class sessionManager {
-
- # Variables
-
- /**
- * Whether we're logged in or not
- * @var bool
- */
-
- var $user_logged_in = false;
-
- /**
- * Our current low-privilege session key
- * @var string
- */
-
- var $sid;
-
- /**
- * Username of currently logged-in user, or IP address if not logged in
- * @var string
- */
-
- var $username;
-
- /**
- * User ID of currently logged-in user, or 1 if not logged in
- * @var int
- */
-
- var $user_id = 1;
-
- /**
- * Real name of currently logged-in user, or blank if not logged in
- * @var string
- */
-
- var $real_name;
-
- /**
- * E-mail address of currently logged-in user, or blank if not logged in
- * @var string
- */
-
- var $email;
-
- /**
- * List of "extra" user information fields (IM handles, etc.)
- * @var array (associative)
- */
-
- var $user_extra;
-
- /**
- * User level of current user
- * USER_LEVEL_GUEST: guest
- * USER_LEVEL_MEMBER: regular user
- * USER_LEVEL_CHPREF: default - pseudo-level that allows changing password and e-mail address (requires re-authentication)
- * USER_LEVEL_MOD: moderator
- * USER_LEVEL_ADMIN: administrator
- * @var int
- */
-
- var $user_level;
-
- /**
- * High-privilege session key
- * @var string or false if not running on high-level authentication
- */
-
- var $sid_super;
-
- /**
- * The user's theme preference, defaults to $template->default_theme
- * @var string
- */
-
- var $theme;
-
- /**
- * The user's style preference, or style auto-detected based on theme if not logged in
- * @var string
- */
-
- var $style;
-
- /**
- * Signature of current user - appended to comments, etc.
- * @var string
- */
-
- var $signature;
-
- /**
- * UNIX timestamp of when we were registered, or 0 if not logged in
- * @var int
- */
-
- var $reg_time;
-
- /**
- * The number of unread private messages this user has.
- * @var int
- */
-
- var $unread_pms = 0;
-
- /**
- * AES key used to encrypt passwords and session key info.
- * @var string
- * @access private
- */
-
- protected $private_key;
-
- /**
- * Regex that defines a valid username, minus the ^ and $, these are added later
- * @var string
- */
-
- var $valid_username = '([^<>&\?\'"%\n\r\t\a\/]+)';
-
- /**
- * The current user's user title. Defaults to NULL.
- * @var string
- */
-
- var $user_title = null;
-
- /**
- * What we're allowed to do as far as permissions go. This changes based on the value of the "auth" URI param.
- * @var string
- */
-
- var $auth_level = 1;
-
- /**
- * Preference for date formatting
- * @var string
- */
-
- var $date_format = DATE_4;
-
- /**
- * Preference for time formatting
- * @var string
- */
-
- var $time_format = TIME_24_NS;
-
- /**
- * State variable to track if a session timed out
- * @var bool
- */
-
- var $sw_timed_out = false;
-
- /**
- * Token appended to some important forms to prevent CSRF.
- * @var string
- */
-
- var $csrf_token = false;
-
- /**
- * Password change disabled, for auth plugins
- * @var bool
- */
-
- var $password_change_disabled = false;
-
- /**
- * Password change page URL + title, for auth plugins
- * @var array
- */
-
- var $password_change_dest = array('url' => '', 'title' => '');
-
- /**
- * Switch to track if we're started or not.
- * @access private
- * @var bool
- */
-
- var $started = false;
-
- /**
- * Switch to control compatibility mode (for older Enano websites being upgraded)
- * @access private
- * @var bool
- */
-
- var $compat = false;
-
- /**
- * Our list of permission types.
- * @access private
- * @var array
- */
-
- var $acl_types = Array();
-
- /**
- * The list of descriptions for the permission types
- * @var array
- */
-
- var $acl_descs = Array();
-
- /**
- * A list of dependencies for ACL types.
- * @var array
- */
-
- var $acl_deps = Array();
-
- /**
- * Our tell-all list of permissions. Do not even try to change this.
- * @access private
- * @var array
- */
-
- var $perms = Array();
-
- /**
- * A cache variable - saved after sitewide permissions are checked but before page-specific permissions.
- * @var array
- * @access private
- */
-
- var $acl_base_cache = Array();
-
- /**
- * Stores the scope information for ACL types.
- * @var array
- * @access private
- */
-
- var $acl_scope = Array();
-
- /**
- * Array to track which default permissions are being used
- * @var array
- * @access private
- */
-
- var $acl_defaults_used = Array();
-
- /**
- * Array to track group membership.
- * @var array
- */
-
- var $groups = Array();
-
- /**
- * Associative array to track group modship.
- * @var array
- */
-
- var $group_mod = Array();
-
- /**
- * A constant array of user-level-to-rank default associations.
- * @var array
- */
-
- var $level_rank_table = array(
- USER_LEVEL_ADMIN => RANK_ID_ADMIN,
- USER_LEVEL_MOD => RANK_ID_MOD,
- USER_LEVEL_MEMBER => RANK_ID_MEMBER,
- USER_LEVEL_CHPREF => RANK_ID_MEMBER,
- USER_LEVEL_GUEST => RANK_ID_GUEST
- );
-
- /**
- * A constant array that maps precedence constants to language strings
- * @var array
- */
-
- var $acl_inherit_lang_table = array(
- ACL_INHERIT_ENANO_DEFAULT => 'acl_inherit_enano_default',
- ACL_INHERIT_GLOBAL_EVERYONE => 'acl_inherit_global_everyone',
- ACL_INHERIT_GLOBAL_GROUP => 'acl_inherit_global_group',
- ACL_INHERIT_GLOBAL_USER => 'acl_inherit_global_user',
- ACL_INHERIT_PG_EVERYONE => 'acl_inherit_pg_everyone',
- ACL_INHERIT_PG_GROUP => 'acl_inherit_pg_group',
- ACL_INHERIT_PG_USER => 'acl_inherit_pg_user',
- ACL_INHERIT_LOCAL_EVERYONE => 'acl_inherit_local_everyone',
- ACL_INHERIT_LOCAL_GROUP => 'acl_inherit_local_group',
- ACL_INHERIT_LOCAL_USER => 'acl_inherit_local_user'
- );
-
- # Basic functions
-
- /**
- * Constructor.
- */
-
- function __construct()
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
-
- if ( defined('IN_ENANO_INSTALL') && !defined('IN_ENANO_UPGRADE') )
- {
- @include(ENANO_ROOT.'/config.new.php');
- }
- else
- {
- @include(ENANO_ROOT.'/config.php');
- }
-
- unset($dbhost, $dbname, $dbuser, $dbpasswd);
- if(isset($crypto_key))
- {
- $this->private_key = $crypto_key;
- $this->private_key = hexdecode($this->private_key);
- }
- else
- {
- if(is_writable(ENANO_ROOT.'/config.php'))
- {
- // Generate and stash a private key
- // This should only happen during an automated silent gradual migration to the new encryption platform.
- $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
- $this->private_key = $aes->gen_readymade_key();
-
- $config = file_get_contents(ENANO_ROOT.'/config.php');
- if(!$config)
- {
- die('$session->__construct(): can\'t get the contents of config.php');
- }
-
- $config = str_replace("?>", "\$crypto_key = '{$this->private_key}';\n?>", $config);
- // And while we're at it...
- $config = str_replace('MIDGET_INSTALLED', 'ENANO_INSTALLED', $config);
- $fh = @fopen(ENANO_ROOT.'/config.php', 'w');
- if ( !$fh )
- {
- die('$session->__construct(): Couldn\'t open config file for writing to store the private key, I tried to avoid something like this...');
- }
-
- fwrite($fh, $config);
- fclose($fh);
- }
- else
- {
- die_semicritical('Crypto error', '
No private key was found in the config file, and we can\'t generate one because we don\'t have write access to the config file. Please CHMOD config.php to 666 or 777 and reload this page.
');
- }
- }
- // Check for compatibility mode
- if(defined('IN_ENANO_INSTALL'))
- {
- $q = $db->sql_query('SELECT old_encryption FROM '.table_prefix.'users LIMIT 1;');
- if(!$q)
- {
- $error = mysql_error();
- if(strstr($error, "Unknown column 'old_encryption'"))
- $this->compat = true;
- else
- $db->_die('This should never happen and is a bug - the only error that was supposed to happen here didn\'t happen. (sessions.php in constructor, during compat mode check)');
- }
- $db->free_result();
- }
- }
-
- /**
- * PHP 4 compatible constructor. Deprecated in 1.1.x.
- */
-
- /*
- function sessionManager()
- {
- $this->__construct();
- }
- */
-
- /**
- * Wrapper function to sanitize strings for MySQL and HTML
- * @param string $text The text to sanitize
- * @return string
- */
-
- function prepare_text($text)
- {
- global $db;
- return $db->escape(htmlspecialchars($text));
- }
-
- /**
- * Makes a SQL query and handles error checking
- * @param string $query The SQL query to make
- * @return resource
- */
-
- function sql($query)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
- $result = $db->sql_query($query);
- if(!$result)
- {
- $db->_die('The error seems to have occurred somewhere in the session management code.');
- }
- return $result;
- }
-
- /**
- * Returns true if we're currently on a page that shouldn't be blocked even if we have an inactive or banned account
- * @param bool strict - if true, whitelist of pages is even stricter (Login, Logout and CSS only). if false (default), admin access is allowed, assuming other factors allow it
- * @return bool
- */
-
- function on_critical_page($strict = false)
- {
- global $urlname;
- list($page_id, $namespace) = RenderMan::strToPageID($urlname);
- list($page_id) = explode('/', $page_id);
-
- if ( $strict )
- {
- return $namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'LangExportJSON', 'ActivateAccount'));
- }
- else
- {
- return $namespace == 'Admin' || ($namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'Administration', 'LangExportJSON', 'ActivateAccount')));
- }
- }
-
- # Session restoration and permissions
-
- /**
- * Initializes the basic state of things, including most user prefs, login data, cookie stuff
- */
-
- function start()
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
- global $lang;
- global $timezone;
- if($this->started) return;
- $this->started = true;
- $user = false;
- if ( isset($_COOKIE['sid']) )
- {
- if ( $this->compat )
- {
- $userdata = $this->compat_validate_session($_COOKIE['sid']);
- }
- else
- {
- $userdata = $this->validate_session($_COOKIE['sid']);
- }
- if ( is_array($userdata) )
- {
- $this->sid = $_COOKIE['sid'];
- $this->user_logged_in = true;
- $this->user_id = intval($userdata['user_id']);
- $this->username = $userdata['username'];
- $this->user_level = intval($userdata['user_level']);
- $this->real_name = $userdata['real_name'];
- $this->email = $userdata['email'];
- $this->unread_pms = $userdata['num_pms'];
- $this->user_title = ( isset($userdata['user_title']) ) ? $userdata['user_title'] : null;
- if(!$this->compat)
- {
- $this->theme = $userdata['theme'];
- $this->style = $userdata['style'];
- $this->signature = $userdata['signature'];
- $this->reg_time = $userdata['reg_time'];
- }
- $this->auth_level = USER_LEVEL_MEMBER;
- // generate an anti-CSRF token
- $this->csrf_token = sha1($this->username . $this->sid . $this->user_id);
- if(!isset($template->named_theme_list[$this->theme]))
- {
- if($this->compat || !is_object($template))
- {
- $this->theme = 'oxygen';
- $this->style = 'bleu';
- }
- else
- {
- $this->theme = $template->default_theme;
- $this->style = $template->default_style;
- }
- }
- $user = true;
-
- // set timezone params
- $GLOBALS['timezone'] = $userdata['user_timezone'];
- $GLOBALS['dst_params'] = explode(';', $userdata['user_dst']);
- foreach ( $GLOBALS['dst_params'] as &$parm )
- {
- if ( substr($parm, -1) != 'd' )
- $parm = intval($parm);
- }
-
- // Set language
- if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
- {
- $lang_id = intval($userdata['user_lang']);
- $lang = new Language($lang_id);
- @setlocale(LC_ALL, $lang->lang_code);
- }
-
- if(isset($_REQUEST['auth']) && !$this->sid_super)
- {
- // Now he thinks he's a moderator. Or maybe even an administrator. Let's find out if he's telling the truth.
- if($this->compat)
- {
- $key = $_REQUEST['auth'];
- $super = $this->compat_validate_session($key);
- }
- else
- {
- $key = $_REQUEST['auth'];
- if ( !empty($key) && ( strlen($key) / 2 ) % 4 == 0 )
- {
- $super = $this->validate_session($key);
- }
- }
- if(is_array(@$super))
- {
- $this->auth_level = intval($super['auth_level']);
- $this->sid_super = $_REQUEST['auth'];
- }
- }
- }
- }
- if(!$user)
- {
- //exit;
- $this->register_guest_session();
- }
- if(!$this->compat)
- {
- // init groups
- $q = $this->sql('SELECT g.group_name,g.group_id,m.is_mod FROM '.table_prefix.'groups AS g' . "\n"
- . ' LEFT JOIN '.table_prefix.'group_members AS m' . "\n"
- . ' ON g.group_id=m.group_id' . "\n"
- . ' WHERE ( m.user_id='.$this->user_id.'' . "\n"
- . ' OR g.group_name=\'Everyone\')' . "\n"
- . ' ' . ( /* quick hack for upgrade compatibility reasons */ enano_version() == '1.0RC1' ? '' : 'AND ( m.pending != 1 OR m.pending IS NULL )' ) . '' . "\n"
- . ' ORDER BY group_id ASC;'); // The ORDER BY is to make sure "Everyone" comes first so the permissions can be overridden
- if($row = $db->fetchrow())
- {
- do {
- $this->groups[$row['group_id']] = $row['group_name'];
- $this->group_mod[$row['group_id']] = ( intval($row['is_mod']) == 1 );
- } while($row = $db->fetchrow());
- }
- else
- {
- die('No group info');
- }
- profiler_log('Fetched group memberships');
- }
-
- // make sure we aren't banned
- $this->check_banlist();
-
- // make sure the account is active
- if ( !$this->compat && $this->user_logged_in && $userdata['account_active'] < 1 && !$this->on_critical_page() )
- {
- $this->show_inactive_error($userdata);
- }
-
- // Printable page view? Probably the wrong place to control
- // it but $template is pretty dumb, it will just about always
- // do what you ask it to do, which isn't always what we want
- if ( isset ( $_GET['printable'] ) )
- {
- $this->theme = 'printable';
- $this->style = 'default';
- }
-
- // setup theme ACLs
- $template->process_theme_acls();
-
- profiler_log('Sessions started. Banlist and theme ACLs initialized');
- }
-
- # Logins
-
- /**
- * Attempts to perform a login using crypto functions
- * @param string $username The username
- * @param string $aes_data The encrypted password, hex-encoded
- * @param string $aes_key The MD5 hash of the encryption key, hex-encoded
- * @param string $challenge The 256-bit MD5 challenge string - first 128 bits should be the hash, the last 128 should be the challenge salt
- * @param int $level The privilege level we're authenticating for, defaults to 0
- * @param string $captcha_hash Optional. If we're locked out and the lockout policy is captcha, this should be the identifier for the code.
- * @param string $captcha_code Optional. If we're locked out and the lockout policy is captcha, this should be the code the user entered.
- * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
- * @param bool $lookup_key Optional. If true (default) this queries the database for the "real" encryption key. Else, uses what is given.
- * @return string 'success' on success, or error string on failure
- */
-
- function login_with_crypto($username, $aes_data, $aes_key_id, $challenge, $level = USER_LEVEL_MEMBER, $captcha_hash = false, $captcha_code = false, $remember = false, $lookup_key = true)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
-
- // Instanciate the Rijndael encryption object
- $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
-
- // Fetch our decryption key
-
- if ( $lookup_key )
- {
- $aes_key = $this->fetch_public_key($aes_key_id);
- if ( !$aes_key )
- {
- // It could be that our key cache is full. If it seems larger than 65KB, clear it
- if ( strlen(getConfig('login_key_cache')) > 65000 )
- {
- setConfig('login_key_cache', '');
- return array(
- 'success' => false,
- 'error' => 'key_not_found_cleared',
- );
- }
- return array(
- 'success' => false,
- 'error' => 'key_not_found'
- );
- }
- }
- else
- {
- $aes_key =& $aes_key_id;
- }
-
- // Convert the key to a binary string
- $bin_key = hexdecode($aes_key);
-
- if(strlen($bin_key) != AES_BITS / 8)
- return array(
- 'success' => false,
- 'error' => 'key_wrong_length'
- );
-
- // Decrypt our password
- $password = $aes->decrypt($aes_data, $bin_key, ENC_HEX);
-
- // Let the LoginAPI do the rest.
- return $this->login_without_crypto($username, $password, false, $level, $captcha_hash, $captcha_code, $remember);
- }
-
- /**
- * Attempts to login without using crypto stuff, mainly for use when the other side doesn't like Javascript
- * This method of authentication is inherently insecure, there's really nothing we can do about it except hope and pray that everyone moves to Firefox
- * Technically it still uses crypto, but it only decrypts the password already stored, which is (obviously) required for authentication
- * @param string $username The username
- * @param string $password The password -OR- the MD5 hash of the password if $already_md5ed is true
- * @param bool $already_md5ed This should be set to true if $password is an MD5 hash, and should be false if it's plaintext. Defaults to false.
- * @param int $level The privilege level we're authenticating for, defaults to 0
- * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
- */
-
- function login_without_crypto($username, $password, $already_md5ed = false, $level = USER_LEVEL_MEMBER, $remember = false)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
-
- if ( $already_md5ed )
- {
- // No longer supported
- return array(
- 'mode' => 'error',
- 'error' => '$already_md5ed is no longer supported (set this parameter to false and make sure the password you send to $session->login_without_crypto() is not hashed)'
- );
- }
-
- // Replace underscores with spaces in username
- // (Added in 1.0.2)
- $username = str_replace('_', ' ', $username);
-
- // Perhaps we're upgrading Enano?
- if($this->compat)
- {
- return $this->login_compat($username, md5($password), $level);
- }
-
- // Instanciate the Rijndael encryption object
- $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
-
- // Initialize our success switch
- $success = false;
-
- // Retrieve the real password from the database
- $username_db = $db->escape(strtolower($username));
- $username_db_upper = $db->escape($username);
- if ( !$db->sql_query('SELECT password,password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
- . " WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );") )
- {
- $this->sql('SELECT password,\'\' AS password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
- . " WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );");
- }
- if ( $db->numrows() < 1 )
- {
- // This wasn't logged in <1.0.2, dunno how it slipped through
- if ( $level > USER_LEVEL_MEMBER )
- $this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES\n"
- . ' (\'security\', \'admin_auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
- . '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
- else
- $this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary) VALUES\n"
- . ' (\'security\', \'auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
- . '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
-
- // Do we also need to increment the lockout countdown?
- if ( !defined('IN_ENANO_INSTALL') )
- $lockout_data = $this->get_lockout_info();
- else
- $lockout_data = array(
- 'lockout_policy' => 'disable'
- );
-
- if ( $lockout_data['policy'] != 'disable' && !defined('IN_ENANO_INSTALL') )
- {
- $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
- // increment fail count
- $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
- $lockout_data['fails']++;
- return array(
- 'success' => false,
- 'error' => ( $lockout_data['fails'] >= $lockout_data['threshold'] ) ? 'locked_out' : 'invalid_credentials',
- 'lockout_threshold' => $lockout_data['threshold'],
- 'lockout_duration' => ( $lockout_data['duration'] ),
- 'lockout_fails' => $lockout_data['fails'],
- 'lockout_policy' => $lockout_data['policy']
- );
- }
-
- return array(
- 'success' => false,
- 'error' => 'invalid_credentials'
- );
- }
- $row = $db->fetchrow();
-
- // Check to see if we're logging in using a temporary password
-
- if((intval($row['temp_password_time']) + 3600*24) > time() )
- {
- $temp_pass = hmac_sha1($password, $row['password_salt']);
- if( $temp_pass === $row['temp_password'] )
- {
- $code = $plugins->setHook('login_password_reset');
- foreach ( $code as $cmd )
- {
- eval($cmd);
- }
-
- return array(
- 'success' => false,
- 'error' => 'valid_reset',
- 'redirect_url' => makeUrlComplete('Special', 'PasswordReset/stage2/' . $row['user_id'] . '/' . $this->pk_encrypt($password))
- );
- }
- }
-
- if ( $row['old_encryption'] == 1 )
- {
- // The user's password is stored using the obsolete and insecure MD5 algorithm - we'll update the field with the new password
- if(md5($password) === $row['password'])
- {
- if ( !defined('IN_ENANO_UPGRADE') )
- {
- $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
- $password_hmac = hmac_sha1($password, $hmac_secret);
- $this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
- }
- $success = true;
- }
- }
- else if ( $row['old_encryption'] == 2 || ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') ) && strlen($row['password']) != 40 )
- {
- // Our password field uses the 1.0RC1-1.1.5 encryption format
- $real_pass = $aes->decrypt($row['password'], $this->private_key);
- if($password === $real_pass)
- {
- if ( !defined('IN_ENANO_UPGRADE') )
- {
- $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
- $password_hmac = hmac_sha1($password, $hmac_secret);
- $this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
- }
- $success = true;
- }
- }
- else
- {
- // Password uses HMAC-SHA1
- $user_challenge = hmac_sha1($password, $row['password_salt']);
- $password_hmac =& $row['password'];
- if ( $user_challenge === $password_hmac )
- {
- $success = true;
- }
- }
- if($success)
- {
- if((int)$level > (int)$row['user_level'])
- return array(
- 'success' => false,
- 'error' => 'too_big_for_britches'
- );
-
- // grant session
- $sess = $this->register_session($row['user_id'], $username, ( isset($password_hmac) ? $password_hmac : $password ), $level, $remember);
-
- if($sess)
- {
- if($level > USER_LEVEL_MEMBER)
- $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,edit_summary,page_text) VALUES(\'security\', \'admin_auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', ' . $row['user_id'] . ', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
- else
- $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,edit_summary) VALUES(\'security\', \'auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', ' . $row['user_id'] . ', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
-
- $code = $plugins->setHook('login_success');
- foreach ( $code as $cmd )
- {
- eval($cmd);
- }
-
- return array(
- 'success' => true
- );
- }
- else
- return array(
- 'success' => false,
- 'error' => 'backend_fail'
- );
- }
- else
- {
- if($level > USER_LEVEL_MEMBER)
- $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
- else
- $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
-
- // Do we also need to increment the lockout countdown?
- if ( !defined('IN_ENANO_INSTALL') && getConfig('lockout_policy', 'lockout') !== 'disable' )
- {
- $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
- // increment fail count
- $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
- }
-
- return array(
- 'success' => false,
- 'error' => 'invalid_credentials'
- );
- }
- }
-
- /**
- * Attempts to log in using the old table structure and algorithm. This is for upgrades from old 1.0.x releases.
- * @param string $username
- * @param string $password This should be an MD5 hash
- * @return string 'success' if successful, or error message on failure
- */
-
- function login_compat($username, $password, $level = 0)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
- $pass_hashed =& $password;
- $this->sql('SELECT password,user_id,user_level FROM '.table_prefix.'users WHERE username=\''.$this->prepare_text($username).'\';');
- if($db->numrows() < 1)
- return 'The username and/or password is incorrect.';
- $row = $db->fetchrow();
- if($row['password'] == $password)
- {
- if((int)$level > (int)$row['user_level'])
- return 'You are not authorized for this level of access.';
- $sess = $this->register_session_compat(intval($row['user_id']), $username, $password, $level);
- if($sess)
- return 'success';
- else
- return 'Your login credentials were correct, but an internal error occured while registering the session key in the database.';
- }
- else
- {
- return 'The username and/or password is incorrect.';
- }
- }
-
- /**
- * Registers a session key in the database. This function *ASSUMES* that the username and password have already been validated!
- * Basically the session key is a hex-encoded cookie (encrypted with the site's private key) that says "u=[username];p=[sha1 of password];s=[unique key id]"
- * @param int $user_id
- * @param string $username
- * @param string $password_hmac The HMAC of the user's password, right from the database
- * @param int $level The level of access to grant, defaults to USER_LEVEL_MEMBER
- * @param bool $remember Whether the session should be long-term (true) or not (false). Defaults to short-term.
- * @return bool
- */
-
- function register_session($user_id, $username, $password_hmac, $level = USER_LEVEL_MEMBER, $remember = false)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
-
- // Random key identifier
- $salt = '';
- for ( $i = 0; $i < 32; $i++ )
- {
- $salt .= chr(mt_rand(32, 126));
- }
-
- // Session key
- if ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') )
- {
- $session_key = $this->pk_encrypt("u=$username;p=" . sha1($password_hmac) . ";s=$salt");
- }
- else
- {
- $key_pieces = array($password_hmac);
- $sk_mode = 'generate';
- $code = $plugins->setHook('session_key_calc');
- foreach ( $code as $cmd )
- {
- eval($cmd);
- }
- $key_pieces = implode("\xFF", $key_pieces);
-
- $session_key = hmac_sha1($key_pieces, $salt);
- }
-
- // Minimum level
- $level = max(array($level, USER_LEVEL_MEMBER));
-
- // Type of key
- $key_type = ( $level > USER_LEVEL_MEMBER ) ? SK_ELEV : ( $remember ? SK_LONG : SK_SHORT );
-
- // If we're registering an elevated-privilege key, it needs to be on GET
- if($level > USER_LEVEL_MEMBER)
- {
- $this->sid_super = $session_key;
- $_GET['auth'] = $session_key;
- }
- else
- {
- // Stash it in a cookie
- // For now, make the cookie last forever, we can change this in 1.1.x
- setcookie( 'sid', $session_key, time()+15552000, scriptPath.'/', null, $GLOBALS['is_https']);
- $_COOKIE['sid'] = $session_key;
- $this->sid = $session_key;
- }
- // $keyhash is stored in the database, this is for compatibility with the older DB structure
- $keyhash = md5($session_key);
- // Record the user's IP
- $ip = $_SERVER['REMOTE_ADDR'];
- if(!is_valid_ip($ip))
- die('$session->register_session: Remote-Addr was spoofed');
- // The time needs to be stashed to enforce the 15-minute limit on elevated session keys
- $time = time();
-
- // Sanity check
- if(!is_int($user_id))
- die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
- if(!is_int($level))
- die(var_dump($level) . ' Somehow an SQL injection attempt crawled into our session registrar! (2)');
-
- // Update RAM
- $this->user_id = $user_id;
- $this->user_level = max(array($this->user_level, $level));
-
- // All done!
- $query = $db->sql_query('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time, key_type) VALUES(\''.$keyhash.'\', \''.$db->escape($salt).'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.', ' . $key_type . ');');
- if ( !$query && defined('IN_ENANO_UPGRADE') )
- // we're trying to upgrade so the key_type column is probably missing - try it again without specifying the key type
- $this->sql('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time) VALUES(\''.$keyhash.'\', \''.$db->escape($salt).'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.');');
-
- return true;
- }
-
- /**
- * Identical to register_session in nature, but uses the old login/table structure. DO NOT use this except in the upgrade script under very controlled circumstances.
- * @see sessionManager::register_session()
- * @access private
- */
-
- function register_session_compat($user_id, $username, $password, $level = 0)
- {
- $salt = md5(microtime() . mt_rand());
- $thekey = md5($password . $salt);
- if($level > 0)
- {
- $this->sid_super = $thekey;
- }
- else
- {
- setcookie( 'sid', $thekey, time()+315360000, scriptPath.'/' );
- $_COOKIE['sid'] = $thekey;
- }
- $ip = ip2hex($_SERVER['REMOTE_ADDR']);
- if(!$ip)
- die('$session->register_session: Remote-Addr was spoofed');
- $time = time();
- if(!is_int($user_id))
- die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
- if(!is_int($level))
- die('Somehow an SQL injection attempt crawled into our session registrar! (2)');
- $query = $this->sql('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time) VALUES(\''.$thekey.'\', \''.$salt.'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.');');
- return true;
- }
-
- /**
- * Tells us if we're locked out from logging in or not.
- * @param reference will be filled with information regarding in-progress lockout
- * @return bool True if locked out, false otherwise
- */
-
- function get_lockout_info()
- {
- global $db;
-
- // this has to be initialized to hide warnings
- $lockdata = null;
-
- // Query database for lockout info
- $locked_out = false;
- $threshold = ( $_ = getConfig('lockout_threshold') ) ? intval($_) : 5;
- $duration = ( $_ = getConfig('lockout_duration') ) ? intval($_) : 15;
- // convert to seconds
- $duration = $duration * 60;
- // decide on policy
- $policy = ( $x = getConfig('lockout_policy') && in_array(getConfig('lockout_policy'), array('lockout', 'disable', 'captcha')) ) ? getConfig('lockout_policy') : 'lockout';
- if ( $policy != 'disable' )
- {
- // enabled; make decision
- $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
- $timestamp_cutoff = time() - $duration;
- $q = $this->sql('SELECT timestamp FROM ' . table_prefix . 'lockout WHERE timestamp > ' . $timestamp_cutoff . ' AND ipaddr = \'' . $ipaddr . '\' ORDER BY timestamp DESC;');
- $fails = $db->numrows($q);
- $row = $db->fetchrow($q);
- $locked_out = ( $fails >= $threshold );
- $lockdata = array(
- 'active' => $locked_out,
- 'threshold' => $threshold,
- 'duration' => ( $duration / 60 ),
- 'fails' => $fails,
- 'policy' => $policy,
- 'last_time' => $row['timestamp'],
- 'time_rem' => $locked_out ? ( $duration / 60 ) - round( ( time() - $row['timestamp'] ) / 60 ) : 0,
- 'captcha' => $policy == 'captcha' ? $this->make_captcha() : ''
- );
- $db->free_result();
- }
- else
- {
- // disabled; send back default dataset
- $lockdata = array(
- 'active' => false,
- 'threshold' => $threshold,
- 'duration' => ( $duration / 60 ),
- 'fails' => 0,
- 'policy' => $policy,
- 'last_time' => 0,
- 'time_rem' => 0,
- 'captcha' => ''
- );
- }
- return $lockdata;
- }
-
- /**
- * Creates/restores a guest session
- * @todo implement real session management for guests
- */
-
- function register_guest_session()
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
- global $lang;
- $this->username = $_SERVER['REMOTE_ADDR'];
- $this->user_level = USER_LEVEL_GUEST;
- if($this->compat || defined('IN_ENANO_INSTALL'))
- {
- $this->theme = 'oxygen';
- $this->style = 'bleu';
- }
- else
- {
- $this->theme = ( isset($_GET['theme']) && isset($template->named_theme_list[$_GET['theme']])) ? $_GET['theme'] : $template->default_theme;
- $this->style = ( isset($_GET['style']) && file_exists(ENANO_ROOT.'/themes/'.$this->theme . '/css/'.$_GET['style'].'.css' )) ? $_GET['style'] : preg_replace('/\.css$/', '', $template->named_theme_list[$this->theme]['default_style']);
- }
- $this->user_id = 1;
- // This is a VERY special case we are allowing. It lets the installer create languages using the Enano API.
- if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
- {
- $language = ( isset($_GET['lang']) && preg_match('/^[a-z0-9-_]+$/', @$_GET['lang']) ) ? $_GET['lang'] : intval(getConfig('default_language'));
- $lang = new Language($language);
- @setlocale(LC_ALL, $lang->lang_code);
- }
- // make a CSRF token
- $this->csrf_token = hmac_sha1($_SERVER['REMOTE_ADDR'], sha1($this->private_key));
- }
-
- /**
- * Validates a session key, and returns the userdata associated with the key or false
- * @param string $key The session key to validate
- * @return array Keys are 'user_id', 'username', 'email', 'real_name', 'user_level', 'theme', 'style', 'signature', 'reg_time', 'account_active', 'activation_key', and 'auth_level' or bool false if validation failed. The key 'auth_level' is the maximum authorization level that this key provides.
- */
-
- function validate_session($key)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
- profiler_log("SessionManager: checking session: " . sha1($key));
-
- if ( strlen($key) > 48 )
- {
- return $this->validate_aes_session($key);
- }
-
- profiler_log("SessionManager: checking session: " . $key);
-
- return $this->validate_session_shared($key, '');
- }
-
- /**
- * Validates an old-format AES session key. DO NOT USE THIS. Will return false if called outside of an upgrade.
- * @param string Session key
- * @return array
- */
-
- protected function validate_aes_session($key)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
-
- // No valid use except during upgrades
- if ( !preg_match('/^upg-/', enano_version()) && !defined('IN_ENANO_UPGRADE') )
- return false;
-
- $decrypted_key = $this->pk_decrypt($key);
- if ( !$decrypted_key )
- {
- // die_semicritical('AES encryption error', '
Something went wrong during the AES decryption process.
'.print_r($decrypted_key, true).'
');
- return false;
- }
-
- $n = preg_match('/^u='.$this->valid_username.';p=([A-Fa-f0-9]+?);s=(.{32})$/', $decrypted_key, $keydata);
- if($n < 1)
- {
- echo '(debug) $session->validate_session: Key does not match regex Decrypted key: '.$decrypted_key;
- return false;
- }
- $keyhash = md5($key);
- $salt = $db->escape($keydata[3]);
-
- return $this->validate_session_shared($keyhash, $salt, true);
- }
-
- /**
- * Shared portion of session validation. Do not try to call this.
- * @return array
- * @access private
- */
-
- protected function validate_session_shared($key, $salt, $loose_call = false)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
-
- // using a normal call to $db->sql_query to avoid failing on errors here
- $columns_select = "u.user_id AS uid, u.username, u.password, u.password_salt, u.email, u.real_name, u.user_level, u.theme,\n"
- . " u.style,u.signature, u.reg_time, u.account_active, u.activation_key, u.user_lang, u.user_title, k.salt, k.source_ip,\n"
- . " k.time, k.auth_level, k.key_type, COUNT(p.message_id) AS num_pms, u.user_timezone, u.user_dst, x.*";
-
- $columns_groupby = "u.user_id, u.username, u.password, u.password_salt, u.email, u.real_name, u.user_level, u.theme, u.style, u.signature,\n"
- . " u.reg_time, u.account_active, u.activation_key, u.user_lang, u.user_timezone, u.user_title, u.user_dst,\n"
- . " k.salt, k.source_ip, k.time, k.auth_level, k.key_type, x.user_id, x.user_aim, x.user_yahoo, x.user_msn,\n"
- . " x.user_xmpp, x.user_homepage, x.user_location, x.user_job, x.user_hobbies, x.email_public,\n"
- . " x.disable_js_fx, x.date_format, x.time_format";
-
- $joins = " LEFT JOIN " . table_prefix . "users AS u\n"
- . " ON ( u.user_id=k.user_id )\n"
- . " LEFT JOIN " . table_prefix . "users_extra AS x\n"
- . " ON ( u.user_id=x.user_id OR x.user_id IS NULL )\n"
- . " LEFT JOIN " . table_prefix . "privmsgs AS p\n"
- . " ON ( p.message_to=u.username AND p.message_read=0 )\n";
- if ( !$loose_call )
- {
- $key_md5 = md5($key);
- $query = $db->sql_query("SELECT $columns_select\n"
- . "FROM " . table_prefix . "session_keys AS k\n"
- . $joins
- . " WHERE k.session_key='$key_md5'\n"
- . " GROUP BY $columns_groupby;");
- }
- else
- {
- $query = $db->sql_query("SELECT $columns_select\n"
- . "FROM " . table_prefix . "session_keys AS k\n"
- . $joins
- . " WHERE k.session_key='$key'\n"
- . " AND k.salt='$salt'\n"
- . " GROUP BY $columns_groupby;");
- }
-
- if ( !$query && ( defined('IN_ENANO_INSTALL') or defined('IN_ENANO_UPGRADE') ) )
- {
- $key_md5 = $loose_call ? $key : md5($key);
- $query = $this->sql('SELECT u.user_id AS uid,u.username,u.password,\'\' AS password_salt,u.email,u.real_name,u.user_level,u.theme,u.style,u.signature,u.reg_time,u.account_active,u.activation_key,k.source_ip,k.time,k.auth_level,COUNT(p.message_id) AS num_pms, 1440 AS user_timezone, \'0;0;0;0;60\' AS user_dst, ' . SK_SHORT . ' AS key_type, k.salt FROM '.table_prefix.'session_keys AS k
- LEFT JOIN '.table_prefix.'users AS u
- ON ( u.user_id=k.user_id )
- LEFT JOIN '.table_prefix.'privmsgs AS p
- ON ( p.message_to=u.username AND p.message_read=0 )
- WHERE k.session_key=\''.$key_md5.'\'
- GROUP BY u.user_id,u.username,u.password,u.email,u.real_name,u.user_level,u.theme,u.style,u.signature,u.reg_time,u.account_active,u.activation_key,k.source_ip,k.time,k.auth_level,k.salt;');
- }
- else if ( !$query )
- {
- $db->_die();
- }
- if($db->numrows() < 1)
- {
- // echo '(debug) $session->validate_session: Key was not found in database: ' . $key_md5 . ' ';
- return false;
- }
- $row = $db->fetchrow();
- profiler_log("SessionManager: session check: selected and fetched results");
-
- $row['user_id'] =& $row['uid'];
- $ip = $_SERVER['REMOTE_ADDR'];
- if($row['auth_level'] > $row['user_level'])
- {
- // Failed authorization check
- // echo '(debug) $session->validate_session: access to this auth level denied ';
- return false;
- }
- if($ip != $row['source_ip'])
- {
- // Special exception for 1.1.x upgrade - the 1.1.3 upgrade changes the size of the column and this is what validate_session
- // expects, but if the column size hasn't changed yet just check the first 10 digits of the IP.
- $fail = true;
- if ( defined('IN_ENANO_UPGRADE') )
- {
- if ( substr($ip, 0, 10) == substr($row['source_ip'], 0, 10) )
- $fail = false;
- }
- // Failed IP address check
- // echo '(debug) $session->validate_session: IP address mismatch ';
- if ( $fail )
- return false;
- }
-
- // $loose_call is turned on only from validate_aes_session
- if ( !$loose_call )
- {
- $key_pieces = array($row['password']);
- $user_id =& $row['uid'];
- $sk_mode = 'validate';
- $code = $plugins->setHook('session_key_calc');
- foreach ( $code as $cmd )
- {
- eval($cmd);
- }
- $key_pieces = implode("\xFF", $key_pieces);
- $correct_key = hexdecode(hmac_sha1($key_pieces, $row['salt']));
- $user_key = hexdecode($key);
- if ( $correct_key !== $user_key || !is_string($user_key) )
- {
- return false;
- }
- }
- else
- {
- // if this is a "loose call", this only works once (during the final upgrade stage). Destroy the contents of session_keys.
- if ( $row['auth_level'] == USER_LEVEL_ADMIN && preg_match('/^upg-/', enano_version()) )
- $this->sql('DELETE FROM ' . table_prefix . "session_keys;");
- }
-
- // timestamp check
- switch ( $row['key_type'] )
- {
- case SK_SHORT:
- $time_now = time();
- $time_key = $row['time'] + ( 60 * intval(getConfig('session_short', '720')) );
- if ( $time_now > $time_key )
- {
- // Session timed out
- return false;
- }
- break;
- case SK_LONG:
- if ( intval(getConfig('session_remember_time', '0')) === 0 )
- {
- // sessions last infinitely, timestamp validation is therefore successful
- break;
- }
- $time_now = time();
- $time_key = $row['time'] + ( 86400 * intval(getConfig('session_remember_time', '30')) );
- if ( $time_now > $time_key )
- {
- // Session timed out
- return false;
- }
- break;
- case SK_ELEV:
- $time_now = time();
- $time_key = $row['time'] + 900;
- if($time_now > $time_key && $row['auth_level'] > USER_LEVEL_MEMBER)
- {
- // Session timed out
- // echo '(debug) $session->validate_session: super session timed out ';
- $this->sw_timed_out = true;
- return false;
- }
- break;
- }
-
- // If this is an elevated-access or short-term session key, update the time
- if( $row['key_type'] == SK_ELEV || $row['key_type'] == SK_SHORT )
- {
- $this->sql('UPDATE '.table_prefix.'session_keys SET time='.time().' WHERE session_key=\''.md5($key).'\';');
- }
-
- $user_extra = array();
- foreach ( array('user_aim', 'user_yahoo', 'user_msn', 'user_xmpp', 'user_homepage', 'user_location', 'user_job', 'user_hobbies', 'email_public', 'disable_js_fx') as $column )
- {
- if ( isset($row[$column]) )
- $user_extra[$column] = $row[$column];
- else
- $user_extra[$column] = '';
- }
-
- if ( isset($row['date_format']) )
- $this->date_format = $row['date_format'];
- if ( isset($row['time_format']) )
- $this->time_format = $row['time_format'];
-
- $this->user_extra = $user_extra;
- // Leave the rest to PHP's automatic garbage collector ;-)
-
- $row['password'] = '';
- $row['user_timezone'] = intval($row['user_timezone']) - 1440;
-
- profiler_log("SessionManager: finished session check");
-
- return $row;
- }
-
- /**
- * Validates a session key, and returns the userdata associated with the key or false. Optimized for compatibility with the old MD5-based auth system.
- * @param string $key The session key to validate
- * @return array Keys are 'user_id', 'username', 'email', 'real_name', 'user_level', 'theme', 'style', 'signature', 'reg_time', 'account_active', 'activation_key', and 'auth_level' or bool false if validation failed. The key 'auth_level' is the maximum authorization level that this key provides.
- */
-
- function compat_validate_session($key)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
- $key = $db->escape($key);
-
- $query = $this->sql('SELECT u.user_id,u.username,u.password,u.email,u.real_name,u.user_level,k.source_ip,k.salt,k.time,k.auth_level,1440 AS user_timezone FROM '.table_prefix.'session_keys AS k
- LEFT JOIN '.table_prefix.'users AS u
- ON u.user_id=k.user_id
- WHERE k.session_key=\''.$key.'\';');
- if($db->numrows() < 1)
- {
- // echo '(debug) $session->validate_session: Key '.$key.' was not found in database ';
- return false;
- }
- $row = $db->fetchrow();
- $ip = ip2hex($_SERVER['REMOTE_ADDR']);
- if($row['auth_level'] > $row['user_level'])
- {
- // Failed authorization check
- // echo '(debug) $session->validate_session: user not authorized for this access level';
- return false;
- }
- if($ip != $row['source_ip'])
- {
- // Failed IP address check
- // echo '(debug) $session->validate_session: IP address mismatch; IP in table: '.$row['source_ip'].'; reported IP: '.$ip.'';
- return false;
- }
-
- // Do the password validation
- $real_key = md5($row['password'] . $row['salt']);
-
- //die('
'.print_r($keydata, true).'
');
- if($real_key != $key)
- {
- // Failed password check
- // echo '(debug) $session->validate_session: supplied password is wrong Real key: '.$real_key.' User key: '.$key;
- return false;
- }
-
- $time_now = time();
- $time_key = $row['time'] + 900;
- if($time_now > $time_key && $row['auth_level'] >= 1)
- {
- $this->sw_timed_out = true;
- // Session timed out
- // echo '(debug) $session->validate_session: super session timed out ';
- return false;
- }
-
- $row['user_timezone'] = intval($row['user_timezone']) - 1440;
-
- return $row;
- }
-
- /**
- * Demotes us to one less than the specified auth level. AKA destroys elevated authentication and/or logs out the user, depending on $level
- * @param int $level How low we should go - USER_LEVEL_MEMBER means demote to USER_LEVEL_GUEST, and anything more powerful than USER_LEVEL_MEMBER means demote to USER_LEVEL_MEMBER
- * @return string 'success' if successful, or error on failure
- */
-
- function logout($level = USER_LEVEL_MEMBER)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
- $ou = $this->username;
- $oid = $this->user_id;
- if($level > USER_LEVEL_MEMBER)
- {
- $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
- if(!$this->user_logged_in || $this->auth_level < ( USER_LEVEL_MEMBER + 1))
- {
- return 'success';
- }
- // Destroy elevated privileges
- $keyhash = md5($this->sid_super);
- $this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.$keyhash.'\' AND user_id=\'' . $this->user_id . '\';');
- $this->sid_super = false;
- $this->auth_level = USER_LEVEL_MEMBER;
- }
- else
- {
- if($this->user_logged_in)
- {
- $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
- // Completely destroy our session
- if($this->auth_level > USER_LEVEL_MEMBER)
- {
- $this->logout(USER_LEVEL_ADMIN);
- }
- $this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.md5($this->sid).'\';');
- setcookie( 'sid', '', time()-(3600*24), scriptPath.'/' );
- }
- }
- $code = $plugins->setHook('logout_success'); // , Array('level'=>$level,'old_username'=>$ou,'old_user_id'=>$oid));
- foreach ( $code as $cmd )
- {
- eval($cmd);
- }
- return 'success';
- }
-
- # Miscellaneous stuff
-
- /**
- * Alerts the user that their account is inactive, and tells them appropriate steps to remedy the situation. Halts execution.
- * @param array Return from validate_session()
- */
-
- function show_inactive_error($userdata)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
- global $lang;
-
- global $title;
- $paths->init($title);
-
- $language = intval(getConfig('default_language'));
- $lang = new Language($language);
- @setlocale(LC_ALL, $lang->lang_code);
-
- $a = getConfig('account_activation');
- switch($a)
- {
- case 'none':
- default:
- $solution = $lang->get('user_login_noact_solution_none');
- break;
- case 'user':
- $solution = $lang->get('user_login_noact_solution_user');
- break;
- case 'admin':
- $solution = $lang->get('user_login_noact_solution_admin');
- break;
- }
-
- // admin activation request opportunity
- $q = $db->sql_query('SELECT 1 FROM '.table_prefix.'logs WHERE log_type=\'admin\' AND action=\'activ_req\' AND edit_summary=\'' . $db->escape($userdata['username']) . '\';');
- if ( !$q )
- $db->_die();
-
- $can_request = ( $db->numrows() < 1 );
- $db->free_result();
-
- if ( isset($_POST['logout']) )
- {
- $this->sid = $_COOKIE['sid'];
- $this->user_logged_in = true;
- $this->user_id = intval($userdata['user_id']);
- $this->username = $userdata['username'];
- $this->auth_level = USER_LEVEL_MEMBER;
- $this->user_level = USER_LEVEL_MEMBER;
- $this->logout();
- redirect(scriptPath . '/', $lang->get('user_login_noact_msg_logout_success_title'), $lang->get('user_login_noact_msg_logout_success_body'), 5);
- }
-
- if ( $can_request && !isset($_POST['activation_request']) )
- {
- $form = '
');
- exit;
- }
- }
-
- # Registration
-
- /**
- * Registers a user. This does not perform any type of login.
- * @param string New user's username
- * @param string This should be unencrypted.
- * @param string E-mail address.
- * @param string Optional, defaults to ''.
- * @param bool Optional. If true, the account is not activated initially and an admin activation request is sent. The caller is responsible for sending the address info and notice.
- */
-
- function create_user($username, $password, $email, $real_name = '', $coppa = false)
- {
- global $db, $session, $paths, $template, $plugins; // Common objects
- global $lang;
-
- // Initialize AES
- $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
-
- // Since we're recording IP addresses, make sure the user's IP is safe.
- $ip =& $_SERVER['REMOTE_ADDR'];
- if ( !is_valid_ip($ip) )
- return 'Invalid IP';
-
- if ( !preg_match('#^'.$this->valid_username.'$#', $username) )
- return $lang->get('user_reg_err_username_banned_chars');
-
- $username = str_replace('_', ' ', $username);
- $user_orig = $username;
- $username = $this->prepare_text($username);
- $email = $this->prepare_text($email);
- $real_name = $this->prepare_text($real_name);
-
- $nameclause = ( $real_name != '' ) ? ' OR real_name=\''.$real_name.'\'' : '';
- $q = $this->sql('SELECT * FROM '.table_prefix.'users WHERE ' . ENANO_SQLFUNC_LOWERCASE . '(username)=\''.strtolower($username).'\' OR email=\''.$email.'\''.$nameclause.';');
- if($db->numrows() > 0)
- {
- $row = $db->fetchrow();
- $str = 'user_reg_err_dupe';
-
- if ( $row['username'] == $username )
- {
- $str .= '_username';
- }
- if ( $row['email'] == $email )
- {
- $str .= '_email';
- }
- if ( $row['real_name'] == $real_name && $real_name != '' )
- {
- $str .= '_realname';
- }
-
- return $lang->get($str);
- }
-
- // Is the password strong enough?
- if ( getConfig('pw_strength_enable') )
- {
- $min_score = intval( getConfig('pw_strength_minimum') );
- $pass_score = password_score($password);
- if ( $pass_score < $min_score )
- {
- return $lang->get('user_reg_err_password_too_weak');
- }
- }
-
- // Require the account to be activated?
- switch(getConfig('account_activation'))
- {
- case 'none':
- default:
- $active = '1';
- break;
- case 'user':
- $active = '0';
- break;
- case 'admin':
- $active = '0';
- break;
- }
- if ( $coppa )
- $active = '0';
-
- $coppa_col = ( $coppa ) ? '1' : '0';
-
- // Generate a totally random activation key
- $actkey = sha1 ( microtime() . mt_rand() );
+
+ # Variables
+
+ /**
+ * Whether we're logged in or not
+ * @var bool
+ */
+
+ var $user_logged_in = false;
+
+ /**
+ * Our current low-privilege session key
+ * @var string
+ */
+
+ var $sid;
+
+ /**
+ * Username of currently logged-in user, or IP address if not logged in
+ * @var string
+ */
+
+ var $username;
+
+ /**
+ * User ID of currently logged-in user, or 1 if not logged in
+ * @var int
+ */
+
+ var $user_id = 1;
+
+ /**
+ * Real name of currently logged-in user, or blank if not logged in
+ * @var string
+ */
+
+ var $real_name;
+
+ /**
+ * E-mail address of currently logged-in user, or blank if not logged in
+ * @var string
+ */
+
+ var $email;
+
+ /**
+ * List of "extra" user information fields (IM handles, etc.)
+ * @var array (associative)
+ */
+
+ var $user_extra;
+
+ /**
+ * User level of current user
+ * USER_LEVEL_GUEST: guest
+ * USER_LEVEL_MEMBER: regular user
+ * USER_LEVEL_CHPREF: default - pseudo-level that allows changing password and e-mail address (requires re-authentication)
+ * USER_LEVEL_MOD: moderator
+ * USER_LEVEL_ADMIN: administrator
+ * @var int
+ */
+
+ var $user_level;
+
+ /**
+ * High-privilege session key
+ * @var string or false if not running on high-level authentication
+ */
+
+ var $sid_super;
+
+ /**
+ * The user's theme preference, defaults to $template->default_theme
+ * @var string
+ */
+
+ var $theme;
+
+ /**
+ * The user's style preference, or style auto-detected based on theme if not logged in
+ * @var string
+ */
+
+ var $style;
+
+ /**
+ * Signature of current user - appended to comments, etc.
+ * @var string
+ */
+
+ var $signature;
+
+ /**
+ * UNIX timestamp of when we were registered, or 0 if not logged in
+ * @var int
+ */
+
+ var $reg_time;
+
+ /**
+ * The number of unread private messages this user has.
+ * @var int
+ */
+
+ var $unread_pms = 0;
+
+ /**
+ * AES key used to encrypt passwords and session key info.
+ * @var string
+ * @access private
+ */
+
+ protected $private_key;
+
+ /**
+ * Regex that defines a valid username, minus the ^ and $, these are added later
+ * @var string
+ */
+
+ var $valid_username = '([^<>&\?\'"%\n\r\t\a\/]+)';
+
+ /**
+ * The current user's user title. Defaults to NULL.
+ * @var string
+ */
+
+ var $user_title = null;
+
+ /**
+ * What we're allowed to do as far as permissions go. This changes based on the value of the "auth" URI param.
+ * @var string
+ */
+
+ var $auth_level = 1;
+
+ /**
+ * Preference for date formatting
+ * @var string
+ */
+
+ var $date_format = DATE_4;
+
+ /**
+ * Preference for time formatting
+ * @var string
+ */
+
+ var $time_format = TIME_24_NS;
+
+ /**
+ * State variable to track if a session timed out
+ * @var bool
+ */
+
+ var $sw_timed_out = false;
+
+ /**
+ * Token appended to some important forms to prevent CSRF.
+ * @var string
+ */
+
+ var $csrf_token = false;
+
+ /**
+ * Password change disabled, for auth plugins
+ * @var bool
+ */
+
+ var $password_change_disabled = false;
+
+ /**
+ * Password change page URL + title, for auth plugins
+ * @var array
+ */
+
+ var $password_change_dest = array('url' => '', 'title' => '');
+
+ /**
+ * Switch to track if we're started or not.
+ * @access private
+ * @var bool
+ */
+
+ var $started = false;
+
+ /**
+ * Switch to control compatibility mode (for older Enano websites being upgraded)
+ * @access private
+ * @var bool
+ */
+
+ var $compat = false;
+
+ /**
+ * Our list of permission types.
+ * @access private
+ * @var array
+ */
+
+ var $acl_types = Array();
+
+ /**
+ * The list of descriptions for the permission types
+ * @var array
+ */
+
+ var $acl_descs = Array();
+
+ /**
+ * A list of dependencies for ACL types.
+ * @var array
+ */
+
+ var $acl_deps = Array();
+
+ /**
+ * Our tell-all list of permissions. Do not even try to change this.
+ * @access private
+ * @var array
+ */
+
+ var $perms = Array();
+
+ /**
+ * A cache variable - saved after sitewide permissions are checked but before page-specific permissions.
+ * @var array
+ * @access private
+ */
+
+ var $acl_base_cache = Array();
+
+ /**
+ * Stores the scope information for ACL types.
+ * @var array
+ * @access private
+ */
+
+ var $acl_scope = Array();
+
+ /**
+ * Array to track which default permissions are being used
+ * @var array
+ * @access private
+ */
+
+ var $acl_defaults_used = Array();
+
+ /**
+ * Array to track group membership.
+ * @var array
+ */
+
+ var $groups = Array();
+
+ /**
+ * Associative array to track group modship.
+ * @var array
+ */
+
+ var $group_mod = Array();
+
+ /**
+ * A constant array of user-level-to-rank default associations.
+ * @var array
+ */
+
+ var $level_rank_table = array(
+ USER_LEVEL_ADMIN => RANK_ID_ADMIN,
+ USER_LEVEL_MOD => RANK_ID_MOD,
+ USER_LEVEL_MEMBER => RANK_ID_MEMBER,
+ USER_LEVEL_CHPREF => RANK_ID_MEMBER,
+ USER_LEVEL_GUEST => RANK_ID_GUEST
+ );
+
+ /**
+ * A constant array that maps precedence constants to language strings
+ * @var array
+ */
+
+ var $acl_inherit_lang_table = array(
+ ACL_INHERIT_ENANO_DEFAULT => 'acl_inherit_enano_default',
+ ACL_INHERIT_GLOBAL_EVERYONE => 'acl_inherit_global_everyone',
+ ACL_INHERIT_GLOBAL_GROUP => 'acl_inherit_global_group',
+ ACL_INHERIT_GLOBAL_USER => 'acl_inherit_global_user',
+ ACL_INHERIT_PG_EVERYONE => 'acl_inherit_pg_everyone',
+ ACL_INHERIT_PG_GROUP => 'acl_inherit_pg_group',
+ ACL_INHERIT_PG_USER => 'acl_inherit_pg_user',
+ ACL_INHERIT_LOCAL_EVERYONE => 'acl_inherit_local_everyone',
+ ACL_INHERIT_LOCAL_GROUP => 'acl_inherit_local_group',
+ ACL_INHERIT_LOCAL_USER => 'acl_inherit_local_user'
+ );
+
+ # Basic functions
+
+ /**
+ * Constructor.
+ */
+
+ function __construct()
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+
+ if ( defined('IN_ENANO_INSTALL') && !defined('IN_ENANO_UPGRADE') )
+ {
+ @include(ENANO_ROOT.'/config.new.php');
+ }
+ else
+ {
+ @include(ENANO_ROOT.'/config.php');
+ }
+
+ unset($dbhost, $dbname, $dbuser, $dbpasswd);
+ if(isset($crypto_key))
+ {
+ $this->private_key = $crypto_key;
+ $this->private_key = hexdecode($this->private_key);
+ }
+ else
+ {
+ if(is_writable(ENANO_ROOT.'/config.php'))
+ {
+ // Generate and stash a private key
+ // This should only happen during an automated silent gradual migration to the new encryption platform.
+ $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
+ $this->private_key = $aes->gen_readymade_key();
+
+ $config = file_get_contents(ENANO_ROOT.'/config.php');
+ if(!$config)
+ {
+ die('$session->__construct(): can\'t get the contents of config.php');
+ }
+
+ $config = str_replace("?>", "\$crypto_key = '{$this->private_key}';\n?>", $config);
+ // And while we're at it...
+ $config = str_replace('MIDGET_INSTALLED', 'ENANO_INSTALLED', $config);
+ $fh = @fopen(ENANO_ROOT.'/config.php', 'w');
+ if ( !$fh )
+ {
+ die('$session->__construct(): Couldn\'t open config file for writing to store the private key, I tried to avoid something like this...');
+ }
+
+ fwrite($fh, $config);
+ fclose($fh);
+ }
+ else
+ {
+ die_semicritical('Crypto error', '
No private key was found in the config file, and we can\'t generate one because we don\'t have write access to the config file. Please CHMOD config.php to 666 or 777 and reload this page.
');
+ }
+ }
+ // Check for compatibility mode
+ if(defined('IN_ENANO_INSTALL'))
+ {
+ $q = $db->sql_query('SELECT old_encryption FROM '.table_prefix.'users LIMIT 1;');
+ if(!$q)
+ {
+ $error = mysql_error();
+ if(strstr($error, "Unknown column 'old_encryption'"))
+ $this->compat = true;
+ else
+ $db->_die('This should never happen and is a bug - the only error that was supposed to happen here didn\'t happen. (sessions.php in constructor, during compat mode check)');
+ }
+ $db->free_result();
+ }
+ }
+
+ /**
+ * PHP 4 compatible constructor. Deprecated in 1.1.x.
+ */
+
+ /*
+ function sessionManager()
+ {
+ $this->__construct();
+ }
+ */
+
+ /**
+ * Wrapper function to sanitize strings for MySQL and HTML
+ * @param string $text The text to sanitize
+ * @return string
+ */
+
+ function prepare_text($text)
+ {
+ global $db;
+ return $db->escape(htmlspecialchars($text));
+ }
+
+ /**
+ * Makes a SQL query and handles error checking
+ * @param string $query The SQL query to make
+ * @return resource
+ */
+
+ function sql($query)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+ $result = $db->sql_query($query);
+ if(!$result)
+ {
+ $db->_die('The error seems to have occurred somewhere in the session management code.');
+ }
+ return $result;
+ }
+
+ /**
+ * Returns true if we're currently on a page that shouldn't be blocked even if we have an inactive or banned account
+ * @param bool strict - if true, whitelist of pages is even stricter (Login, Logout and CSS only). if false (default), admin access is allowed, assuming other factors allow it
+ * @return bool
+ */
+
+ function on_critical_page($strict = false)
+ {
+ global $urlname;
+ list($page_id, $namespace) = RenderMan::strToPageID($urlname);
+ list($page_id) = explode('/', $page_id);
+
+ if ( $strict )
+ {
+ return $namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'LangExportJSON', 'ActivateAccount'));
+ }
+ else
+ {
+ return $namespace == 'Admin' || ($namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'Administration', 'LangExportJSON', 'ActivateAccount')));
+ }
+ }
+
+ # Session restoration and permissions
+
+ /**
+ * Initializes the basic state of things, including most user prefs, login data, cookie stuff
+ */
+
+ function start()
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+ global $lang;
+ global $timezone;
+ if($this->started) return;
+ $this->started = true;
+ $user = false;
+ if ( isset($_COOKIE['sid']) )
+ {
+ if ( $this->compat )
+ {
+ $userdata = $this->compat_validate_session($_COOKIE['sid']);
+ }
+ else
+ {
+ $userdata = $this->validate_session($_COOKIE['sid']);
+ }
+ if ( is_array($userdata) )
+ {
+ $this->sid = $_COOKIE['sid'];
+ $this->user_logged_in = true;
+ $this->user_id = intval($userdata['user_id']);
+ $this->username = $userdata['username'];
+ $this->user_level = intval($userdata['user_level']);
+ $this->real_name = $userdata['real_name'];
+ $this->email = $userdata['email'];
+ $this->unread_pms = $userdata['num_pms'];
+ $this->user_title = ( isset($userdata['user_title']) ) ? $userdata['user_title'] : null;
+ if(!$this->compat)
+ {
+ $this->theme = $userdata['theme'];
+ $this->style = $userdata['style'];
+ $this->signature = $userdata['signature'];
+ $this->reg_time = $userdata['reg_time'];
+ }
+ $this->auth_level = USER_LEVEL_MEMBER;
+ // generate an anti-CSRF token
+ $this->csrf_token = sha1($this->username . $this->sid . $this->user_id);
+ if(!isset($template->named_theme_list[$this->theme]))
+ {
+ if($this->compat || !is_object($template))
+ {
+ $this->theme = 'oxygen';
+ $this->style = 'bleu';
+ }
+ else
+ {
+ $this->theme = $template->default_theme;
+ $this->style = $template->default_style;
+ }
+ }
+ $user = true;
+
+ // set timezone params
+ $GLOBALS['timezone'] = $userdata['user_timezone'];
+ $GLOBALS['dst_params'] = explode(';', $userdata['user_dst']);
+ foreach ( $GLOBALS['dst_params'] as &$parm )
+ {
+ if ( substr($parm, -1) != 'd' )
+ $parm = intval($parm);
+ }
+
+ // Set language
+ if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
+ {
+ $lang_id = intval($userdata['user_lang']);
+ $lang = new Language($lang_id);
+ @setlocale(LC_ALL, $lang->lang_code);
+ }
+
+ if(isset($_REQUEST['auth']) && !$this->sid_super)
+ {
+ // Now he thinks he's a moderator. Or maybe even an administrator. Let's find out if he's telling the truth.
+ if($this->compat)
+ {
+ $key = $_REQUEST['auth'];
+ $super = $this->compat_validate_session($key);
+ }
+ else
+ {
+ $key = $_REQUEST['auth'];
+ if ( !empty($key) && ( strlen($key) / 2 ) % 4 == 0 )
+ {
+ $super = $this->validate_session($key);
+ }
+ }
+ if(is_array(@$super))
+ {
+ $this->auth_level = intval($super['auth_level']);
+ $this->sid_super = $_REQUEST['auth'];
+ }
+ }
+ }
+ }
+ if(!$user)
+ {
+ //exit;
+ $this->register_guest_session();
+ }
+ if(!$this->compat)
+ {
+ // init groups
+ $q = $this->sql('SELECT g.group_name,g.group_id,m.is_mod FROM '.table_prefix.'groups AS g' . "\n"
+ . ' LEFT JOIN '.table_prefix.'group_members AS m' . "\n"
+ . ' ON g.group_id=m.group_id' . "\n"
+ . ' WHERE ( m.user_id='.$this->user_id.'' . "\n"
+ . ' OR g.group_name=\'Everyone\')' . "\n"
+ . ' ' . ( /* quick hack for upgrade compatibility reasons */ enano_version() == '1.0RC1' ? '' : 'AND ( m.pending != 1 OR m.pending IS NULL )' ) . '' . "\n"
+ . ' ORDER BY group_id ASC;'); // The ORDER BY is to make sure "Everyone" comes first so the permissions can be overridden
+ if($row = $db->fetchrow())
+ {
+ do {
+ $this->groups[$row['group_id']] = $row['group_name'];
+ $this->group_mod[$row['group_id']] = ( intval($row['is_mod']) == 1 );
+ } while($row = $db->fetchrow());
+ }
+ else
+ {
+ die('No group info');
+ }
+ profiler_log('Fetched group memberships');
+ }
+
+ // make sure we aren't banned
+ $this->check_banlist();
+
+ // make sure the account is active
+ if ( !$this->compat && $this->user_logged_in && $userdata['account_active'] < 1 && !$this->on_critical_page() )
+ {
+ $this->show_inactive_error($userdata);
+ }
+
+ // Printable page view? Probably the wrong place to control
+ // it but $template is pretty dumb, it will just about always
+ // do what you ask it to do, which isn't always what we want
+ if ( isset ( $_GET['printable'] ) )
+ {
+ $this->theme = 'printable';
+ $this->style = 'default';
+ }
+
+ // setup theme ACLs
+ $template->process_theme_acls();
+
+ profiler_log('Sessions started. Banlist and theme ACLs initialized');
+ }
+
+ # Logins
+
+ /**
+ * Attempts to perform a login using crypto functions
+ * @param string $username The username
+ * @param string $aes_data The encrypted password, hex-encoded
+ * @param string $aes_key The MD5 hash of the encryption key, hex-encoded
+ * @param string $challenge The 256-bit MD5 challenge string - first 128 bits should be the hash, the last 128 should be the challenge salt
+ * @param int $level The privilege level we're authenticating for, defaults to 0
+ * @param string $captcha_hash Optional. If we're locked out and the lockout policy is captcha, this should be the identifier for the code.
+ * @param string $captcha_code Optional. If we're locked out and the lockout policy is captcha, this should be the code the user entered.
+ * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
+ * @param bool $lookup_key Optional. If true (default) this queries the database for the "real" encryption key. Else, uses what is given.
+ * @return string 'success' on success, or error string on failure
+ */
+
+ function login_with_crypto($username, $aes_data, $aes_key_id, $challenge, $level = USER_LEVEL_MEMBER, $captcha_hash = false, $captcha_code = false, $remember = false, $lookup_key = true)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+
+ // Instanciate the Rijndael encryption object
+ $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
+
+ // Fetch our decryption key
+
+ if ( $lookup_key )
+ {
+ $aes_key = $this->fetch_public_key($aes_key_id);
+ if ( !$aes_key )
+ {
+ // It could be that our key cache is full. If it seems larger than 65KB, clear it
+ if ( strlen(getConfig('login_key_cache')) > 65000 )
+ {
+ setConfig('login_key_cache', '');
+ return array(
+ 'success' => false,
+ 'error' => 'key_not_found_cleared',
+ );
+ }
+ return array(
+ 'success' => false,
+ 'error' => 'key_not_found'
+ );
+ }
+ }
+ else
+ {
+ $aes_key =& $aes_key_id;
+ }
+
+ // Convert the key to a binary string
+ $bin_key = hexdecode($aes_key);
+
+ if(strlen($bin_key) != AES_BITS / 8)
+ return array(
+ 'success' => false,
+ 'error' => 'key_wrong_length'
+ );
+
+ // Decrypt our password
+ $password = $aes->decrypt($aes_data, $bin_key, ENC_HEX);
+
+ // Let the LoginAPI do the rest.
+ return $this->login_without_crypto($username, $password, false, $level, $captcha_hash, $captcha_code, $remember);
+ }
+
+ /**
+ * Attempts to login without using crypto stuff, mainly for use when the other side doesn't like Javascript
+ * This method of authentication is inherently insecure, there's really nothing we can do about it except hope and pray that everyone moves to Firefox
+ * Technically it still uses crypto, but it only decrypts the password already stored, which is (obviously) required for authentication
+ * @param string $username The username
+ * @param string $password The password -OR- the MD5 hash of the password if $already_md5ed is true
+ * @param bool $already_md5ed This should be set to true if $password is an MD5 hash, and should be false if it's plaintext. Defaults to false.
+ * @param int $level The privilege level we're authenticating for, defaults to 0
+ * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
+ */
+
+ function login_without_crypto($username, $password, $already_md5ed = false, $level = USER_LEVEL_MEMBER, $remember = false)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+
+ if ( $already_md5ed )
+ {
+ // No longer supported
+ return array(
+ 'mode' => 'error',
+ 'error' => '$already_md5ed is no longer supported (set this parameter to false and make sure the password you send to $session->login_without_crypto() is not hashed)'
+ );
+ }
+
+ // Replace underscores with spaces in username
+ // (Added in 1.0.2)
+ $username = str_replace('_', ' ', $username);
+
+ // Perhaps we're upgrading Enano?
+ if($this->compat)
+ {
+ return $this->login_compat($username, md5($password), $level);
+ }
+
+ // Instanciate the Rijndael encryption object
+ $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
+
+ // Initialize our success switch
+ $success = false;
+
+ // Retrieve the real password from the database
+ $username_db = $db->escape(strtolower($username));
+ $username_db_upper = $db->escape($username);
+ if ( !$db->sql_query('SELECT password,password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
+ . " WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );") )
+ {
+ $this->sql('SELECT password,\'\' AS password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
+ . " WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );");
+ }
+ if ( $db->numrows() < 1 )
+ {
+ // This wasn't logged in <1.0.2, dunno how it slipped through
+ if ( $level > USER_LEVEL_MEMBER )
+ $this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES\n"
+ . ' (\'security\', \'admin_auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
+ . '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
+ else
+ $this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary) VALUES\n"
+ . ' (\'security\', \'auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
+ . '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
+
+ // Do we also need to increment the lockout countdown?
+ if ( !defined('IN_ENANO_INSTALL') )
+ $lockout_data = $this->get_lockout_info();
+ else
+ $lockout_data = array(
+ 'lockout_policy' => 'disable'
+ );
+
+ if ( $lockout_data['policy'] != 'disable' && !defined('IN_ENANO_INSTALL') )
+ {
+ $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+ // increment fail count
+ $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
+ $lockout_data['fails']++;
+ return array(
+ 'success' => false,
+ 'error' => ( $lockout_data['fails'] >= $lockout_data['threshold'] ) ? 'locked_out' : 'invalid_credentials',
+ 'lockout_threshold' => $lockout_data['threshold'],
+ 'lockout_duration' => ( $lockout_data['duration'] ),
+ 'lockout_fails' => $lockout_data['fails'],
+ 'lockout_policy' => $lockout_data['policy']
+ );
+ }
+
+ return array(
+ 'success' => false,
+ 'error' => 'invalid_credentials'
+ );
+ }
+ $row = $db->fetchrow();
+
+ // Check to see if we're logging in using a temporary password
+
+ if((intval($row['temp_password_time']) + 3600*24) > time() )
+ {
+ $temp_pass = hmac_sha1($password, $row['password_salt']);
+ if( $temp_pass === $row['temp_password'] )
+ {
+ $code = $plugins->setHook('login_password_reset');
+ foreach ( $code as $cmd )
+ {
+ eval($cmd);
+ }
+
+ return array(
+ 'success' => false,
+ 'error' => 'valid_reset',
+ 'redirect_url' => makeUrlComplete('Special', 'PasswordReset/stage2/' . $row['user_id'] . '/' . $this->pk_encrypt($password))
+ );
+ }
+ }
+
+ if ( $row['old_encryption'] == 1 )
+ {
+ // The user's password is stored using the obsolete and insecure MD5 algorithm - we'll update the field with the new password
+ if(md5($password) === $row['password'])
+ {
+ if ( !defined('IN_ENANO_UPGRADE') )
+ {
+ $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
+ $password_hmac = hmac_sha1($password, $hmac_secret);
+ $this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
+ }
+ $success = true;
+ }
+ }
+ else if ( $row['old_encryption'] == 2 || ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') ) && strlen($row['password']) != 40 )
+ {
+ // Our password field uses the 1.0RC1-1.1.5 encryption format
+ $real_pass = $aes->decrypt($row['password'], $this->private_key);
+ if($password === $real_pass)
+ {
+ if ( !defined('IN_ENANO_UPGRADE') )
+ {
+ $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
+ $password_hmac = hmac_sha1($password, $hmac_secret);
+ $this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
+ }
+ $success = true;
+ }
+ }
+ else
+ {
+ // Password uses HMAC-SHA1
+ $user_challenge = hmac_sha1($password, $row['password_salt']);
+ $password_hmac =& $row['password'];
+ if ( $user_challenge === $password_hmac )
+ {
+ $success = true;
+ }
+ }
+ if($success)
+ {
+ if((int)$level > (int)$row['user_level'])
+ return array(
+ 'success' => false,
+ 'error' => 'too_big_for_britches'
+ );
+
+ // grant session
+ $sess = $this->register_session($row['user_id'], $username, ( isset($password_hmac) ? $password_hmac : $password ), $level, $remember);
+
+ if($sess)
+ {
+ if($level > USER_LEVEL_MEMBER)
+ $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,edit_summary,page_text) VALUES(\'security\', \'admin_auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', ' . $row['user_id'] . ', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
+ else
+ $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,edit_summary) VALUES(\'security\', \'auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', ' . $row['user_id'] . ', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
+
+ $code = $plugins->setHook('login_success');
+ foreach ( $code as $cmd )
+ {
+ eval($cmd);
+ }
+
+ return array(
+ 'success' => true
+ );
+ }
+ else
+ return array(
+ 'success' => false,
+ 'error' => 'backend_fail'
+ );
+ }
+ else
+ {
+ if($level > USER_LEVEL_MEMBER)
+ $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
+ else
+ $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
+
+ // Do we also need to increment the lockout countdown?
+ if ( !defined('IN_ENANO_INSTALL') && getConfig('lockout_policy', 'lockout') !== 'disable' )
+ {
+ $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+ // increment fail count
+ $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
+ }
+
+ return array(
+ 'success' => false,
+ 'error' => 'invalid_credentials'
+ );
+ }
+ }
+
+ /**
+ * Attempts to log in using the old table structure and algorithm. This is for upgrades from old 1.0.x releases.
+ * @param string $username
+ * @param string $password This should be an MD5 hash
+ * @return string 'success' if successful, or error message on failure
+ */
+
+ function login_compat($username, $password, $level = 0)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+ $pass_hashed =& $password;
+ $this->sql('SELECT password,user_id,user_level FROM '.table_prefix.'users WHERE username=\''.$this->prepare_text($username).'\';');
+ if($db->numrows() < 1)
+ return 'The username and/or password is incorrect.';
+ $row = $db->fetchrow();
+ if($row['password'] == $password)
+ {
+ if((int)$level > (int)$row['user_level'])
+ return 'You are not authorized for this level of access.';
+ $sess = $this->register_session_compat(intval($row['user_id']), $username, $password, $level);
+ if($sess)
+ return 'success';
+ else
+ return 'Your login credentials were correct, but an internal error occured while registering the session key in the database.';
+ }
+ else
+ {
+ return 'The username and/or password is incorrect.';
+ }
+ }
+
+ /**
+ * Registers a session key in the database. This function *ASSUMES* that the username and password have already been validated!
+ * Basically the session key is a hex-encoded cookie (encrypted with the site's private key) that says "u=[username];p=[sha1 of password];s=[unique key id]"
+ * @param int $user_id
+ * @param string $username
+ * @param string $password_hmac The HMAC of the user's password, right from the database
+ * @param int $level The level of access to grant, defaults to USER_LEVEL_MEMBER
+ * @param bool $remember Whether the session should be long-term (true) or not (false). Defaults to short-term.
+ * @return bool
+ */
+
+ function register_session($user_id, $username, $password_hmac, $level = USER_LEVEL_MEMBER, $remember = false)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+
+ // Random key identifier
+ $salt = '';
+ for ( $i = 0; $i < 32; $i++ )
+ {
+ $salt .= chr(mt_rand(32, 126));
+ }
+
+ // Session key
+ if ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') )
+ {
+ $session_key = $this->pk_encrypt("u=$username;p=" . sha1($password_hmac) . ";s=$salt");
+ }
+ else
+ {
+ $key_pieces = array($password_hmac);
+ $sk_mode = 'generate';
+ $code = $plugins->setHook('session_key_calc');
+ foreach ( $code as $cmd )
+ {
+ eval($cmd);
+ }
+ $key_pieces = implode("\xFF", $key_pieces);
+
+ $session_key = hmac_sha1($key_pieces, $salt);
+ }
+
+ // Minimum level
+ $level = max(array($level, USER_LEVEL_MEMBER));
+
+ // Type of key
+ $key_type = ( $level > USER_LEVEL_MEMBER ) ? SK_ELEV : ( $remember ? SK_LONG : SK_SHORT );
+
+ // If we're registering an elevated-privilege key, it needs to be on GET
+ if($level > USER_LEVEL_MEMBER)
+ {
+ $this->sid_super = $session_key;
+ $_GET['auth'] = $session_key;
+ }
+ else
+ {
+ // Stash it in a cookie
+ // For now, make the cookie last forever, we can change this in 1.1.x
+ setcookie( 'sid', $session_key, time()+15552000, scriptPath.'/', null, $GLOBALS['is_https']);
+ $_COOKIE['sid'] = $session_key;
+ $this->sid = $session_key;
+ }
+ // $keyhash is stored in the database, this is for compatibility with the older DB structure
+ $keyhash = md5($session_key);
+ // Record the user's IP
+ $ip = $_SERVER['REMOTE_ADDR'];
+ if(!is_valid_ip($ip))
+ die('$session->register_session: Remote-Addr was spoofed');
+ // The time needs to be stashed to enforce the 15-minute limit on elevated session keys
+ $time = time();
+
+ // Sanity check
+ if(!is_int($user_id))
+ die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
+ if(!is_int($level))
+ die(var_dump($level) . ' Somehow an SQL injection attempt crawled into our session registrar! (2)');
+
+ // Update RAM
+ $this->user_id = $user_id;
+ $this->user_level = max(array($this->user_level, $level));
+
+ // All done!
+ $query = $db->sql_query('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time, key_type) VALUES(\''.$keyhash.'\', \''.$db->escape($salt).'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.', ' . $key_type . ');');
+ if ( !$query && defined('IN_ENANO_UPGRADE') )
+ // we're trying to upgrade so the key_type column is probably missing - try it again without specifying the key type
+ $this->sql('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time) VALUES(\''.$keyhash.'\', \''.$db->escape($salt).'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.');');
+
+ return true;
+ }
+
+ /**
+ * Identical to register_session in nature, but uses the old login/table structure. DO NOT use this except in the upgrade script under very controlled circumstances.
+ * @see sessionManager::register_session()
+ * @access private
+ */
+
+ function register_session_compat($user_id, $username, $password, $level = 0)
+ {
+ $salt = md5(microtime() . mt_rand());
+ $thekey = md5($password . $salt);
+ if($level > 0)
+ {
+ $this->sid_super = $thekey;
+ }
+ else
+ {
+ setcookie( 'sid', $thekey, time()+315360000, scriptPath.'/' );
+ $_COOKIE['sid'] = $thekey;
+ }
+ $ip = ip2hex($_SERVER['REMOTE_ADDR']);
+ if(!$ip)
+ die('$session->register_session: Remote-Addr was spoofed');
+ $time = time();
+ if(!is_int($user_id))
+ die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
+ if(!is_int($level))
+ die('Somehow an SQL injection attempt crawled into our session registrar! (2)');
+ $query = $this->sql('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time) VALUES(\''.$thekey.'\', \''.$salt.'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.');');
+ return true;
+ }
+
+ /**
+ * Tells us if we're locked out from logging in or not.
+ * @param reference will be filled with information regarding in-progress lockout
+ * @return bool True if locked out, false otherwise
+ */
+
+ function get_lockout_info()
+ {
+ global $db;
+
+ // this has to be initialized to hide warnings
+ $lockdata = null;
+
+ // Query database for lockout info
+ $locked_out = false;
+ $threshold = ( $_ = getConfig('lockout_threshold') ) ? intval($_) : 5;
+ $duration = ( $_ = getConfig('lockout_duration') ) ? intval($_) : 15;
+ // convert to seconds
+ $duration = $duration * 60;
+ // decide on policy
+ $policy = ( $x = getConfig('lockout_policy') && in_array(getConfig('lockout_policy'), array('lockout', 'disable', 'captcha')) ) ? getConfig('lockout_policy') : 'lockout';
+ if ( $policy != 'disable' )
+ {
+ // enabled; make decision
+ $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+ $timestamp_cutoff = time() - $duration;
+ $q = $this->sql('SELECT timestamp FROM ' . table_prefix . 'lockout WHERE timestamp > ' . $timestamp_cutoff . ' AND ipaddr = \'' . $ipaddr . '\' ORDER BY timestamp DESC;');
+ $fails = $db->numrows($q);
+ $row = $db->fetchrow($q);
+ $locked_out = ( $fails >= $threshold );
+ $lockdata = array(
+ 'active' => $locked_out,
+ 'threshold' => $threshold,
+ 'duration' => ( $duration / 60 ),
+ 'fails' => $fails,
+ 'policy' => $policy,
+ 'last_time' => $row['timestamp'],
+ 'time_rem' => $locked_out ? ( $duration / 60 ) - round( ( time() - $row['timestamp'] ) / 60 ) : 0,
+ 'captcha' => $policy == 'captcha' ? $this->make_captcha() : ''
+ );
+ $db->free_result();
+ }
+ else
+ {
+ // disabled; send back default dataset
+ $lockdata = array(
+ 'active' => false,
+ 'threshold' => $threshold,
+ 'duration' => ( $duration / 60 ),
+ 'fails' => 0,
+ 'policy' => $policy,
+ 'last_time' => 0,
+ 'time_rem' => 0,
+ 'captcha' => ''
+ );
+ }
+ return $lockdata;
+ }
+
+ /**
+ * Creates/restores a guest session
+ * @todo implement real session management for guests
+ */
+
+ function register_guest_session()
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+ global $lang;
+ $this->username = $_SERVER['REMOTE_ADDR'];
+ $this->user_level = USER_LEVEL_GUEST;
+ if($this->compat || defined('IN_ENANO_INSTALL'))
+ {
+ $this->theme = 'oxygen';
+ $this->style = 'bleu';
+ }
+ else
+ {
+ $this->theme = ( isset($_GET['theme']) && isset($template->named_theme_list[$_GET['theme']])) ? $_GET['theme'] : $template->default_theme;
+ $this->style = ( isset($_GET['style']) && file_exists(ENANO_ROOT.'/themes/'.$this->theme . '/css/'.$_GET['style'].'.css' )) ? $_GET['style'] : preg_replace('/\.css$/', '', $template->named_theme_list[$this->theme]['default_style']);
+ }
+ $this->user_id = 1;
+ // This is a VERY special case we are allowing. It lets the installer create languages using the Enano API.
+ if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
+ {
+ $language = ( isset($_GET['lang']) && preg_match('/^[a-z0-9-_]+$/', @$_GET['lang']) ) ? $_GET['lang'] : intval(getConfig('default_language'));
+ $lang = new Language($language);
+ @setlocale(LC_ALL, $lang->lang_code);
+ }
+ // make a CSRF token
+ $this->csrf_token = hmac_sha1($_SERVER['REMOTE_ADDR'], sha1($this->private_key));
+ }
+
+ /**
+ * Validates a session key, and returns the userdata associated with the key or false
+ * @param string $key The session key to validate
+ * @return array Keys are 'user_id', 'username', 'email', 'real_name', 'user_level', 'theme', 'style', 'signature', 'reg_time', 'account_active', 'activation_key', and 'auth_level' or bool false if validation failed. The key 'auth_level' is the maximum authorization level that this key provides.
+ */
+
+ function validate_session($key)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+ profiler_log("SessionManager: checking session: " . sha1($key));
+
+ if ( strlen($key) > 48 )
+ {
+ return $this->validate_aes_session($key);
+ }
+
+ profiler_log("SessionManager: checking session: " . $key);
+
+ return $this->validate_session_shared($key, '');
+ }
+
+ /**
+ * Validates an old-format AES session key. DO NOT USE THIS. Will return false if called outside of an upgrade.
+ * @param string Session key
+ * @return array
+ */
+
+ protected function validate_aes_session($key)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+
+ // No valid use except during upgrades
+ if ( !preg_match('/^upg-/', enano_version()) && !defined('IN_ENANO_UPGRADE') )
+ return false;
+
+ $decrypted_key = $this->pk_decrypt($key);
+ if ( !$decrypted_key )
+ {
+ // die_semicritical('AES encryption error', '
Something went wrong during the AES decryption process.
'.print_r($decrypted_key, true).'
');
+ return false;
+ }
+
+ $n = preg_match('/^u='.$this->valid_username.';p=([A-Fa-f0-9]+?);s=(.{32})$/', $decrypted_key, $keydata);
+ if($n < 1)
+ {
+ echo '(debug) $session->validate_session: Key does not match regex Decrypted key: '.$decrypted_key;
+ return false;
+ }
+ $keyhash = md5($key);
+ $salt = $db->escape($keydata[3]);
+
+ return $this->validate_session_shared($keyhash, $salt, true);
+ }
+
+ /**
+ * Shared portion of session validation. Do not try to call this.
+ * @return array
+ * @access private
+ */
+
+ protected function validate_session_shared($key, $salt, $loose_call = false)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+
+ // using a normal call to $db->sql_query to avoid failing on errors here
+ $columns_select = "u.user_id AS uid, u.username, u.password, u.password_salt, u.email, u.real_name, u.user_level, u.theme,\n"
+ . " u.style,u.signature, u.reg_time, u.account_active, u.activation_key, u.user_lang, u.user_title, k.salt, k.source_ip,\n"
+ . " k.time, k.auth_level, k.key_type, COUNT(p.message_id) AS num_pms, u.user_timezone, u.user_dst, x.*";
+
+ $columns_groupby = "u.user_id, u.username, u.password, u.password_salt, u.email, u.real_name, u.user_level, u.theme, u.style, u.signature,\n"
+ . " u.reg_time, u.account_active, u.activation_key, u.user_lang, u.user_timezone, u.user_title, u.user_dst,\n"
+ . " k.salt, k.source_ip, k.time, k.auth_level, k.key_type, x.user_id, x.user_aim, x.user_yahoo, x.user_msn,\n"
+ . " x.user_xmpp, x.user_homepage, x.user_location, x.user_job, x.user_hobbies, x.email_public,\n"
+ . " x.disable_js_fx, x.date_format, x.time_format";
+
+ $joins = " LEFT JOIN " . table_prefix . "users AS u\n"
+ . " ON ( u.user_id=k.user_id )\n"
+ . " LEFT JOIN " . table_prefix . "users_extra AS x\n"
+ . " ON ( u.user_id=x.user_id OR x.user_id IS NULL )\n"
+ . " LEFT JOIN " . table_prefix . "privmsgs AS p\n"
+ . " ON ( p.message_to=u.username AND p.message_read=0 )\n";
+ if ( !$loose_call )
+ {
+ $key_md5 = md5($key);
+ $query = $db->sql_query("SELECT $columns_select\n"
+ . "FROM " . table_prefix . "session_keys AS k\n"
+ . $joins
+ . " WHERE k.session_key='$key_md5'\n"
+ . " GROUP BY $columns_groupby;");
+ }
+ else
+ {
+ $query = $db->sql_query("SELECT $columns_select\n"
+ . "FROM " . table_prefix . "session_keys AS k\n"
+ . $joins
+ . " WHERE k.session_key='$key'\n"
+ . " AND k.salt='$salt'\n"
+ . " GROUP BY $columns_groupby;");
+ }
+
+ if ( !$query && ( defined('IN_ENANO_INSTALL') or defined('IN_ENANO_UPGRADE') ) )
+ {
+ $key_md5 = $loose_call ? $key : md5($key);
+ $query = $this->sql('SELECT u.user_id AS uid,u.username,u.password,\'\' AS password_salt,u.email,u.real_name,u.user_level,u.theme,u.style,u.signature,u.reg_time,u.account_active,u.activation_key,k.source_ip,k.time,k.auth_level,COUNT(p.message_id) AS num_pms, 1440 AS user_timezone, \'0;0;0;0;60\' AS user_dst, ' . SK_SHORT . ' AS key_type, k.salt FROM '.table_prefix.'session_keys AS k
+ LEFT JOIN '.table_prefix.'users AS u
+ ON ( u.user_id=k.user_id )
+ LEFT JOIN '.table_prefix.'privmsgs AS p
+ ON ( p.message_to=u.username AND p.message_read=0 )
+ WHERE k.session_key=\''.$key_md5.'\'
+ GROUP BY u.user_id,u.username,u.password,u.email,u.real_name,u.user_level,u.theme,u.style,u.signature,u.reg_time,u.account_active,u.activation_key,k.source_ip,k.time,k.auth_level,k.salt;');
+ }
+ else if ( !$query )
+ {
+ $db->_die();
+ }
+ if($db->numrows() < 1)
+ {
+ // echo '(debug) $session->validate_session: Key was not found in database: ' . $key_md5 . ' ';
+ return false;
+ }
+ $row = $db->fetchrow();
+ profiler_log("SessionManager: session check: selected and fetched results");
+
+ $row['user_id'] =& $row['uid'];
+ $ip = $_SERVER['REMOTE_ADDR'];
+ if($row['auth_level'] > $row['user_level'])
+ {
+ // Failed authorization check
+ // echo '(debug) $session->validate_session: access to this auth level denied ';
+ return false;
+ }
+ if($ip != $row['source_ip'])
+ {
+ // Special exception for 1.1.x upgrade - the 1.1.3 upgrade changes the size of the column and this is what validate_session
+ // expects, but if the column size hasn't changed yet just check the first 10 digits of the IP.
+ $fail = true;
+ if ( defined('IN_ENANO_UPGRADE') )
+ {
+ if ( substr($ip, 0, 10) == substr($row['source_ip'], 0, 10) )
+ $fail = false;
+ }
+ // Failed IP address check
+ // echo '(debug) $session->validate_session: IP address mismatch ';
+ if ( $fail )
+ return false;
+ }
+
+ // $loose_call is turned on only from validate_aes_session
+ if ( !$loose_call )
+ {
+ $key_pieces = array($row['password']);
+ $user_id =& $row['uid'];
+ $sk_mode = 'validate';
+ $code = $plugins->setHook('session_key_calc');
+ foreach ( $code as $cmd )
+ {
+ eval($cmd);
+ }
+ $key_pieces = implode("\xFF", $key_pieces);
+ $correct_key = hexdecode(hmac_sha1($key_pieces, $row['salt']));
+ $user_key = hexdecode($key);
+ if ( $correct_key !== $user_key || !is_string($user_key) )
+ {
+ return false;
+ }
+ }
+ else
+ {
+ // if this is a "loose call", this only works once (during the final upgrade stage). Destroy the contents of session_keys.
+ if ( $row['auth_level'] == USER_LEVEL_ADMIN && preg_match('/^upg-/', enano_version()) )
+ $this->sql('DELETE FROM ' . table_prefix . "session_keys;");
+ }
+
+ // timestamp check
+ switch ( $row['key_type'] )
+ {
+ case SK_SHORT:
+ $time_now = time();
+ $time_key = $row['time'] + ( 60 * intval(getConfig('session_short', '720')) );
+ if ( $time_now > $time_key )
+ {
+ // Session timed out
+ return false;
+ }
+ break;
+ case SK_LONG:
+ if ( intval(getConfig('session_remember_time', '0')) === 0 )
+ {
+ // sessions last infinitely, timestamp validation is therefore successful
+ break;
+ }
+ $time_now = time();
+ $time_key = $row['time'] + ( 86400 * intval(getConfig('session_remember_time', '30')) );
+ if ( $time_now > $time_key )
+ {
+ // Session timed out
+ return false;
+ }
+ break;
+ case SK_ELEV:
+ $time_now = time();
+ $time_key = $row['time'] + 900;
+ if($time_now > $time_key && $row['auth_level'] > USER_LEVEL_MEMBER)
+ {
+ // Session timed out
+ // echo '(debug) $session->validate_session: super session timed out ';
+ $this->sw_timed_out = true;
+ return false;
+ }
+ break;
+ }
+
+ // If this is an elevated-access or short-term session key, update the time
+ if( $row['key_type'] == SK_ELEV || $row['key_type'] == SK_SHORT )
+ {
+ $this->sql('UPDATE '.table_prefix.'session_keys SET time='.time().' WHERE session_key=\''.md5($key).'\';');
+ }
+
+ $user_extra = array();
+ foreach ( array('user_aim', 'user_yahoo', 'user_msn', 'user_xmpp', 'user_homepage', 'user_location', 'user_job', 'user_hobbies', 'email_public', 'disable_js_fx') as $column )
+ {
+ if ( isset($row[$column]) )
+ $user_extra[$column] = $row[$column];
+ else
+ $user_extra[$column] = '';
+ }
+
+ if ( isset($row['date_format']) )
+ $this->date_format = $row['date_format'];
+ if ( isset($row['time_format']) )
+ $this->time_format = $row['time_format'];
+
+ $this->user_extra = $user_extra;
+ // Leave the rest to PHP's automatic garbage collector ;-)
+
+ $row['password'] = '';
+ $row['user_timezone'] = intval($row['user_timezone']) - 1440;
+
+ profiler_log("SessionManager: finished session check");
+
+ return $row;
+ }
+
+ /**
+ * Validates a session key, and returns the userdata associated with the key or false. Optimized for compatibility with the old MD5-based auth system.
+ * @param string $key The session key to validate
+ * @return array Keys are 'user_id', 'username', 'email', 'real_name', 'user_level', 'theme', 'style', 'signature', 'reg_time', 'account_active', 'activation_key', and 'auth_level' or bool false if validation failed. The key 'auth_level' is the maximum authorization level that this key provides.
+ */
+
+ function compat_validate_session($key)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+ $key = $db->escape($key);
+
+ $query = $this->sql('SELECT u.user_id,u.username,u.password,u.email,u.real_name,u.user_level,k.source_ip,k.salt,k.time,k.auth_level,1440 AS user_timezone FROM '.table_prefix.'session_keys AS k
+ LEFT JOIN '.table_prefix.'users AS u
+ ON u.user_id=k.user_id
+ WHERE k.session_key=\''.$key.'\';');
+ if($db->numrows() < 1)
+ {
+ // echo '(debug) $session->validate_session: Key '.$key.' was not found in database ';
+ return false;
+ }
+ $row = $db->fetchrow();
+ $ip = ip2hex($_SERVER['REMOTE_ADDR']);
+ if($row['auth_level'] > $row['user_level'])
+ {
+ // Failed authorization check
+ // echo '(debug) $session->validate_session: user not authorized for this access level';
+ return false;
+ }
+ if($ip != $row['source_ip'])
+ {
+ // Failed IP address check
+ // echo '(debug) $session->validate_session: IP address mismatch; IP in table: '.$row['source_ip'].'; reported IP: '.$ip.'';
+ return false;
+ }
+
+ // Do the password validation
+ $real_key = md5($row['password'] . $row['salt']);
+
+ //die('
'.print_r($keydata, true).'
');
+ if($real_key != $key)
+ {
+ // Failed password check
+ // echo '(debug) $session->validate_session: supplied password is wrong Real key: '.$real_key.' User key: '.$key;
+ return false;
+ }
+
+ $time_now = time();
+ $time_key = $row['time'] + 900;
+ if($time_now > $time_key && $row['auth_level'] >= 1)
+ {
+ $this->sw_timed_out = true;
+ // Session timed out
+ // echo '(debug) $session->validate_session: super session timed out ';
+ return false;
+ }
+
+ $row['user_timezone'] = intval($row['user_timezone']) - 1440;
+
+ return $row;
+ }
+
+ /**
+ * Demotes us to one less than the specified auth level. AKA destroys elevated authentication and/or logs out the user, depending on $level
+ * @param int $level How low we should go - USER_LEVEL_MEMBER means demote to USER_LEVEL_GUEST, and anything more powerful than USER_LEVEL_MEMBER means demote to USER_LEVEL_MEMBER
+ * @return string 'success' if successful, or error on failure
+ */
+
+ function logout($level = USER_LEVEL_MEMBER)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+ $ou = $this->username;
+ $oid = $this->user_id;
+ if($level > USER_LEVEL_MEMBER)
+ {
+ $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
+ if(!$this->user_logged_in || $this->auth_level < ( USER_LEVEL_MEMBER + 1))
+ {
+ return 'success';
+ }
+ // Destroy elevated privileges
+ $keyhash = md5($this->sid_super);
+ $this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.$keyhash.'\' AND user_id=\'' . $this->user_id . '\';');
+ $this->sid_super = false;
+ $this->auth_level = USER_LEVEL_MEMBER;
+ }
+ else
+ {
+ if($this->user_logged_in)
+ {
+ $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
+ // Completely destroy our session
+ if($this->auth_level > USER_LEVEL_MEMBER)
+ {
+ $this->logout(USER_LEVEL_ADMIN);
+ }
+ $this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.md5($this->sid).'\';');
+ setcookie( 'sid', '', time()-(3600*24), scriptPath.'/' );
+ }
+ }
+ $code = $plugins->setHook('logout_success'); // , Array('level'=>$level,'old_username'=>$ou,'old_user_id'=>$oid));
+ foreach ( $code as $cmd )
+ {
+ eval($cmd);
+ }
+ return 'success';
+ }
+
+ # Miscellaneous stuff
+
+ /**
+ * Alerts the user that their account is inactive, and tells them appropriate steps to remedy the situation. Halts execution.
+ * @param array Return from validate_session()
+ */
+
+ function show_inactive_error($userdata)
+ {
+ global $db, $session, $paths, $template, $plugins; // Common objects
+ global $lang;
+
+ global $title;
+ $paths->init($title);
+
+ $language = intval(getConfig('default_language'));
+ $lang = new Language($language);
+ @setlocale(LC_ALL, $lang->lang_code);
+
+ $a = getConfig('account_activation');
+ switch($a)
+ {
+ case 'none':
+ default:
+ $solution = $lang->get('user_login_noact_solution_none');
+ break;
+ case 'user':
+ $solution = $lang->get('user_login_noact_solution_user');
+ break;
+ case 'admin':
+ $solution = $lang->get('user_login_noact_solution_admin');
+ break;
+ }
+
+ // admin activation request opportunity
+ $q = $db->sql_query('SELECT 1 FROM '.table_prefix.'logs WHERE log_type=\'admin\' AND action=\'activ_req\' AND edit_summary=\'' . $db->escape($userdata['username']) . '\';');
+ if ( !$q )
+ $db->_die();
+
+ $can_request = ( $db->numrows() < 1 );
+ $db->free_result();
+
+ if ( isset($_POST['logout']) )
+ {
+ $this->sid = $_COOKIE['sid'];
+ $this->user_logged_in = true;
+ $this->user_id = intval($userdata['user_id']);
+ $this->username = $userdata['username'];
+ $this->auth_level = USER_LEVEL_MEMBER;
+ $this->user_level = USER_LEVEL_MEMBER;
+ $this->logout();
+ redirect(scriptPath . '/', $lang->get('user_login_noact_msg_logout_success_title'), $lang->get('user_login_noact_msg_logout_success_body'), 5);
+ }
+
+ if ( $can_request && !isset($_POST['activation_request']) )
+ {
+ $form = '