LogInOut.php 25 KB

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