LogInOut.php 27 KB

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