LogInOut.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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
  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. // Are we using any sort of integration to validate the login?
  175. 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))
  176. {
  177. $context['login_errors'] = array($txt['login_hash_error']);
  178. $context['disable_login_hashing'] = true;
  179. return;
  180. }
  181. // Load the data up!
  182. $request = $smcFunc['db_query']('', '
  183. SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt,
  184. openid_uri, passwd_flood
  185. FROM {db_prefix}members
  186. WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name) = LOWER({string:user_name})' : 'member_name = {string:user_name}') . '
  187. LIMIT 1',
  188. array(
  189. 'user_name' => $smcFunc['db_case_sensitive'] ? strtolower($_POST['user']) : $_POST['user'],
  190. )
  191. );
  192. // Probably mistyped or their email, try it as an email address. (member_name first, though!)
  193. if ($smcFunc['db_num_rows']($request) == 0)
  194. {
  195. $smcFunc['db_free_result']($request);
  196. $request = $smcFunc['db_query']('', '
  197. SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt, openid_uri,
  198. passwd_flood
  199. FROM {db_prefix}members
  200. WHERE email_address = {string:user_name}
  201. LIMIT 1',
  202. array(
  203. 'user_name' => $_POST['user'],
  204. )
  205. );
  206. // Let them try again, it didn't match anything...
  207. if ($smcFunc['db_num_rows']($request) == 0)
  208. {
  209. $context['login_errors'] = array($txt['username_no_exist']);
  210. return;
  211. }
  212. }
  213. $user_settings = $smcFunc['db_fetch_assoc']($request);
  214. $smcFunc['db_free_result']($request);
  215. // Figure out the password using SMF's encryption - if what they typed is right.
  216. if (isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) == 40)
  217. {
  218. // Needs upgrading?
  219. if (strlen($user_settings['passwd']) != 40)
  220. {
  221. $context['login_errors'] = array($txt['login_hash_error']);
  222. $context['disable_login_hashing'] = true;
  223. unset($user_settings);
  224. return;
  225. }
  226. // Challenge passed.
  227. elseif ($_POST['hash_passwrd'] == sha1($user_settings['passwd'] . $sc))
  228. $sha_passwd = $user_settings['passwd'];
  229. else
  230. {
  231. // Don't allow this!
  232. validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
  233. $_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;
  234. if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold'])
  235. redirectexit('action=reminder');
  236. else
  237. {
  238. log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
  239. $context['disable_login_hashing'] = true;
  240. $context['login_errors'] = array($txt['incorrect_password']);
  241. unset($user_settings);
  242. return;
  243. }
  244. }
  245. }
  246. else
  247. $sha_passwd = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
  248. // Bad password! Thought you could fool the database?!
  249. if ($user_settings['passwd'] != $sha_passwd)
  250. {
  251. // Let's be cautious, no hacking please. thanx.
  252. validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
  253. // Maybe we were too hasty... let's try some other authentication methods.
  254. $other_passwords = array();
  255. // None of the below cases will be used most of the time (because the salt is normally set.)
  256. if ($user_settings['password_salt'] == '')
  257. {
  258. // YaBB SE, Discus, MD5 (used a lot), SHA-1 (used some), SMF 1.0.x, IkonBoard, and none at all.
  259. $other_passwords[] = crypt($_POST['passwrd'], substr($_POST['passwrd'], 0, 2));
  260. $other_passwords[] = crypt($_POST['passwrd'], substr($user_settings['passwd'], 0, 2));
  261. $other_passwords[] = md5($_POST['passwrd']);
  262. $other_passwords[] = sha1($_POST['passwrd']);
  263. $other_passwords[] = md5_hmac($_POST['passwrd'], strtolower($user_settings['member_name']));
  264. $other_passwords[] = md5($_POST['passwrd'] . strtolower($user_settings['member_name']));
  265. $other_passwords[] = md5(md5($_POST['passwrd']));
  266. $other_passwords[] = $_POST['passwrd'];
  267. // This one is a strange one... MyPHP, crypt() on the MD5 hash.
  268. $other_passwords[] = crypt(md5($_POST['passwrd']), md5($_POST['passwrd']));
  269. // Snitz style - SHA-256. Technically, this is a downgrade, but most PHP configurations don't support sha256 anyway.
  270. if (strlen($user_settings['passwd']) == 64 && function_exists('mhash') && defined('MHASH_SHA256'))
  271. $other_passwords[] = bin2hex(mhash(MHASH_SHA256, $_POST['passwrd']));
  272. // phpBB3 users new hashing. We now support it as well ;).
  273. $other_passwords[] = phpBB3_password_check($_POST['passwrd'], $user_settings['passwd']);
  274. // APBoard 2 Login Method.
  275. $other_passwords[] = md5(crypt($_POST['passwrd'], 'CRYPT_MD5'));
  276. }
  277. // The hash should be 40 if it's SHA-1, so we're safe with more here too.
  278. elseif (strlen($user_settings['passwd']) == 32)
  279. {
  280. // vBulletin 3 style hashing? Let's welcome them with open arms \o/.
  281. $other_passwords[] = md5(md5($_POST['passwrd']) . $user_settings['password_salt']);
  282. // Hmm.. p'raps it's Invision 2 style?
  283. $other_passwords[] = md5(md5($user_settings['password_salt']) . md5($_POST['passwrd']));
  284. // Some common md5 ones.
  285. $other_passwords[] = md5($user_settings['password_salt'] . $_POST['passwrd']);
  286. $other_passwords[] = md5($_POST['passwrd'] . $user_settings['password_salt']);
  287. }
  288. elseif (strlen($user_settings['passwd']) == 40)
  289. {
  290. // Maybe they are using a hash from before the password fix.
  291. $other_passwords[] = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
  292. // BurningBoard3 style of hashing.
  293. $other_passwords[] = sha1($user_settings['password_salt'] . sha1($user_settings['password_salt'] . sha1($_POST['passwrd'])));
  294. // Perhaps we converted to UTF-8 and have a valid password being hashed differently.
  295. if ($context['character_set'] == 'utf8' && !empty($modSettings['previousCharacterSet']) && $modSettings['previousCharacterSet'] != 'utf8')
  296. {
  297. // Try iconv first, for no particular reason.
  298. if (function_exists('iconv'))
  299. $other_passwords['iconv'] = sha1(strtolower(iconv('UTF-8', $modSettings['previousCharacterSet'], $user_settings['member_name'])) . un_htmlspecialchars(iconv('UTF-8', $modSettings['previousCharacterSet'], $_POST['passwrd'])));
  300. // Say it aint so, iconv failed!
  301. if (empty($other_passwords['iconv']) && function_exists('mb_convert_encoding'))
  302. $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'])));
  303. }
  304. }
  305. // 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!
  306. if (strpos(strtolower(PHP_OS), 'win') !== 0)
  307. {
  308. require_once($sourcedir . '/Subs-Compat.php');
  309. $other_passwords[] = sha1_smf(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
  310. }
  311. // Whichever encryption it was using, let's make it use SMF's now ;).
  312. if (in_array($user_settings['passwd'], $other_passwords))
  313. {
  314. $user_settings['passwd'] = $sha_passwd;
  315. $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
  316. // Update the password and set up the hash.
  317. updateMemberData($user_settings['id_member'], array('passwd' => $user_settings['passwd'], 'password_salt' => $user_settings['password_salt'], 'passwd_flood' => ''));
  318. }
  319. // Okay, they for sure didn't enter the password!
  320. else
  321. {
  322. // They've messed up again - keep a count to see if they need a hand.
  323. $_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;
  324. // Hmm... don't remember it, do you? Here, try the password reminder ;).
  325. if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold'])
  326. redirectexit('action=reminder');
  327. // We'll give you another chance...
  328. else
  329. {
  330. // Log an error so we know that it didn't go well in the error log.
  331. log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
  332. $context['login_errors'] = array($txt['incorrect_password']);
  333. return;
  334. }
  335. }
  336. }
  337. elseif (!empty($user_settings['passwd_flood']))
  338. {
  339. // Let's be sure they weren't a little hacker.
  340. validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood'], true);
  341. // If we got here then we can reset the flood counter.
  342. updateMemberData($user_settings['id_member'], array('passwd_flood' => ''));
  343. }
  344. // Correct password, but they've got no salt; fix it!
  345. if ($user_settings['password_salt'] == '')
  346. {
  347. $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
  348. updateMemberData($user_settings['id_member'], array('password_salt' => $user_settings['password_salt']));
  349. }
  350. // Check their activation status.
  351. if (!checkActivation())
  352. return;
  353. DoLogin();
  354. }
  355. function checkActivation()
  356. {
  357. global $context, $txt, $scripturl, $user_settings, $modSettings;
  358. if (!isset($context['login_errors']))
  359. $context['login_errors'] = array();
  360. // What is the true activation status of this account?
  361. $activation_status = $user_settings['is_activated'] > 10 ? $user_settings['is_activated'] - 10 : $user_settings['is_activated'];
  362. // Check if the account is activated - COPPA first...
  363. if ($activation_status == 5)
  364. {
  365. $context['login_errors'][] = $txt['coppa_no_concent'] . ' <a href="' . $scripturl . '?action=coppa;member=' . $user_settings['id_member'] . '">' . $txt['coppa_need_more_details'] . '</a>';
  366. return false;
  367. }
  368. // Awaiting approval still?
  369. elseif ($activation_status == 3)
  370. fatal_lang_error('still_awaiting_approval', 'user');
  371. // Awaiting deletion, changed their mind?
  372. elseif ($activation_status == 4)
  373. {
  374. if (isset($_REQUEST['undelete']))
  375. {
  376. updateMemberData($user_settings['id_member'], array('is_activated' => 1));
  377. updateSettings(array('unapprovedMembers' => ($modSettings['unapprovedMembers'] > 0 ? $modSettings['unapprovedMembers'] - 1 : 0)));
  378. }
  379. else
  380. {
  381. $context['disable_login_hashing'] = true;
  382. $context['login_errors'][] = $txt['awaiting_delete_account'];
  383. $context['login_show_undelete'] = true;
  384. return false;
  385. }
  386. }
  387. // Standard activation?
  388. elseif ($activation_status != 1)
  389. {
  390. log_error($txt['activate_not_completed1'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', false);
  391. $context['login_errors'][] = $txt['activate_not_completed1'] . ' <a href="' . $scripturl . '?action=activate;sa=resend;u=' . $user_settings['id_member'] . '">' . $txt['activate_not_completed2'] . '</a>';
  392. return false;
  393. }
  394. return true;
  395. }
  396. function DoLogin()
  397. {
  398. global $txt, $scripturl, $user_info, $user_settings, $smcFunc;
  399. global $cookiename, $maintenance, $modSettings, $context, $sourcedir;
  400. // Load cookie authentication stuff.
  401. require_once($sourcedir . '/Subs-Auth.php');
  402. // Call login integration functions.
  403. 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']));
  404. // Get ready to set the cookie...
  405. $username = $user_settings['member_name'];
  406. $user_info['id'] = $user_settings['id_member'];
  407. // Bam! Cookie set. A session too, just in case.
  408. setLoginCookie(60 * $modSettings['cookieTime'], $user_settings['id_member'], sha1($user_settings['passwd'] . $user_settings['password_salt']));
  409. // Reset the login threshold.
  410. if (isset($_SESSION['failed_login']))
  411. unset($_SESSION['failed_login']);
  412. $user_info['is_guest'] = false;
  413. $user_settings['additional_groups'] = explode(',', $user_settings['additional_groups']);
  414. $user_info['is_admin'] = $user_settings['id_group'] == 1 || in_array(1, $user_settings['additional_groups']);
  415. // Are you banned?
  416. is_not_banned(true);
  417. // An administrator, set up the login so they don't have to type it again.
  418. if ($user_info['is_admin'] && isset($user_settings['openid_uri']) && empty($user_settings['openid_uri']))
  419. {
  420. $_SESSION['admin_time'] = time();
  421. unset($_SESSION['just_registered']);
  422. }
  423. // Don't stick the language or theme after this point.
  424. unset($_SESSION['language'], $_SESSION['id_theme']);
  425. // First login?
  426. $request = $smcFunc['db_query']('', '
  427. SELECT last_login
  428. FROM {db_prefix}members
  429. WHERE id_member = {int:id_member}
  430. AND last_login = 0',
  431. array(
  432. 'id_member' => $user_info['id'],
  433. )
  434. );
  435. if ($smcFunc['db_num_rows']($request) == 1)
  436. $_SESSION['first_login'] = true;
  437. else
  438. unset($_SESSION['first_login']);
  439. $smcFunc['db_free_result']($request);
  440. // You've logged in, haven't you?
  441. updateMemberData($user_info['id'], array('last_login' => time(), 'member_ip' => $user_info['ip'], 'member_ip2' => $_SERVER['BAN_CHECK_IP']));
  442. // Get rid of the online entry for that old guest....
  443. $smcFunc['db_query']('', '
  444. DELETE FROM {db_prefix}log_online
  445. WHERE session = {string:session}',
  446. array(
  447. 'session' => 'ip' . $user_info['ip'],
  448. )
  449. );
  450. $_SESSION['log_time'] = 0;
  451. // Just log you back out if it's in maintenance mode and you AREN'T an admin.
  452. if (empty($maintenance) || allowedTo('admin_forum'))
  453. redirectexit('action=login2;sa=check;member=' . $user_info['id'], $context['server']['needs_login_fix']);
  454. else
  455. redirectexit('action=logout;' . $context['session_var'] . '=' . $context['session_id'], $context['server']['needs_login_fix']);
  456. }
  457. // Log the user out.
  458. function Logout($internal = false, $redirect = true)
  459. {
  460. global $sourcedir, $user_info, $user_settings, $context, $modSettings, $smcFunc;
  461. // Make sure they aren't being auto-logged out.
  462. if (!$internal)
  463. checkSession('get');
  464. require_once($sourcedir . '/Subs-Auth.php');
  465. if (isset($_SESSION['pack_ftp']))
  466. $_SESSION['pack_ftp'] = null;
  467. // They cannot be open ID verified any longer.
  468. if (isset($_SESSION['openid']))
  469. unset($_SESSION['openid']);
  470. // It won't be first login anymore.
  471. unset($_SESSION['first_login']);
  472. // Just ensure they aren't a guest!
  473. if (!$user_info['is_guest'])
  474. {
  475. // Pass the logout information to integrations.
  476. call_integration_hook('integrate_logout', array($user_settings['member_name']));
  477. // If you log out, you aren't online anymore :P.
  478. $smcFunc['db_query']('', '
  479. DELETE FROM {db_prefix}log_online
  480. WHERE id_member = {int:current_member}',
  481. array(
  482. 'current_member' => $user_info['id'],
  483. )
  484. );
  485. }
  486. $_SESSION['log_time'] = 0;
  487. // Empty the cookie! (set it in the past, and for id_member = 0)
  488. setLoginCookie(-3600, 0);
  489. // Off to the merry board index we go!
  490. if ($redirect)
  491. {
  492. if (empty($_SESSION['logout_url']))
  493. redirectexit('', $context['server']['needs_login_fix']);
  494. else
  495. {
  496. $temp = $_SESSION['logout_url'];
  497. unset($_SESSION['logout_url']);
  498. redirectexit($temp, $context['server']['needs_login_fix']);
  499. }
  500. }
  501. }
  502. // MD5 Encryption used for older passwords.
  503. function md5_hmac($data, $key)
  504. {
  505. $key = str_pad(strlen($key) <= 64 ? $key : pack('H*', md5($key)), 64, chr(0x00));
  506. return md5(($key ^ str_repeat(chr(0x5c), 64)) . pack('H*', md5(($key ^ str_repeat(chr(0x36), 64)) . $data)));
  507. }
  508. // Special encryption used by phpBB3.
  509. function phpBB3_password_check($passwd, $passwd_hash)
  510. {
  511. // Too long or too short?
  512. if (strlen($passwd_hash) != 34)
  513. return;
  514. // Range of characters allowed.
  515. $range = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  516. // Tests
  517. $strpos = strpos($range, $passwd_hash[3]);
  518. $count = 1 << $strpos;
  519. $count2 = $count;
  520. $salt = substr($passwd_hash, 4, 8);
  521. // Things are done differently for PHP 5.
  522. if (@version_compare(PHP_VERSION, '5') >= 0)
  523. {
  524. $hash = md5($salt . $passwd, true);
  525. for (; $count != 0; --$count)
  526. $hash = md5($hash . $passwd, true);
  527. }
  528. else
  529. {
  530. $hash = pack('H*', md5($salt . $passwd));
  531. for (; $count != 0; --$count)
  532. $hash = pack('H*', md5($hash . $passwd));
  533. }
  534. $output = substr($passwd_hash, 0, 12);
  535. $i = 0;
  536. while ($i < 16)
  537. {
  538. $value = ord($hash[$i++]);
  539. $output .= $range[$value & 0x3f];
  540. if ($i < 16)
  541. $value |= ord($hash[$i]) << 8;
  542. $output .= $range[($value >> 6) & 0x3f];
  543. if ($i++ >= 16)
  544. break;
  545. if ($i < 16)
  546. $value |= ord($hash[$i]) << 16;
  547. $output .= $range[($value >> 12) & 0x3f];
  548. if ($i++ >= 16)
  549. break;
  550. $output .= $range[($value >> 18) & 0x3f];
  551. }
  552. // Return now.
  553. return $output;
  554. }
  555. // This protects against brute force attacks on a member's password. Importantly even if the password was right we DON'T TELL THEM!
  556. function validatePasswordFlood($id_member, $password_flood_value = false, $was_correct = false)
  557. {
  558. global $smcFunc, $cookiename, $sourcedir;
  559. // As this is only brute protection, we allow 5 attempts every 10 seconds.
  560. // Destroy any session or cookie data about this member, as they validated wrong.
  561. require_once($sourcedir . '/Subs-Auth.php');
  562. setLoginCookie(-3600, 0);
  563. if (isset($_SESSION['login_' . $cookiename]))
  564. unset($_SESSION['login_' . $cookiename]);
  565. // We need a member!
  566. if (!$id_member)
  567. {
  568. // Redirect back!
  569. redirectexit();
  570. // Probably not needed, but still make sure...
  571. fatal_lang_error('no_access', false);
  572. }
  573. // Right, have we got a flood value?
  574. if ($password_flood_value !== false)
  575. @list ($time_stamp, $number_tries) = explode('|', $password_flood_value);
  576. // Timestamp invalid or non-existent?
  577. if (empty($number_tries) || $time_stamp < (time() - 10))
  578. {
  579. // If it wasn't *that* long ago, don't give them another five goes.
  580. $number_tries = !empty($number_tries) && $time_stamp < (time() - 20) ? 2 : 0;
  581. $time_stamp = time();
  582. }
  583. $number_tries++;
  584. // Broken the law?
  585. if ($number_tries > 5)
  586. fatal_lang_error('login_threshold_brute_fail', 'critical');
  587. // Otherwise set the members data. If they correct on their first attempt then we actually clear it, otherwise we set it!
  588. updateMemberData($id_member, array('passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries));
  589. }
  590. ?>