PageRenderTime 63ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/sessions.php

https://code.google.com/p/enanocms/
PHP | 4735 lines | 3152 code | 576 blank | 1007 comment | 654 complexity | 496688a8a19ea62f9a4bfaaaf0aec9fa MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
  4. * Copyright (C) 2006-2009 Dan Fuhry
  5. * sessions.php - everything related to security and user management
  6. *
  7. * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
  11. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
  12. */
  13. /**
  14. * Anything and everything related to security and user management. This includes AES encryption, which is illegal in some countries.
  15. * Documenting the API was not easy - I hope you folks enjoy it.
  16. * @package Enano
  17. * @subpackage Session manager
  18. * @category security, user management, logins, etc.
  19. */
  20. class sessionManager {
  21. # Variables
  22. /**
  23. * Whether we're logged in or not
  24. * @var bool
  25. */
  26. var $user_logged_in = false;
  27. /**
  28. * Our current low-privilege session key
  29. * @var string
  30. */
  31. var $sid;
  32. /**
  33. * Username of currently logged-in user, or IP address if not logged in
  34. * @var string
  35. */
  36. var $username;
  37. /**
  38. * User ID of currently logged-in user, or 1 if not logged in
  39. * @var int
  40. */
  41. var $user_id = 1;
  42. /**
  43. * Real name of currently logged-in user, or blank if not logged in
  44. * @var string
  45. */
  46. var $real_name;
  47. /**
  48. * E-mail address of currently logged-in user, or blank if not logged in
  49. * @var string
  50. */
  51. var $email;
  52. /**
  53. * List of "extra" user information fields (IM handles, etc.)
  54. * @var array (associative)
  55. */
  56. var $user_extra;
  57. /**
  58. * User level of current user
  59. * USER_LEVEL_GUEST: guest
  60. * USER_LEVEL_MEMBER: regular user
  61. * USER_LEVEL_CHPREF: default - pseudo-level that allows changing password and e-mail address (requires re-authentication)
  62. * USER_LEVEL_MOD: moderator
  63. * USER_LEVEL_ADMIN: administrator
  64. * @var int
  65. */
  66. var $user_level;
  67. /**
  68. * High-privilege session key
  69. * @var string or false if not running on high-level authentication
  70. */
  71. var $sid_super;
  72. /**
  73. * The user's theme preference, defaults to $template->default_theme
  74. * @var string
  75. */
  76. var $theme;
  77. /**
  78. * The user's style preference, or style auto-detected based on theme if not logged in
  79. * @var string
  80. */
  81. var $style;
  82. /**
  83. * Signature of current user - appended to comments, etc.
  84. * @var string
  85. */
  86. var $signature;
  87. /**
  88. * UNIX timestamp of when we were registered, or 0 if not logged in
  89. * @var int
  90. */
  91. var $reg_time;
  92. /**
  93. * The number of unread private messages this user has.
  94. * @var int
  95. */
  96. var $unread_pms = 0;
  97. /**
  98. * AES key used to encrypt passwords and session key info.
  99. * @var string
  100. * @access private
  101. */
  102. protected $private_key;
  103. /**
  104. * Regex that defines a valid username, minus the ^ and $, these are added later
  105. * @var string
  106. */
  107. var $valid_username = '([^<>&\?\'"%\n\r\t\a\/]+)';
  108. /**
  109. * The current user's user title. Defaults to NULL.
  110. * @var string
  111. */
  112. var $user_title = null;
  113. /**
  114. * What we're allowed to do as far as permissions go. This changes based on the value of the "auth" URI param.
  115. * @var string
  116. */
  117. var $auth_level = 1;
  118. /**
  119. * Preference for date formatting
  120. * @var string
  121. */
  122. var $date_format = DATE_4;
  123. /**
  124. * Preference for time formatting
  125. * @var string
  126. */
  127. var $time_format = TIME_24_NS;
  128. /**
  129. * State variable to track if a session timed out
  130. * @var bool
  131. */
  132. var $sw_timed_out = false;
  133. /**
  134. * Token appended to some important forms to prevent CSRF.
  135. * @var string
  136. */
  137. var $csrf_token = false;
  138. /**
  139. * Password change disabled, for auth plugins
  140. * @var bool
  141. */
  142. var $password_change_disabled = false;
  143. /**
  144. * Password change page URL + title, for auth plugins
  145. * @var array
  146. */
  147. var $password_change_dest = array('url' => '', 'title' => '');
  148. /**
  149. * Switch to track if we're started or not.
  150. * @access private
  151. * @var bool
  152. */
  153. var $started = false;
  154. /**
  155. * Switch to control compatibility mode (for older Enano websites being upgraded)
  156. * @access private
  157. * @var bool
  158. */
  159. var $compat = false;
  160. /**
  161. * Our list of permission types.
  162. * @access private
  163. * @var array
  164. */
  165. var $acl_types = Array();
  166. /**
  167. * The list of descriptions for the permission types
  168. * @var array
  169. */
  170. var $acl_descs = Array();
  171. /**
  172. * A list of dependencies for ACL types.
  173. * @var array
  174. */
  175. var $acl_deps = Array();
  176. /**
  177. * Our tell-all list of permissions. Do not even try to change this.
  178. * @access private
  179. * @var array
  180. */
  181. var $perms = Array();
  182. /**
  183. * A cache variable - saved after sitewide permissions are checked but before page-specific permissions.
  184. * @var array
  185. * @access private
  186. */
  187. var $acl_base_cache = Array();
  188. /**
  189. * Stores the scope information for ACL types.
  190. * @var array
  191. * @access private
  192. */
  193. var $acl_scope = Array();
  194. /**
  195. * Array to track which default permissions are being used
  196. * @var array
  197. * @access private
  198. */
  199. var $acl_defaults_used = Array();
  200. /**
  201. * Array to track group membership.
  202. * @var array
  203. */
  204. var $groups = Array();
  205. /**
  206. * Associative array to track group modship.
  207. * @var array
  208. */
  209. var $group_mod = Array();
  210. /**
  211. * A constant array of user-level-to-rank default associations.
  212. * @var array
  213. */
  214. var $level_rank_table = array(
  215. USER_LEVEL_ADMIN => RANK_ID_ADMIN,
  216. USER_LEVEL_MOD => RANK_ID_MOD,
  217. USER_LEVEL_MEMBER => RANK_ID_MEMBER,
  218. USER_LEVEL_CHPREF => RANK_ID_MEMBER,
  219. USER_LEVEL_GUEST => RANK_ID_GUEST
  220. );
  221. /**
  222. * A constant array that maps precedence constants to language strings
  223. * @var array
  224. */
  225. var $acl_inherit_lang_table = array(
  226. ACL_INHERIT_ENANO_DEFAULT => 'acl_inherit_enano_default',
  227. ACL_INHERIT_GLOBAL_EVERYONE => 'acl_inherit_global_everyone',
  228. ACL_INHERIT_GLOBAL_GROUP => 'acl_inherit_global_group',
  229. ACL_INHERIT_GLOBAL_USER => 'acl_inherit_global_user',
  230. ACL_INHERIT_PG_EVERYONE => 'acl_inherit_pg_everyone',
  231. ACL_INHERIT_PG_GROUP => 'acl_inherit_pg_group',
  232. ACL_INHERIT_PG_USER => 'acl_inherit_pg_user',
  233. ACL_INHERIT_LOCAL_EVERYONE => 'acl_inherit_local_everyone',
  234. ACL_INHERIT_LOCAL_GROUP => 'acl_inherit_local_group',
  235. ACL_INHERIT_LOCAL_USER => 'acl_inherit_local_user'
  236. );
  237. # Basic functions
  238. /**
  239. * Constructor.
  240. */
  241. function __construct()
  242. {
  243. global $db, $session, $paths, $template, $plugins; // Common objects
  244. if ( defined('IN_ENANO_INSTALL') && !defined('IN_ENANO_UPGRADE') )
  245. {
  246. @include(ENANO_ROOT.'/config.new.php');
  247. }
  248. else
  249. {
  250. @include(ENANO_ROOT.'/config.php');
  251. }
  252. unset($dbhost, $dbname, $dbuser, $dbpasswd);
  253. if(isset($crypto_key))
  254. {
  255. $this->private_key = $crypto_key;
  256. $this->private_key = hexdecode($this->private_key);
  257. }
  258. else
  259. {
  260. if(is_writable(ENANO_ROOT.'/config.php'))
  261. {
  262. // Generate and stash a private key
  263. // This should only happen during an automated silent gradual migration to the new encryption platform.
  264. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  265. $this->private_key = $aes->gen_readymade_key();
  266. $config = file_get_contents(ENANO_ROOT.'/config.php');
  267. if(!$config)
  268. {
  269. die('$session->__construct(): can\'t get the contents of config.php');
  270. }
  271. $config = str_replace("?>", "\$crypto_key = '{$this->private_key}';\n?>", $config);
  272. // And while we're at it...
  273. $config = str_replace('MIDGET_INSTALLED', 'ENANO_INSTALLED', $config);
  274. $fh = @fopen(ENANO_ROOT.'/config.php', 'w');
  275. if ( !$fh )
  276. {
  277. die('$session->__construct(): Couldn\'t open config file for writing to store the private key, I tried to avoid something like this...');
  278. }
  279. fwrite($fh, $config);
  280. fclose($fh);
  281. }
  282. else
  283. {
  284. die_semicritical('Crypto error', '<p>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.</p>');
  285. }
  286. }
  287. // Check for compatibility mode
  288. if(defined('IN_ENANO_INSTALL'))
  289. {
  290. $q = $db->sql_query('SELECT old_encryption FROM '.table_prefix.'users LIMIT 1;');
  291. if(!$q)
  292. {
  293. $error = mysql_error();
  294. if(strstr($error, "Unknown column 'old_encryption'"))
  295. $this->compat = true;
  296. else
  297. $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)');
  298. }
  299. $db->free_result();
  300. }
  301. }
  302. /**
  303. * PHP 4 compatible constructor. Deprecated in 1.1.x.
  304. */
  305. /*
  306. function sessionManager()
  307. {
  308. $this->__construct();
  309. }
  310. */
  311. /**
  312. * Wrapper function to sanitize strings for MySQL and HTML
  313. * @param string $text The text to sanitize
  314. * @return string
  315. */
  316. function prepare_text($text)
  317. {
  318. global $db;
  319. return $db->escape(htmlspecialchars($text));
  320. }
  321. /**
  322. * Makes a SQL query and handles error checking
  323. * @param string $query The SQL query to make
  324. * @return resource
  325. */
  326. function sql($query)
  327. {
  328. global $db, $session, $paths, $template, $plugins; // Common objects
  329. $result = $db->sql_query($query);
  330. if(!$result)
  331. {
  332. $db->_die('The error seems to have occurred somewhere in the session management code.');
  333. }
  334. return $result;
  335. }
  336. /**
  337. * Returns true if we're currently on a page that shouldn't be blocked even if we have an inactive or banned account
  338. * @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
  339. * @return bool
  340. */
  341. function on_critical_page($strict = false)
  342. {
  343. global $urlname;
  344. list($page_id, $namespace) = RenderMan::strToPageID($urlname);
  345. list($page_id) = explode('/', $page_id);
  346. if ( $strict )
  347. {
  348. return $namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'LangExportJSON', 'ActivateAccount'));
  349. }
  350. else
  351. {
  352. return $namespace == 'Admin' || ($namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'Administration', 'LangExportJSON', 'ActivateAccount')));
  353. }
  354. }
  355. # Session restoration and permissions
  356. /**
  357. * Initializes the basic state of things, including most user prefs, login data, cookie stuff
  358. */
  359. function start()
  360. {
  361. global $db, $session, $paths, $template, $plugins; // Common objects
  362. global $lang;
  363. global $timezone;
  364. if($this->started) return;
  365. $this->started = true;
  366. $user = false;
  367. if ( isset($_COOKIE['sid']) )
  368. {
  369. if ( $this->compat )
  370. {
  371. $userdata = $this->compat_validate_session($_COOKIE['sid']);
  372. }
  373. else
  374. {
  375. $userdata = $this->validate_session($_COOKIE['sid']);
  376. }
  377. if ( is_array($userdata) )
  378. {
  379. $this->sid = $_COOKIE['sid'];
  380. $this->user_logged_in = true;
  381. $this->user_id = intval($userdata['user_id']);
  382. $this->username = $userdata['username'];
  383. $this->user_level = intval($userdata['user_level']);
  384. $this->real_name = $userdata['real_name'];
  385. $this->email = $userdata['email'];
  386. $this->unread_pms = $userdata['num_pms'];
  387. $this->user_title = ( isset($userdata['user_title']) ) ? $userdata['user_title'] : null;
  388. if(!$this->compat)
  389. {
  390. $this->theme = $userdata['theme'];
  391. $this->style = $userdata['style'];
  392. $this->signature = $userdata['signature'];
  393. $this->reg_time = $userdata['reg_time'];
  394. }
  395. $this->auth_level = USER_LEVEL_MEMBER;
  396. // generate an anti-CSRF token
  397. $this->csrf_token = sha1($this->username . $this->sid . $this->user_id);
  398. if(!isset($template->named_theme_list[$this->theme]))
  399. {
  400. if($this->compat || !is_object($template))
  401. {
  402. $this->theme = 'oxygen';
  403. $this->style = 'bleu';
  404. }
  405. else
  406. {
  407. $this->theme = $template->default_theme;
  408. $this->style = $template->default_style;
  409. }
  410. }
  411. $user = true;
  412. // set timezone params
  413. $GLOBALS['timezone'] = $userdata['user_timezone'];
  414. $GLOBALS['dst_params'] = explode(';', $userdata['user_dst']);
  415. foreach ( $GLOBALS['dst_params'] as &$parm )
  416. {
  417. if ( substr($parm, -1) != 'd' )
  418. $parm = intval($parm);
  419. }
  420. // Set language
  421. if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
  422. {
  423. $lang_id = intval($userdata['user_lang']);
  424. $lang = new Language($lang_id);
  425. @setlocale(LC_ALL, $lang->lang_code);
  426. }
  427. if(isset($_REQUEST['auth']) && !$this->sid_super)
  428. {
  429. // Now he thinks he's a moderator. Or maybe even an administrator. Let's find out if he's telling the truth.
  430. if($this->compat)
  431. {
  432. $key = $_REQUEST['auth'];
  433. $super = $this->compat_validate_session($key);
  434. }
  435. else
  436. {
  437. $key = $_REQUEST['auth'];
  438. if ( !empty($key) && ( strlen($key) / 2 ) % 4 == 0 )
  439. {
  440. $super = $this->validate_session($key);
  441. }
  442. }
  443. if(is_array(@$super))
  444. {
  445. $this->auth_level = intval($super['auth_level']);
  446. $this->sid_super = $_REQUEST['auth'];
  447. }
  448. }
  449. }
  450. }
  451. if(!$user)
  452. {
  453. //exit;
  454. $this->register_guest_session();
  455. }
  456. if(!$this->compat)
  457. {
  458. // init groups
  459. $q = $this->sql('SELECT g.group_name,g.group_id,m.is_mod FROM '.table_prefix.'groups AS g' . "\n"
  460. . ' LEFT JOIN '.table_prefix.'group_members AS m' . "\n"
  461. . ' ON g.group_id=m.group_id' . "\n"
  462. . ' WHERE ( m.user_id='.$this->user_id.'' . "\n"
  463. . ' OR g.group_name=\'Everyone\')' . "\n"
  464. . ' ' . ( /* quick hack for upgrade compatibility reasons */ enano_version() == '1.0RC1' ? '' : 'AND ( m.pending != 1 OR m.pending IS NULL )' ) . '' . "\n"
  465. . ' ORDER BY group_id ASC;'); // The ORDER BY is to make sure "Everyone" comes first so the permissions can be overridden
  466. if($row = $db->fetchrow())
  467. {
  468. do {
  469. $this->groups[$row['group_id']] = $row['group_name'];
  470. $this->group_mod[$row['group_id']] = ( intval($row['is_mod']) == 1 );
  471. } while($row = $db->fetchrow());
  472. }
  473. else
  474. {
  475. die('No group info');
  476. }
  477. profiler_log('Fetched group memberships');
  478. }
  479. // make sure we aren't banned
  480. $this->check_banlist();
  481. // make sure the account is active
  482. if ( !$this->compat && $this->user_logged_in && $userdata['account_active'] < 1 && !$this->on_critical_page() )
  483. {
  484. $this->show_inactive_error($userdata);
  485. }
  486. // Printable page view? Probably the wrong place to control
  487. // it but $template is pretty dumb, it will just about always
  488. // do what you ask it to do, which isn't always what we want
  489. if ( isset ( $_GET['printable'] ) )
  490. {
  491. $this->theme = 'printable';
  492. $this->style = 'default';
  493. }
  494. // setup theme ACLs
  495. $template->process_theme_acls();
  496. profiler_log('Sessions started. Banlist and theme ACLs initialized');
  497. }
  498. # Logins
  499. /**
  500. * Attempts to perform a login using crypto functions
  501. * @param string $username The username
  502. * @param string $aes_data The encrypted password, hex-encoded
  503. * @param string $aes_key The MD5 hash of the encryption key, hex-encoded
  504. * @param string $challenge The 256-bit MD5 challenge string - first 128 bits should be the hash, the last 128 should be the challenge salt
  505. * @param int $level The privilege level we're authenticating for, defaults to 0
  506. * @param string $captcha_hash Optional. If we're locked out and the lockout policy is captcha, this should be the identifier for the code.
  507. * @param string $captcha_code Optional. If we're locked out and the lockout policy is captcha, this should be the code the user entered.
  508. * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
  509. * @param bool $lookup_key Optional. If true (default) this queries the database for the "real" encryption key. Else, uses what is given.
  510. * @return string 'success' on success, or error string on failure
  511. */
  512. 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)
  513. {
  514. global $db, $session, $paths, $template, $plugins; // Common objects
  515. // Instanciate the Rijndael encryption object
  516. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  517. // Fetch our decryption key
  518. if ( $lookup_key )
  519. {
  520. $aes_key = $this->fetch_public_key($aes_key_id);
  521. if ( !$aes_key )
  522. {
  523. // It could be that our key cache is full. If it seems larger than 65KB, clear it
  524. if ( strlen(getConfig('login_key_cache')) > 65000 )
  525. {
  526. setConfig('login_key_cache', '');
  527. return array(
  528. 'success' => false,
  529. 'error' => 'key_not_found_cleared',
  530. );
  531. }
  532. return array(
  533. 'success' => false,
  534. 'error' => 'key_not_found'
  535. );
  536. }
  537. }
  538. else
  539. {
  540. $aes_key =& $aes_key_id;
  541. }
  542. // Convert the key to a binary string
  543. $bin_key = hexdecode($aes_key);
  544. if(strlen($bin_key) != AES_BITS / 8)
  545. return array(
  546. 'success' => false,
  547. 'error' => 'key_wrong_length'
  548. );
  549. // Decrypt our password
  550. $password = $aes->decrypt($aes_data, $bin_key, ENC_HEX);
  551. // Let the LoginAPI do the rest.
  552. return $this->login_without_crypto($username, $password, false, $level, $captcha_hash, $captcha_code, $remember);
  553. }
  554. /**
  555. * Attempts to login without using crypto stuff, mainly for use when the other side doesn't like Javascript
  556. * 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
  557. * Technically it still uses crypto, but it only decrypts the password already stored, which is (obviously) required for authentication
  558. * @param string $username The username
  559. * @param string $password The password -OR- the MD5 hash of the password if $already_md5ed is true
  560. * @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.
  561. * @param int $level The privilege level we're authenticating for, defaults to 0
  562. * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
  563. */
  564. function login_without_crypto($username, $password, $already_md5ed = false, $level = USER_LEVEL_MEMBER, $remember = false)
  565. {
  566. global $db, $session, $paths, $template, $plugins; // Common objects
  567. if ( $already_md5ed )
  568. {
  569. // No longer supported
  570. return array(
  571. 'mode' => 'error',
  572. '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)'
  573. );
  574. }
  575. // Replace underscores with spaces in username
  576. // (Added in 1.0.2)
  577. $username = str_replace('_', ' ', $username);
  578. // Perhaps we're upgrading Enano?
  579. if($this->compat)
  580. {
  581. return $this->login_compat($username, md5($password), $level);
  582. }
  583. // Instanciate the Rijndael encryption object
  584. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  585. // Initialize our success switch
  586. $success = false;
  587. // Retrieve the real password from the database
  588. $username_db = $db->escape(strtolower($username));
  589. $username_db_upper = $db->escape($username);
  590. if ( !$db->sql_query('SELECT password,password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
  591. . " WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );") )
  592. {
  593. $this->sql('SELECT password,\'\' AS password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
  594. . " WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );");
  595. }
  596. if ( $db->numrows() < 1 )
  597. {
  598. // This wasn't logged in <1.0.2, dunno how it slipped through
  599. if ( $level > USER_LEVEL_MEMBER )
  600. $this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES\n"
  601. . ' (\'security\', \'admin_auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
  602. . '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
  603. else
  604. $this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary) VALUES\n"
  605. . ' (\'security\', \'auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
  606. . '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
  607. // Do we also need to increment the lockout countdown?
  608. if ( !defined('IN_ENANO_INSTALL') )
  609. $lockout_data = $this->get_lockout_info();
  610. else
  611. $lockout_data = array(
  612. 'lockout_policy' => 'disable'
  613. );
  614. if ( $lockout_data['policy'] != 'disable' && !defined('IN_ENANO_INSTALL') )
  615. {
  616. $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
  617. // increment fail count
  618. $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
  619. $lockout_data['fails']++;
  620. return array(
  621. 'success' => false,
  622. 'error' => ( $lockout_data['fails'] >= $lockout_data['threshold'] ) ? 'locked_out' : 'invalid_credentials',
  623. 'lockout_threshold' => $lockout_data['threshold'],
  624. 'lockout_duration' => ( $lockout_data['duration'] ),
  625. 'lockout_fails' => $lockout_data['fails'],
  626. 'lockout_policy' => $lockout_data['policy']
  627. );
  628. }
  629. return array(
  630. 'success' => false,
  631. 'error' => 'invalid_credentials'
  632. );
  633. }
  634. $row = $db->fetchrow();
  635. // Check to see if we're logging in using a temporary password
  636. if((intval($row['temp_password_time']) + 3600*24) > time() )
  637. {
  638. $temp_pass = hmac_sha1($password, $row['password_salt']);
  639. if( $temp_pass === $row['temp_password'] )
  640. {
  641. $code = $plugins->setHook('login_password_reset');
  642. foreach ( $code as $cmd )
  643. {
  644. eval($cmd);
  645. }
  646. return array(
  647. 'success' => false,
  648. 'error' => 'valid_reset',
  649. 'redirect_url' => makeUrlComplete('Special', 'PasswordReset/stage2/' . $row['user_id'] . '/' . $this->pk_encrypt($password))
  650. );
  651. }
  652. }
  653. if ( $row['old_encryption'] == 1 )
  654. {
  655. // The user's password is stored using the obsolete and insecure MD5 algorithm - we'll update the field with the new password
  656. if(md5($password) === $row['password'])
  657. {
  658. if ( !defined('IN_ENANO_UPGRADE') )
  659. {
  660. $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
  661. $password_hmac = hmac_sha1($password, $hmac_secret);
  662. $this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
  663. }
  664. $success = true;
  665. }
  666. }
  667. else if ( $row['old_encryption'] == 2 || ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') ) && strlen($row['password']) != 40 )
  668. {
  669. // Our password field uses the 1.0RC1-1.1.5 encryption format
  670. $real_pass = $aes->decrypt($row['password'], $this->private_key);
  671. if($password === $real_pass)
  672. {
  673. if ( !defined('IN_ENANO_UPGRADE') )
  674. {
  675. $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
  676. $password_hmac = hmac_sha1($password, $hmac_secret);
  677. $this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
  678. }
  679. $success = true;
  680. }
  681. }
  682. else
  683. {
  684. // Password uses HMAC-SHA1
  685. $user_challenge = hmac_sha1($password, $row['password_salt']);
  686. $password_hmac =& $row['password'];
  687. if ( $user_challenge === $password_hmac )
  688. {
  689. $success = true;
  690. }
  691. }
  692. if($success)
  693. {
  694. if((int)$level > (int)$row['user_level'])
  695. return array(
  696. 'success' => false,
  697. 'error' => 'too_big_for_britches'
  698. );
  699. // grant session
  700. $sess = $this->register_session($row['user_id'], $username, ( isset($password_hmac) ? $password_hmac : $password ), $level, $remember);
  701. if($sess)
  702. {
  703. if ( getConfig('db_version') >= 1125 )
  704. {
  705. if($level > USER_LEVEL_MEMBER)
  706. $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) . ')');
  707. else
  708. $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']).'\')');
  709. }
  710. else
  711. {
  712. if($level > USER_LEVEL_MEMBER)
  713. $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
  714. else
  715. $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
  716. }
  717. $code = $plugins->setHook('login_success');
  718. foreach ( $code as $cmd )
  719. {
  720. eval($cmd);
  721. }
  722. return array(
  723. 'success' => true
  724. );
  725. }
  726. else
  727. return array(
  728. 'success' => false,
  729. 'error' => 'backend_fail'
  730. );
  731. }
  732. else
  733. {
  734. if($level > USER_LEVEL_MEMBER)
  735. $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) . ')');
  736. else
  737. $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']).'\')');
  738. // Do we also need to increment the lockout countdown?
  739. if ( !defined('IN_ENANO_INSTALL') && getConfig('lockout_policy', 'lockout') !== 'disable' )
  740. {
  741. $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
  742. // increment fail count
  743. $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
  744. }
  745. return array(
  746. 'success' => false,
  747. 'error' => 'invalid_credentials'
  748. );
  749. }
  750. }
  751. /**
  752. * Attempts to log in using the old table structure and algorithm. This is for upgrades from old 1.0.x releases.
  753. * @param string $username
  754. * @param string $password This should be an MD5 hash
  755. * @return string 'success' if successful, or error message on failure
  756. */
  757. function login_compat($username, $password, $level = 0)
  758. {
  759. global $db, $session, $paths, $template, $plugins; // Common objects
  760. $pass_hashed =& $password;
  761. $this->sql('SELECT password,user_id,user_level FROM '.table_prefix.'users WHERE username=\''.$this->prepare_text($username).'\';');
  762. if($db->numrows() < 1)
  763. return 'The username and/or password is incorrect.';
  764. $row = $db->fetchrow();
  765. if($row['password'] == $password)
  766. {
  767. if((int)$level > (int)$row['user_level'])
  768. return 'You are not authorized for this level of access.';
  769. $sess = $this->register_session_compat(intval($row['user_id']), $username, $password, $level);
  770. if($sess)
  771. return 'success';
  772. else
  773. return 'Your login credentials were correct, but an internal error occured while registering the session key in the database.';
  774. }
  775. else
  776. {
  777. return 'The username and/or password is incorrect.';
  778. }
  779. }
  780. /**
  781. * Registers a session key in the database. This function *ASSUMES* that the username and password have already been validated!
  782. * 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]"
  783. * @param int $user_id
  784. * @param string $username
  785. * @param string $password_hmac The HMAC of the user's password, right from the database
  786. * @param int $level The level of access to grant, defaults to USER_LEVEL_MEMBER
  787. * @param bool $remember Whether the session should be long-term (true) or not (false). Defaults to short-term.
  788. * @return bool
  789. */
  790. function register_session($user_id, $username, $password_hmac, $level = USER_LEVEL_MEMBER, $remember = false)
  791. {
  792. global $db, $session, $paths, $template, $plugins; // Common objects
  793. // Random key identifier
  794. $salt = '';
  795. for ( $i = 0; $i < 32; $i++ )
  796. {
  797. $salt .= chr(mt_rand(32, 126));
  798. }
  799. // Session key
  800. if ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') )
  801. {
  802. $session_key = $this->pk_encrypt("u=$username;p=" . sha1($password_hmac) . ";s=$salt");
  803. }
  804. else
  805. {
  806. $key_pieces = array($password_hmac);
  807. $sk_mode = 'generate';
  808. $code = $plugins->setHook('session_key_calc');
  809. foreach ( $code as $cmd )
  810. {
  811. eval($cmd);
  812. }
  813. $key_pieces = implode("\xFF", $key_pieces);
  814. $session_key = hmac_sha1($key_pieces, $salt);
  815. }
  816. // Minimum level
  817. $level = max(array($level, USER_LEVEL_MEMBER));
  818. // Type of key
  819. $key_type = ( $level > USER_LEVEL_MEMBER ) ? SK_ELEV : ( $remember ? SK_LONG : SK_SHORT );
  820. // If we're registering an elevated-privilege key, it needs to be on GET
  821. if($level > USER_LEVEL_MEMBER)
  822. {
  823. $this->sid_super = $session_key;
  824. $_GET['auth'] = $session_key;
  825. }
  826. else
  827. {
  828. // Stash it in a cookie
  829. // For now, make the cookie last forever, we can change this in 1.1.x
  830. setcookie( 'sid', $session_key, time()+15552000, scriptPath.'/', null, $GLOBALS['is_https']);
  831. $_COOKIE['sid'] = $session_key;
  832. $this->sid = $session_key;
  833. }
  834. // $keyhash is stored in the database, this is for compatibility with the older DB structure
  835. $keyhash = md5($session_key);
  836. // Record the user's IP
  837. $ip = $_SERVER['REMOTE_ADDR'];
  838. if(!is_valid_ip($ip))
  839. die('$session->register_session: Remote-Addr was spoofed');
  840. // The time needs to be stashed to enforce the 15-minute limit on elevated session keys
  841. $time = time();
  842. // Sanity check
  843. if(!is_int($user_id))
  844. die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
  845. if(!is_int($level))
  846. die(var_dump($level) . '<br />Somehow an SQL injection attempt crawled into our session registrar! (2)');
  847. // Update RAM
  848. $this->user_id = $user_id;
  849. $this->user_level = max(array($this->user_level, $level));
  850. // All done!
  851. $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 . ');');
  852. if ( !$query && defined('IN_ENANO_UPGRADE') )
  853. // we're trying to upgrade so the key_type column is probably missing - try it again without specifying the key type
  854. $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.');');
  855. return true;
  856. }
  857. /**
  858. * 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.
  859. * @see sessionManager::register_session()
  860. * @access private
  861. */
  862. function register_session_compat($user_id, $username, $password, $level = 0)
  863. {
  864. $salt = md5(microtime() . mt_rand());
  865. $thekey = md5($password . $salt);
  866. if($level > 0)
  867. {
  868. $this->sid_super = $thekey;
  869. }
  870. else
  871. {
  872. setcookie( 'sid', $thekey, time()+315360000, scriptPath.'/' );
  873. $_COOKIE['sid'] = $thekey;
  874. }
  875. $ip = ip2hex($_SERVER['REMOTE_ADDR']);
  876. if(!$ip)
  877. die('$session->register_session: Remote-Addr was spoofed');
  878. $time = time();
  879. if(!is_int($user_id))
  880. die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
  881. if(!is_int($level))
  882. die('Somehow an SQL injection attempt crawled into our session registrar! (2)');
  883. $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.');');
  884. return true;
  885. }
  886. /**
  887. * Tells us if we're locked out from logging in or not.
  888. * @param reference will be filled with information regarding in-progress lockout
  889. * @return bool True if locked out, false otherwise
  890. */
  891. function get_lockout_info()
  892. {
  893. global $db;
  894. // this has to be initialized to hide warnings
  895. $lockdata = null;
  896. // Query database for lockout info
  897. $locked_out = false;
  898. $threshold = ( $_ = getConfig('lockout_threshold') ) ? intval($_) : 5;
  899. $duration = ( $_ = getConfig('lockout_duration') ) ? intval($_) : 15;
  900. // convert to seconds
  901. $duration = $duration * 60;
  902. // decide on policy
  903. $policy = ( $x = getConfig('lockout_policy') && in_array(getConfig('lockout_policy'), array('lockout', 'disable', 'captcha')) ) ? getConfig('lockout_policy') : 'lockout';
  904. if ( $policy != 'disable' )
  905. {
  906. // enabled; make decision
  907. $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
  908. $timestamp_cutoff = time() - $duration;
  909. $q = $this->sql('SELECT timestamp FROM ' . table_prefix . 'lockout WHERE timestamp > ' . $timestamp_cutoff . ' AND ipaddr = \'' . $ipaddr . '\' ORDER BY timestamp DESC;');
  910. $fails = $db->numrows($q);
  911. $row = $db->fetchrow($q);
  912. $locked_out = ( $fails >= $threshold );
  913. $lockdata = array(
  914. 'active' => $locked_out,
  915. 'threshold' => $threshold,
  916. 'duration' => ( $duration / 60 ),
  917. 'fails' => $fails,
  918. 'policy' => $policy,
  919. 'last_time' => $row['timestamp'],
  920. 'time_rem' => $locked_out ? ( $duration / 60 ) - round( ( time() - $row['timestamp'] ) / 60 ) : 0,
  921. 'captcha' => $policy == 'captcha' ? $this->make_captcha() : ''
  922. );
  923. $db->free_result();
  924. }
  925. else
  926. {
  927. // disabled; send back default dataset
  928. $lockdata = array(
  929. 'active' => false,
  930. 'threshold' => $threshold,
  931. 'duration' => ( $duration / 60 ),
  932. 'fails' => 0,
  933. 'policy' => $policy,
  934. 'last_time' => 0,
  935. 'time_rem' => 0,
  936. 'captcha' => ''
  937. );
  938. }
  939. return $lockdata;
  940. }
  941. /**
  942. * Creates/restores a guest session
  943. * @todo implement real session management for guests
  944. */
  945. function register_guest_session()
  946. {
  947. global $db, $session, $paths, $template, $plugins; // Common objects
  948. global $lang;
  949. $this->username = $_SERVER['REMOTE_ADDR'];
  950. $this->user_level = USER_LEVEL_GUEST;
  951. if($this->compat || defined('IN_ENANO_INSTALL'))
  952. {
  953. $this->theme = 'oxygen';
  954. $this->style = 'bleu';
  955. }
  956. else
  957. {
  958. $this->theme = ( isset($_GET['theme']) && isset($template->named_theme_list[$_GET['theme']])) ? $_GET['theme'] : $template->default_theme;
  959. $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']);
  960. }
  961. $this->user_id = 1;
  962. // This is a VERY special case we are allowing. It lets the installer create languages using the Enano API.
  963. if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
  964. {
  965. $language = ( isset($_GET['lang']) && preg_match('/^[a-z0-9-_]+$/', @$_GET['lang']) ) ? $_GET['lang'] : intval(getConfig('default_language'));
  966. $lang = new Language($language);
  967. @setlocale(LC_ALL, $lang->lang_code);
  968. }
  969. // make a CSRF token
  970. $this->csrf_token = hmac_sha1($_SERVER['REMOTE_ADDR'], sha1($this->private_key));
  971. }
  972. /**
  973. * Validates a session key, and returns the userdata associated with the key or false
  974. * @param string $key The session key to validate
  975. * @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.
  976. */
  977. function validate_session($key)
  978. {
  979. global $db, $session, $paths, $template, $plugins; // Common objects
  980. profiler_log("SessionManager: checking session: " . sha1($key));
  981. if ( strlen($key) > 48 )
  982. {
  983. return $this->validate_aes_session($key);
  984. }
  985. profiler_log("SessionManager: checking session: " . $key);
  986. return $this->validate_session_shared($key, '');
  987. }
  988. /**
  989. * Validates an old-format AES session key. DO NOT USE THIS. Will return false if called outside of an upgrade.
  990. * @param string Session key
  991. * @return array
  992. */
  993. protected function validate_aes_session($key)
  994. {
  995. global $db, $session, $paths, $template, $plugins; // Common objects
  996. // No valid use except during upgrades
  997. if ( !preg_match('/^upg-/', enano_version()) && !defined('IN_ENANO_UPGRADE') )
  998. return false;
  999. $decrypted_key = $this->pk_decrypt($key);
  1000. if ( !$decrypted_key )
  1001. {
  1002. // die_semicritical('AES encryption error', '<p>Something went wrong during the AES decryption process.</p><pre>'.print_r($decrypted_key, true).'</pre>');
  1003. return false;
  1004. }
  1005. $n = preg_match('/^u='.$this->valid_username.';p=([A-Fa-f0-9]+?);s=(.{32})$/', $decrypted_key, $keydata);
  1006. if($n < 1)
  1007. {
  1008. echo '(debug) $session->validate_session: Key does not match regex<br />Decrypted key: '.$decrypted_key;
  1009. return false;
  1010. }
  1011. $keyhash = md5($key);
  1012. $salt = $db->escape($keydata[3]);
  1013. return $this->validate_session_shared($keyhash, $salt, true);
  1014. }
  1015. /**
  1016. * Shared portion of session validation. Do not try to call this.
  1017. * @return array
  1018. * @access private
  1019. */
  1020. protected function validate_session_shared($key, $salt, $loose_call = false)
  1021. {
  1022. global $db, $session, $paths, $template, $plugins; // Common objects
  1023. // using a normal call to $db->sql_query to avoid failing on errors here
  1024. $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"
  1025. . " 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"
  1026. . " k.time, k.auth_level, k.key_type, COUNT(p.message_id) AS num_pms, u.user_timezone, u.user_dst, x.*";
  1027. $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"
  1028. . " u.reg_time, u.account_active, u.activation_key, u.user_lang, u.user_timezone, u.user_title, u.user_dst,\n"
  1029. . " 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"
  1030. . " x.user_xmpp, x.user_homepage, x.user_location, x.user_job, x.user_hobbies, x.email_public,\n"
  1031. . " x.disable_js_fx, x.date_format, x.time_format";
  1032. $joins = " LEFT JOIN " . table_prefix . "users AS u\n"
  1033. . " ON ( u.user_id=k.user_id )\n"
  1034. . " LEFT JOIN " . table_prefix . "users_extra AS x\n"
  1035. . " ON ( u.user_id=x.user_id OR x.user_id IS NULL )\n"
  1036. . " LEFT JOIN " . table_prefix . "privmsgs AS p\n"
  1037. . " ON ( p.message_to=u.username AND p.message_read=0 )\n";
  1038. if ( !$loose_call )
  1039. {
  1040. $key_md5 = md5($key);
  1041. $query = $db->sql_query("SELECT $columns_select\n"
  1042. . "FROM " . table_prefix . "session_keys AS k\n"
  1043. . $joins
  1044. . " WHERE k.session_key='$key_md5'\n"
  1045. . " GROUP BY $columns_groupby;");
  1046. }
  1047. else
  1048. {
  1049. $query = $db->sql_query("SELECT $columns_select\n"
  1050. . "FROM " . table_prefix . "session_keys AS k\n"
  1051. . $joins
  1052. . " WHERE k.session_key='$key'\n"
  1053. . " AND k.salt='$salt'\n"
  1054. . " GROUP BY $columns_groupby;");
  1055. }
  1056. if ( !$query && ( defined('IN_ENANO_INSTALL') or defined('IN_ENANO_UPGRADE') ) )
  1057. {
  1058. $key_md5 = $loose_call ? $key : md5($key);
  1059. $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
  1060. LEFT JOIN '.table_prefix.'users AS u
  1061. ON ( u.user_id=k.user_id )
  1062. LEFT JOIN '.table_prefix.'privmsgs AS p
  1063. ON ( p.message_to=u.username AND p.message_read=0 )
  1064. WHERE k.session_key=\''.$key_md5.'\'
  1065. 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;');
  1066. }
  1067. else if ( !$query )
  1068. {
  1069. $db->_die();
  1070. }
  1071. if($db->numrows() < 1)
  1072. {
  1073. // echo '(debug) $session->validate_session: Key was not found in database: ' . $key_md5 . '<br />';
  1074. return false;
  1075. }
  1076. $row = $db->fetchrow();
  1077. profiler_log("SessionManager: session check: selected and fetched results");
  1078. $row['user_id'] =& $row['uid'];
  1079. $ip = $_SERVER['REMOTE_ADDR'];
  1080. if($row['auth_level'] > $row['user_level'])
  1081. {
  1082. // Failed authorization check
  1083. // echo '(debug) $session->validate_session: access to this auth level denied<br />';
  1084. return false;
  1085. }
  1086. if($ip != $row['source_ip'])
  1087. {
  1088. // Special exception for 1.1.x upgrade - the 1.1.3 upgrade changes the size of the column and this is what validate_session
  1089. // expects, but if the column size hasn't changed yet just check the first 10 digits of the IP.
  1090. $fail = true;
  1091. if ( defined('IN_ENANO_UPGRADE') )
  1092. {
  1093. if ( substr($ip, 0, 10) == substr($row['source_ip'], 0, 10) )
  1094. $fail = false;
  1095. }
  1096. // Failed IP address check
  1097. // echo '(debug) $session->validate_session: IP address mismatch<br />';
  1098. if ( $fail )
  1099. return false;
  1100. }
  1101. // $loose_call is turned on only from validate_aes_session
  1102. if ( !$loose_call )
  1103. {
  1104. $key_pieces = array($row['password']);
  1105. $user_id =& $row['uid'];
  1106. $sk_mode = 'validate';
  1107. $code = $plugins->setHook('session_key_calc');
  1108. foreach ( $code as $cmd )
  1109. {
  1110. eval($cmd);
  1111. }
  1112. $key_pieces = implode("\xFF", $key_pieces);
  1113. $correct_key = hexdecode(hmac_sha1($key_pieces, $row['salt']));
  1114. $user_key = hexdecode($key);
  1115. if ( $correct_key !== $user_key || !is_string($user_key) )
  1116. {
  1117. return false;
  1118. }
  1119. }
  1120. else
  1121. {
  1122. // if this is a "loose call", this only works once (during the final upgrade stage). Destroy the contents of session_keys.
  1123. if ( $row['auth_level'] == USER_LEVEL_ADMIN && preg_match('/^upg-/', enano_version()) )
  1124. $this->sql('DELETE FROM ' . table_prefix . "session_keys;");
  1125. }
  1126. // timestamp check
  1127. switch ( $row['key_type'] )
  1128. {
  1129. case SK_SHORT:
  1130. $time_now = time();
  1131. $time_key = $row['time'] + ( 60 * intval(getConfig('session_short', '720')) );
  1132. if ( $time_now > $time_key )
  1133. {
  1134. // Session timed out
  1135. return false;
  1136. }
  1137. break;
  1138. case SK_LONG:
  1139. if ( intval(getConfig('session_remember_time', '0')) === 0 )
  1140. {
  1141. // sessions last infinitely, timestamp validation is therefore successful
  1142. break;
  1143. }
  1144. $time_now = time();
  1145. $time_key = $row['time'] + ( 86400 * intval(getConfig('session_remember_time', '30')) );
  1146. if ( $time_now > $time_key )
  1147. {
  1148. // Session timed out
  1149. return false;
  1150. }
  1151. break;
  1152. case SK_ELEV:
  1153. $time_now = time();
  1154. $time_key = $row['time'] + 900;
  1155. if($time_now > $time_key && $row['auth_level'] > USER_LEVEL_MEMBER)
  1156. {
  1157. // Session timed out
  1158. // echo '(debug) $session->validate_session: super session timed out<br />';
  1159. $this->sw_timed_out = true;
  1160. return false;
  1161. }
  1162. break;
  1163. }
  1164. // If this is an elevated-access or short-term session key, update the time
  1165. if( $row['key_type'] == SK_ELEV || $row['key_type'] == SK_SHORT )
  1166. {
  1167. $this->sql('UPDATE '.table_prefix.'session_keys SET time='.time().' WHERE session_key=\''.md5($key).'\';');
  1168. }
  1169. $user_extra = array();
  1170. 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 )
  1171. {
  1172. if ( isset($row[$column]) )
  1173. $user_extra[$column] = $row[$column];
  1174. else
  1175. $user_extra[$column] = '';
  1176. }
  1177. if ( isset($row['date_format']) )
  1178. $this->date_format = $row['date_format'];
  1179. if ( isset($row['time_format']) )
  1180. $this->time_format = $row['time_format'];
  1181. $this->user_extra = $user_extra;
  1182. // Leave the rest to PHP's automatic garbage collector ;-)
  1183. $row['password'] = '';
  1184. $row['user_timezone'] = intval($row['user_timezone']) - 1440;
  1185. profiler_log("SessionManager: finished session check");
  1186. return $row;
  1187. }
  1188. /**
  1189. * Validates a session key, and returns the userdata associated with the key or false. Optimized for compatibility with the old MD5-based auth system.
  1190. * @param string $key The session key to validate
  1191. * @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.
  1192. */
  1193. function compat_validate_session($key)
  1194. {
  1195. global $db, $session, $paths, $template, $plugins; // Common objects
  1196. $key = $db->escape($key);
  1197. $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
  1198. LEFT JOIN '.table_prefix.'users AS u
  1199. ON u.user_id=k.user_id
  1200. WHERE k.session_key=\''.$key.'\';');
  1201. if($db->numrows() < 1)
  1202. {
  1203. // echo '(debug) $session->validate_session: Key '.$key.' was not found in database<br />';
  1204. return false;
  1205. }
  1206. $row = $db->fetchrow();
  1207. $ip = ip2hex($_SERVER['REMOTE_ADDR']);
  1208. if($row['auth_level'] > $row['user_level'])
  1209. {
  1210. // Failed authorization check
  1211. // echo '(debug) $session->validate_session: user not authorized for this access level';
  1212. return false;
  1213. }
  1214. if($ip != $row['source_ip'])
  1215. {
  1216. // Failed IP address check
  1217. // echo '(debug) $session->validate_session: IP address mismatch; IP in table: '.$row['source_ip'].'; reported IP: '.$ip.'';
  1218. return false;
  1219. }
  1220. // Do the password validation
  1221. $real_key = md5($row['password'] . $row['salt']);
  1222. //die('<pre>'.print_r($keydata, true).'</pre>');
  1223. if($real_key != $key)
  1224. {
  1225. // Failed password check
  1226. // echo '(debug) $session->validate_session: supplied password is wrong<br />Real key: '.$real_key.'<br />User key: '.$key;
  1227. return false;
  1228. }
  1229. $time_now = time();
  1230. $time_key = $row['time'] + 900;
  1231. if($time_now > $time_key && $row['auth_level'] >= 1)
  1232. {
  1233. $this->sw_timed_out = true;
  1234. // Session timed out
  1235. // echo '(debug) $session->validate_session: super session timed out<br />';
  1236. return false;
  1237. }
  1238. $row['user_timezone'] = intval($row['user_timezone']) - 1440;
  1239. return $row;
  1240. }
  1241. /**
  1242. * Demotes us to one less than the specified auth level. AKA destroys elevated authentication and/or logs out the user, depending on $level
  1243. * @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
  1244. * @return string 'success' if successful, or error on failure
  1245. */
  1246. function logout($level = USER_LEVEL_MEMBER)
  1247. {
  1248. global $db, $session, $paths, $template, $plugins; // Common objects
  1249. $ou = $this->username;
  1250. $oid = $this->user_id;
  1251. if($level > USER_LEVEL_MEMBER)
  1252. {
  1253. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  1254. if(!$this->user_logged_in || $this->auth_level < ( USER_LEVEL_MEMBER + 1))
  1255. {
  1256. return 'success';
  1257. }
  1258. // Destroy elevated privileges
  1259. $keyhash = md5($this->sid_super);
  1260. $this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.$keyhash.'\' AND user_id=\'' . $this->user_id . '\';');
  1261. $this->sid_super = false;
  1262. $this->auth_level = USER_LEVEL_MEMBER;
  1263. }
  1264. else
  1265. {
  1266. if($this->user_logged_in)
  1267. {
  1268. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  1269. // Completely destroy our session
  1270. if($this->auth_level > USER_LEVEL_MEMBER)
  1271. {
  1272. $this->logout(USER_LEVEL_ADMIN);
  1273. }
  1274. $this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.md5($this->sid).'\';');
  1275. setcookie( 'sid', '', time()-(3600*24), scriptPath.'/' );
  1276. }
  1277. }
  1278. $code = $plugins->setHook('logout_success'); // , Array('level'=>$level,'old_username'=>$ou,'old_user_id'=>$oid));
  1279. foreach ( $code as $cmd )
  1280. {
  1281. eval($cmd);
  1282. }
  1283. return 'success';
  1284. }
  1285. # Miscellaneous stuff
  1286. /**
  1287. * Alerts the user that their account is inactive, and tells them appropriate steps to remedy the situation. Halts execution.
  1288. * @param array Return from validate_session()
  1289. */
  1290. function show_inactive_error($userdata)
  1291. {
  1292. global $db, $session, $paths, $template, $plugins; // Common objects
  1293. global $lang;
  1294. global $title;
  1295. $paths->init($title);
  1296. $language = intval(getConfig('def…

Large files files are truncated, but you can click here to view the full file