LogInOut.php 26 KB

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