PageRenderTime 42ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/forum/Sources/LogInOut.php

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