PageRenderTime 54ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/php/Sources/LogInOut.php

https://github.com/dekoza/openshift-smf-2.0.7
PHP | 733 lines | 456 code | 119 blank | 158 comment | 136 complexity | 5feb06de61001fafee766475add534f0 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0.7
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* This file is concerned pretty entirely, as you see from its name, with
  15. logging in and out members, and the validation of that. It contains:
  16. void Login()
  17. - shows a page for the user to type in their username and password.
  18. - caches the referring URL in $_SESSION['login_url'].
  19. - uses the Login template and language file with the login sub
  20. template.
  21. - if you are using a wireless device, uses the protocol_login sub
  22. template in the Wireless template.
  23. - accessed from ?action=login.
  24. void Login2()
  25. - actually logs you in and checks that login was successful.
  26. - employs protection against a specific IP or user trying to brute
  27. force a login to an account.
  28. - on error, uses the same templates Login() uses.
  29. - upgrades password encryption on login, if necessary.
  30. - after successful login, redirects you to $_SESSION['login_url'].
  31. - accessed from ?action=login2, by forms.
  32. void Logout(bool internal = false)
  33. - logs the current user out of their account.
  34. - requires that the session hash is sent as well, to prevent automatic
  35. logouts by images or javascript.
  36. - doesn't check the session if internal is true.
  37. - redirects back to $_SESSION['logout_url'], if it exists.
  38. - accessed via ?action=logout;session_var=...
  39. string md5_hmac(string data, string key)
  40. - old style SMF 1.0.x/YaBB SE 1.5.x hashing.
  41. - returns the HMAC MD5 of data with key.
  42. string phpBB3_password_check(string passwd, string passwd_hash)
  43. - custom encryption for phpBB3 based passwords.
  44. void validatePasswordFlood(id_member, password_flood_value = false, was_correct = false)
  45. - this function helps protect against brute force attacks on a member's password.
  46. */
  47. // Ask them for their login information.
  48. function Login()
  49. {
  50. global $txt, $context, $scripturl;
  51. // In wireless? If so, use the correct sub template.
  52. if (WIRELESS)
  53. $context['sub_template'] = WIRELESS_PROTOCOL . '_login';
  54. // Otherwise, we need to load the Login template/language file.
  55. else
  56. {
  57. loadLanguage('Login');
  58. loadTemplate('Login');
  59. $context['sub_template'] = 'login';
  60. }
  61. // Get the template ready.... not really much else to do.
  62. $context['page_title'] = $txt['login'];
  63. $context['default_username'] = &$_REQUEST['u'];
  64. $context['default_password'] = '';
  65. $context['never_expire'] = false;
  66. // Add the login chain to the link tree.
  67. $context['linktree'][] = array(
  68. 'url' => $scripturl . '?action=login',
  69. 'name' => $txt['login'],
  70. );
  71. // Set the login URL - will be used when the login process is done (but careful not to send us to an attachment).
  72. if (isset($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'dlattach') === false && preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0)
  73. $_SESSION['login_url'] = $_SESSION['old_url'];
  74. else
  75. unset($_SESSION['login_url']);
  76. }
  77. // Perform the actual logging-in.
  78. function Login2()
  79. {
  80. global $txt, $scripturl, $user_info, $user_settings, $smcFunc;
  81. global $cookiename, $maintenance, $modSettings, $context, $sc, $sourcedir;
  82. // Load cookie authentication stuff.
  83. require_once($sourcedir . '/Subs-Auth.php');
  84. if (isset($_GET['sa']) && $_GET['sa'] == 'salt' && !$user_info['is_guest'])
  85. {
  86. if (isset($_COOKIE[$cookiename]) && preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~', $_COOKIE[$cookiename]) === 1)
  87. list (, , $timeout) = @unserialize($_COOKIE[$cookiename]);
  88. elseif (isset($_SESSION['login_' . $cookiename]))
  89. list (, , $timeout) = @unserialize($_SESSION['login_' . $cookiename]);
  90. else
  91. trigger_error('Login2(): Cannot be logged in without a session or cookie', E_USER_ERROR);
  92. $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
  93. updateMemberData($user_info['id'], array('password_salt' => $user_settings['password_salt']));
  94. setLoginCookie($timeout - time(), $user_info['id'], sha1($user_settings['passwd'] . $user_settings['password_salt']));
  95. redirectexit('action=login2;sa=check;member=' . $user_info['id'], $context['server']['needs_login_fix']);
  96. }
  97. // Double check the cookie...
  98. elseif (isset($_GET['sa']) && $_GET['sa'] == 'check')
  99. {
  100. // Strike! You're outta there!
  101. if ($_GET['member'] != $user_info['id'])
  102. fatal_lang_error('login_cookie_error', false);
  103. // Some whitelisting for login_url...
  104. if (empty($_SESSION['login_url']))
  105. redirectexit();
  106. else
  107. {
  108. // Best not to clutter the session data too much...
  109. $temp = $_SESSION['login_url'];
  110. unset($_SESSION['login_url']);
  111. redirectexit($temp);
  112. }
  113. }
  114. // Beyond this point you are assumed to be a guest trying to login.
  115. if (!$user_info['is_guest'])
  116. redirectexit();
  117. // Are you guessing with a script?
  118. spamProtection('login');
  119. // Set the login_url if it's not already set (but careful not to send us to an attachment).
  120. if (empty($_SESSION['login_url']) && isset($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'dlattach') === false && preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0)
  121. $_SESSION['login_url'] = $_SESSION['old_url'];
  122. // Been guessing a lot, haven't we?
  123. if (isset($_SESSION['failed_login']) && $_SESSION['failed_login'] >= $modSettings['failed_login_threshold'] * 3)
  124. fatal_lang_error('login_threshold_fail', 'critical');
  125. // Set up the cookie length. (if it's invalid, just fall through and use the default.)
  126. if (isset($_POST['cookieneverexp']) || (!empty($_POST['cookielength']) && $_POST['cookielength'] == -1))
  127. $modSettings['cookieTime'] = 3153600;
  128. elseif (!empty($_POST['cookielength']) && ($_POST['cookielength'] >= 1 || $_POST['cookielength'] <= 525600))
  129. $modSettings['cookieTime'] = (int) $_POST['cookielength'];
  130. loadLanguage('Login');
  131. // Load the template stuff - wireless or normal.
  132. if (WIRELESS)
  133. $context['sub_template'] = WIRELESS_PROTOCOL . '_login';
  134. else
  135. {
  136. loadTemplate('Login');
  137. $context['sub_template'] = 'login';
  138. }
  139. // Set up the default/fallback stuff.
  140. $context['default_username'] = isset($_POST['user']) ? preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($_POST['user'])) : '';
  141. $context['default_password'] = '';
  142. $context['never_expire'] = $modSettings['cookieTime'] == 525600 || $modSettings['cookieTime'] == 3153600;
  143. $context['login_errors'] = array($txt['error_occured']);
  144. $context['page_title'] = $txt['login'];
  145. // Add the login chain to the link tree.
  146. $context['linktree'][] = array(
  147. 'url' => $scripturl . '?action=login',
  148. 'name' => $txt['login'],
  149. );
  150. if (!empty($_POST['openid_identifier']) && !empty($modSettings['enableOpenID']))
  151. {
  152. require_once($sourcedir . '/Subs-OpenID.php');
  153. if (($open_id = smf_openID_validate($_POST['openid_identifier'])) !== 'no_data')
  154. return $open_id;
  155. }
  156. // You forgot to type your username, dummy!
  157. if (!isset($_POST['user']) || $_POST['user'] == '')
  158. {
  159. $context['login_errors'] = array($txt['need_username']);
  160. return;
  161. }
  162. // Hmm... maybe 'admin' will login with no password. Uhh... NO!
  163. if ((!isset($_POST['passwrd']) || $_POST['passwrd'] == '') && (!isset($_POST['hash_passwrd']) || strlen($_POST['hash_passwrd']) != 40))
  164. {
  165. $context['login_errors'] = array($txt['no_password']);
  166. return;
  167. }
  168. // No funky symbols either.
  169. if (preg_match('~[<>&"\'=\\\]~', preg_replace('~(&#(\\d{1,7}|x[0-9a-fA-F]{1,6});)~', '', $_POST['user'])) != 0)
  170. {
  171. $context['login_errors'] = array($txt['error_invalid_characters_username']);
  172. return;
  173. }
  174. // And if it's too long, trim it back.
  175. if ($smcFunc['strlen']($_POST['user']) > 80)
  176. {
  177. $_POST['user'] = $smcFunc['substr']($_POST['user'], 0, 79);
  178. $context['default_username'] = preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($_POST['user']));
  179. }
  180. // Are we using any sort of integration to validate the login?
  181. if (in_array('retry', call_integration_hook('integrate_validate_login', array($_POST['user'], isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) == 40 ? $_POST['hash_passwrd'] : null, $modSettings['cookieTime'])), true))
  182. {
  183. $context['login_errors'] = array($txt['login_hash_error']);
  184. $context['disable_login_hashing'] = true;
  185. return;
  186. }
  187. // Load the data up!
  188. $request = $smcFunc['db_query']('', '
  189. SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt,
  190. openid_uri, passwd_flood
  191. FROM {db_prefix}members
  192. WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name) = LOWER({string:user_name})' : 'member_name = {string:user_name}') . '
  193. LIMIT 1',
  194. array(
  195. 'user_name' => $smcFunc['db_case_sensitive'] ? strtolower($_POST['user']) : $_POST['user'],
  196. )
  197. );
  198. // Probably mistyped or their email, try it as an email address. (member_name first, though!)
  199. if ($smcFunc['db_num_rows']($request) == 0)
  200. {
  201. $smcFunc['db_free_result']($request);
  202. $request = $smcFunc['db_query']('', '
  203. SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt, openid_uri,
  204. passwd_flood
  205. FROM {db_prefix}members
  206. WHERE email_address = {string:user_name}
  207. LIMIT 1',
  208. array(
  209. 'user_name' => $_POST['user'],
  210. )
  211. );
  212. // Let them try again, it didn't match anything...
  213. if ($smcFunc['db_num_rows']($request) == 0)
  214. {
  215. $context['login_errors'] = array($txt['username_no_exist']);
  216. return;
  217. }
  218. }
  219. $user_settings = $smcFunc['db_fetch_assoc']($request);
  220. $smcFunc['db_free_result']($request);
  221. // Figure out the password using SMF's encryption - if what they typed is right.
  222. if (isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) == 40)
  223. {
  224. // Needs upgrading?
  225. if (strlen($user_settings['passwd']) != 40)
  226. {
  227. $context['login_errors'] = array($txt['login_hash_error']);
  228. $context['disable_login_hashing'] = true;
  229. unset($user_settings);
  230. return;
  231. }
  232. // Challenge passed.
  233. elseif ($_POST['hash_passwrd'] == sha1($user_settings['passwd'] . $sc))
  234. $sha_passwd = $user_settings['passwd'];
  235. else
  236. {
  237. // Don't allow this!
  238. validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
  239. $_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;
  240. if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold'])
  241. redirectexit('action=reminder');
  242. else
  243. {
  244. log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
  245. $context['disable_login_hashing'] = true;
  246. $context['login_errors'] = array($txt['incorrect_password']);
  247. unset($user_settings);
  248. return;
  249. }
  250. }
  251. }
  252. else
  253. $sha_passwd = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
  254. // Bad password! Thought you could fool the database?!
  255. if ($user_settings['passwd'] != $sha_passwd)
  256. {
  257. // Let's be cautious, no hacking please. thanx.
  258. validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
  259. // Maybe we were too hasty... let's try some other authentication methods.
  260. $other_passwords = array();
  261. // None of the below cases will be used most of the time (because the salt is normally set.)
  262. if ($user_settings['password_salt'] == '')
  263. {
  264. // YaBB SE, Discus, MD5 (used a lot), SHA-1 (used some), SMF 1.0.x, IkonBoard, and none at all.
  265. $other_passwords[] = crypt($_POST['passwrd'], substr($_POST['passwrd'], 0, 2));
  266. $other_passwords[] = crypt($_POST['passwrd'], substr($user_settings['passwd'], 0, 2));
  267. $other_passwords[] = md5($_POST['passwrd']);
  268. $other_passwords[] = sha1($_POST['passwrd']);
  269. $other_passwords[] = md5_hmac($_POST['passwrd'], strtolower($user_settings['member_name']));
  270. $other_passwords[] = md5($_POST['passwrd'] . strtolower($user_settings['member_name']));
  271. $other_passwords[] = md5(md5($_POST['passwrd']));
  272. $other_passwords[] = $_POST['passwrd'];
  273. // This one is a strange one... MyPHP, crypt() on the MD5 hash.
  274. $other_passwords[] = crypt(md5($_POST['passwrd']), md5($_POST['passwrd']));
  275. // Snitz style - SHA-256. Technically, this is a downgrade, but most PHP configurations don't support sha256 anyway.
  276. if (strlen($user_settings['passwd']) == 64 && function_exists('mhash') && defined('MHASH_SHA256'))
  277. $other_passwords[] = bin2hex(mhash(MHASH_SHA256, $_POST['passwrd']));
  278. // phpBB3 users new hashing. We now support it as well ;).
  279. $other_passwords[] = phpBB3_password_check($_POST['passwrd'], $user_settings['passwd']);
  280. // APBoard 2 Login Method.
  281. $other_passwords[] = md5(crypt($_POST['passwrd'], 'CRYPT_MD5'));
  282. }
  283. // The hash should be 40 if it's SHA-1, so we're safe with more here too.
  284. elseif (strlen($user_settings['passwd']) == 32)
  285. {
  286. // vBulletin 3 style hashing? Let's welcome them with open arms \o/.
  287. $other_passwords[] = md5(md5($_POST['passwrd']) . $user_settings['password_salt']);
  288. // Hmm.. p'raps it's Invision 2 style?
  289. $other_passwords[] = md5(md5($user_settings['password_salt']) . md5($_POST['passwrd']));
  290. // Some common md5 ones.
  291. $other_passwords[] = md5($user_settings['password_salt'] . $_POST['passwrd']);
  292. $other_passwords[] = md5($_POST['passwrd'] . $user_settings['password_salt']);
  293. }
  294. elseif (strlen($user_settings['passwd']) == 40)
  295. {
  296. // Maybe they are using a hash from before the password fix.
  297. $other_passwords[] = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
  298. // BurningBoard3 style of hashing.
  299. $other_passwords[] = sha1($user_settings['password_salt'] . sha1($user_settings['password_salt'] . sha1($_POST['passwrd'])));
  300. // Perhaps we converted to UTF-8 and have a valid password being hashed differently.
  301. if ($context['character_set'] == 'utf8' && !empty($modSettings['previousCharacterSet']) && $modSettings['previousCharacterSet'] != 'utf8')
  302. {
  303. // Try iconv first, for no particular reason.
  304. if (function_exists('iconv'))
  305. $other_passwords['iconv'] = sha1(strtolower(iconv('UTF-8', $modSettings['previousCharacterSet'], $user_settings['member_name'])) . un_htmlspecialchars(iconv('UTF-8', $modSettings['previousCharacterSet'], $_POST['passwrd'])));
  306. // Say it aint so, iconv failed!
  307. if (empty($other_passwords['iconv']) && function_exists('mb_convert_encoding'))
  308. $other_passwords[] = sha1(strtolower(mb_convert_encoding($user_settings['member_name'], 'UTF-8', $modSettings['previousCharacterSet'])) . un_htmlspecialchars(mb_convert_encoding($_POST['passwrd'], 'UTF-8', $modSettings['previousCharacterSet'])));
  309. }
  310. }
  311. // SMF's sha1 function can give a funny result on Linux (Not our fault!). If we've now got the real one let the old one be valid!
  312. if (strpos(strtolower(PHP_OS), 'win') !== 0)
  313. {
  314. require_once($sourcedir . '/Subs-Compat.php');
  315. $other_passwords[] = sha1_smf(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
  316. }
  317. // Whichever encryption it was using, let's make it use SMF's now ;).
  318. if (in_array($user_settings['passwd'], $other_passwords))
  319. {
  320. $user_settings['passwd'] = $sha_passwd;
  321. $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
  322. // Update the password and set up the hash.
  323. updateMemberData($user_settings['id_member'], array('passwd' => $user_settings['passwd'], 'password_salt' => $user_settings['password_salt'], 'passwd_flood' => ''));
  324. }
  325. // Okay, they for sure didn't enter the password!
  326. else
  327. {
  328. // They've messed up again - keep a count to see if they need a hand.
  329. $_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;
  330. // Hmm... don't remember it, do you? Here, try the password reminder ;).
  331. if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold'])
  332. redirectexit('action=reminder');
  333. // We'll give you another chance...
  334. else
  335. {
  336. // Log an error so we know that it didn't go well in the error log.
  337. log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
  338. $context['login_errors'] = array($txt['incorrect_password']);
  339. return;
  340. }
  341. }
  342. }
  343. elseif (!empty($user_settings['passwd_flood']))
  344. {
  345. // Let's be sure they weren't a little hacker.
  346. validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood'], true);
  347. // If we got here then we can reset the flood counter.
  348. updateMemberData($user_settings['id_member'], array('passwd_flood' => ''));
  349. }
  350. // Correct password, but they've got no salt; fix it!
  351. if ($user_settings['password_salt'] == '')
  352. {
  353. $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
  354. updateMemberData($user_settings['id_member'], array('password_salt' => $user_settings['password_salt']));
  355. }
  356. // Check their activation status.
  357. if (!checkActivation())
  358. return;
  359. DoLogin();
  360. }
  361. function checkActivation()
  362. {
  363. global $context, $txt, $scripturl, $user_settings, $modSettings;
  364. if (!isset($context['login_errors']))
  365. $context['login_errors'] = array();
  366. // What is the true activation status of this account?
  367. $activation_status = $user_settings['is_activated'] > 10 ? $user_settings['is_activated'] - 10 : $user_settings['is_activated'];
  368. // Check if the account is activated - COPPA first...
  369. if ($activation_status == 5)
  370. {
  371. $context['login_errors'][] = $txt['coppa_no_concent'] . ' <a href="' . $scripturl . '?action=coppa;member=' . $user_settings['id_member'] . '">' . $txt['coppa_need_more_details'] . '</a>';
  372. return false;
  373. }
  374. // Awaiting approval still?
  375. elseif ($activation_status == 3)
  376. fatal_lang_error('still_awaiting_approval', 'user');
  377. // Awaiting deletion, changed their mind?
  378. elseif ($activation_status == 4)
  379. {
  380. if (isset($_REQUEST['undelete']))
  381. {
  382. updateMemberData($user_settings['id_member'], array('is_activated' => 1));
  383. updateSettings(array('unapprovedMembers' => ($modSettings['unapprovedMembers'] > 0 ? $modSettings['unapprovedMembers'] - 1 : 0)));
  384. }
  385. else
  386. {
  387. $context['disable_login_hashing'] = true;
  388. $context['login_errors'][] = $txt['awaiting_delete_account'];
  389. $context['login_show_undelete'] = true;
  390. return false;
  391. }
  392. }
  393. // Standard activation?
  394. elseif ($activation_status != 1)
  395. {
  396. log_error($txt['activate_not_completed1'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', false);
  397. $context['login_errors'][] = $txt['activate_not_completed1'] . ' <a href="' . $scripturl . '?action=activate;sa=resend;u=' . $user_settings['id_member'] . '">' . $txt['activate_not_completed2'] . '</a>';
  398. return false;
  399. }
  400. return true;
  401. }
  402. function DoLogin()
  403. {
  404. global $txt, $scripturl, $user_info, $user_settings, $smcFunc;
  405. global $cookiename, $maintenance, $modSettings, $context, $sourcedir;
  406. // Load cookie authentication stuff.
  407. require_once($sourcedir . '/Subs-Auth.php');
  408. // Call login integration functions.
  409. call_integration_hook('integrate_login', array($user_settings['member_name'], isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) == 40 ? $_POST['hash_passwrd'] : null, $modSettings['cookieTime']));
  410. // Get ready to set the cookie...
  411. $username = $user_settings['member_name'];
  412. $user_info['id'] = $user_settings['id_member'];
  413. // Bam! Cookie set. A session too, just in case.
  414. setLoginCookie(60 * $modSettings['cookieTime'], $user_settings['id_member'], sha1($user_settings['passwd'] . $user_settings['password_salt']));
  415. // Reset the login threshold.
  416. if (isset($_SESSION['failed_login']))
  417. unset($_SESSION['failed_login']);
  418. $user_info['is_guest'] = false;
  419. $user_settings['additional_groups'] = explode(',', $user_settings['additional_groups']);
  420. $user_info['is_admin'] = $user_settings['id_group'] == 1 || in_array(1, $user_settings['additional_groups']);
  421. // Are you banned?
  422. is_not_banned(true);
  423. // An administrator, set up the login so they don't have to type it again.
  424. if ($user_info['is_admin'] && isset($user_settings['openid_uri']) && empty($user_settings['openid_uri']))
  425. {
  426. $_SESSION['admin_time'] = time();
  427. unset($_SESSION['just_registered']);
  428. }
  429. // Don't stick the language or theme after this point.
  430. unset($_SESSION['language'], $_SESSION['id_theme']);
  431. // First login?
  432. $request = $smcFunc['db_query']('', '
  433. SELECT last_login
  434. FROM {db_prefix}members
  435. WHERE id_member = {int:id_member}
  436. AND last_login = 0',
  437. array(
  438. 'id_member' => $user_info['id'],
  439. )
  440. );
  441. if ($smcFunc['db_num_rows']($request) == 1)
  442. $_SESSION['first_login'] = true;
  443. else
  444. unset($_SESSION['first_login']);
  445. $smcFunc['db_free_result']($request);
  446. // You've logged in, haven't you?
  447. updateMemberData($user_info['id'], array('last_login' => time(), 'member_ip' => $user_info['ip'], 'member_ip2' => $_SERVER['BAN_CHECK_IP']));
  448. // Get rid of the online entry for that old guest....
  449. $smcFunc['db_query']('', '
  450. DELETE FROM {db_prefix}log_online
  451. WHERE session = {string:session}',
  452. array(
  453. 'session' => 'ip' . $user_info['ip'],
  454. )
  455. );
  456. $_SESSION['log_time'] = 0;
  457. // Just log you back out if it's in maintenance mode and you AREN'T an admin.
  458. if (empty($maintenance) || allowedTo('admin_forum'))
  459. redirectexit('action=login2;sa=check;member=' . $user_info['id'], $context['server']['needs_login_fix']);
  460. else
  461. redirectexit('action=logout;' . $context['session_var'] . '=' . $context['session_id'], $context['server']['needs_login_fix']);
  462. }
  463. // Log the user out.
  464. function Logout($internal = false, $redirect = true)
  465. {
  466. global $sourcedir, $user_info, $user_settings, $context, $modSettings, $smcFunc;
  467. // Make sure they aren't being auto-logged out.
  468. if (!$internal)
  469. checkSession('get');
  470. require_once($sourcedir . '/Subs-Auth.php');
  471. if (isset($_SESSION['pack_ftp']))
  472. $_SESSION['pack_ftp'] = null;
  473. // They cannot be open ID verified any longer.
  474. if (isset($_SESSION['openid']))
  475. unset($_SESSION['openid']);
  476. // It won't be first login anymore.
  477. unset($_SESSION['first_login']);
  478. // Just ensure they aren't a guest!
  479. if (!$user_info['is_guest'])
  480. {
  481. // Pass the logout information to integrations.
  482. call_integration_hook('integrate_logout', array($user_settings['member_name']));
  483. // If you log out, you aren't online anymore :P.
  484. $smcFunc['db_query']('', '
  485. DELETE FROM {db_prefix}log_online
  486. WHERE id_member = {int:current_member}',
  487. array(
  488. 'current_member' => $user_info['id'],
  489. )
  490. );
  491. }
  492. $_SESSION['log_time'] = 0;
  493. // Empty the cookie! (set it in the past, and for id_member = 0)
  494. setLoginCookie(-3600, 0);
  495. // And some other housekeeping while we're at it.
  496. session_destroy();
  497. if (!empty($user_info['id']))
  498. updateMemberData($user_info['id'], array('password_salt' => substr(md5(mt_rand()), 0, 4)));
  499. // Off to the merry board index we go!
  500. if ($redirect)
  501. {
  502. if (empty($_SESSION['logout_url']))
  503. redirectexit('', $context['server']['needs_login_fix']);
  504. else
  505. {
  506. $temp = $_SESSION['logout_url'];
  507. unset($_SESSION['logout_url']);
  508. redirectexit($temp, $context['server']['needs_login_fix']);
  509. }
  510. }
  511. }
  512. // MD5 Encryption used for older passwords.
  513. function md5_hmac($data, $key)
  514. {
  515. $key = str_pad(strlen($key) <= 64 ? $key : pack('H*', md5($key)), 64, chr(0x00));
  516. return md5(($key ^ str_repeat(chr(0x5c), 64)) . pack('H*', md5(($key ^ str_repeat(chr(0x36), 64)) . $data)));
  517. }
  518. // Special encryption used by phpBB3.
  519. function phpBB3_password_check($passwd, $passwd_hash)
  520. {
  521. // Too long or too short?
  522. if (strlen($passwd_hash) != 34)
  523. return;
  524. // Range of characters allowed.
  525. $range = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  526. // Tests
  527. $strpos = strpos($range, $passwd_hash[3]);
  528. $count = 1 << $strpos;
  529. $count2 = $count;
  530. $salt = substr($passwd_hash, 4, 8);
  531. // Things are done differently for PHP 5.
  532. if (@version_compare(PHP_VERSION, '5') >= 0)
  533. {
  534. $hash = md5($salt . $passwd, true);
  535. for (; $count != 0; --$count)
  536. $hash = md5($hash . $passwd, true);
  537. }
  538. else
  539. {
  540. $hash = pack('H*', md5($salt . $passwd));
  541. for (; $count != 0; --$count)
  542. $hash = pack('H*', md5($hash . $passwd));
  543. }
  544. $output = substr($passwd_hash, 0, 12);
  545. $i = 0;
  546. while ($i < 16)
  547. {
  548. $value = ord($hash[$i++]);
  549. $output .= $range[$value & 0x3f];
  550. if ($i < 16)
  551. $value |= ord($hash[$i]) << 8;
  552. $output .= $range[($value >> 6) & 0x3f];
  553. if ($i++ >= 16)
  554. break;
  555. if ($i < 16)
  556. $value |= ord($hash[$i]) << 16;
  557. $output .= $range[($value >> 12) & 0x3f];
  558. if ($i++ >= 16)
  559. break;
  560. $output .= $range[($value >> 18) & 0x3f];
  561. }
  562. // Return now.
  563. return $output;
  564. }
  565. // This protects against brute force attacks on a member's password. Importantly even if the password was right we DON'T TELL THEM!
  566. function validatePasswordFlood($id_member, $password_flood_value = false, $was_correct = false)
  567. {
  568. global $smcFunc, $cookiename, $sourcedir;
  569. // As this is only brute protection, we allow 5 attempts every 10 seconds.
  570. // Destroy any session or cookie data about this member, as they validated wrong.
  571. require_once($sourcedir . '/Subs-Auth.php');
  572. setLoginCookie(-3600, 0);
  573. if (isset($_SESSION['login_' . $cookiename]))
  574. unset($_SESSION['login_' . $cookiename]);
  575. // We need a member!
  576. if (!$id_member)
  577. {
  578. // Redirect back!
  579. redirectexit();
  580. // Probably not needed, but still make sure...
  581. fatal_lang_error('no_access', false);
  582. }
  583. // Right, have we got a flood value?
  584. if ($password_flood_value !== false)
  585. @list ($time_stamp, $number_tries) = explode('|', $password_flood_value);
  586. // Timestamp or number of tries invalid?
  587. if (empty($number_tries) || empty($time_stamp))
  588. {
  589. $number_tries = 0;
  590. $time_stamp = time();
  591. }
  592. // They've failed logging in already
  593. if (!empty($number_tries))
  594. {
  595. // Give them less chances if they failed before
  596. $number_tries = $time_stamp < time() - 20 ? 2 : $number_tries;
  597. // They are trying too fast, make them wait longer
  598. if ($time_stamp < time() - 10)
  599. $time_stamp = time();
  600. }
  601. $number_tries++;
  602. // Broken the law?
  603. if ($number_tries > 5)
  604. fatal_lang_error('login_threshold_brute_fail', 'critical');
  605. // Otherwise set the members data. If they correct on their first attempt then we actually clear it, otherwise we set it!
  606. updateMemberData($id_member, array('passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries));
  607. }
  608. ?>