LogInOut.php 26 KB

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