Issues (1061)

Sources/LogInOut.php (4 issues)

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

689
		setTFACookie((int) $exp - time(), /** @scrutinizer ignore-type */ $salt, hash_salt($user_settings['tfa_backup'], $salt));
Loading history...
690
	}
691
692
	session_destroy();
693
694
	// Off to the merry board index we go!
695
	if ($redirect)
696
	{
697
		if (empty($_SESSION['logout_url']))
698
			redirectexit('', $context['server']['needs_login_fix']);
699
		elseif (!empty($_SESSION['logout_url']) && (strpos($_SESSION['logout_url'], 'http://') === false && strpos($_SESSION['logout_url'], 'https://') === false))
700
		{
701
			unset ($_SESSION['logout_url']);
702
			redirectexit();
703
		}
704
		else
705
		{
706
			$temp = $_SESSION['logout_url'];
707
			unset($_SESSION['logout_url']);
708
709
			redirectexit($temp, $context['server']['needs_login_fix']);
710
		}
711
	}
712
}
713
714
/**
715
 * MD5 Encryption used for older passwords. (SMF 1.0.x/YaBB SE 1.5.x hashing)
716
 *
717
 * @param string $data The data
718
 * @param string $key The key
719
 * @return string The HMAC MD5 of data with key
720
 */
721
function md5_hmac($data, $key)
722
{
723
	$key = str_pad(strlen($key) <= 64 ? $key : pack('H*', md5($key)), 64, chr(0x00));
724
	return md5(($key ^ str_repeat(chr(0x5c), 64)) . pack('H*', md5(($key ^ str_repeat(chr(0x36), 64)) . $data)));
725
}
726
727
/**
728
 * Custom encryption for phpBB3 based passwords.
729
 *
730
 * @param string $passwd The raw (unhashed) password
731
 * @param string $passwd_hash The hashed password
732
 * @return string The hashed version of $passwd
733
 */
734
function phpBB3_password_check($passwd, $passwd_hash)
735
{
736
	// Too long or too short?
737
	if (strlen($passwd_hash) != 34)
738
		return;
739
740
	// Range of characters allowed.
741
	$range = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
742
743
	// Tests
744
	$strpos = strpos($range, $passwd_hash[3]);
745
	$count = 1 << $strpos;
746
	$salt = substr($passwd_hash, 4, 8);
747
748
	$hash = md5($salt . $passwd, true);
749
	for (; $count != 0; --$count)
750
		$hash = md5($hash . $passwd, true);
751
752
	$output = substr($passwd_hash, 0, 12);
753
	$i = 0;
754
	while ($i < 16)
755
	{
756
		$value = ord($hash[$i++]);
757
		$output .= $range[$value & 0x3f];
758
759
		if ($i < 16)
760
			$value |= ord($hash[$i]) << 8;
761
762
		$output .= $range[($value >> 6) & 0x3f];
763
764
		if ($i++ >= 16)
765
			break;
766
767
		if ($i < 16)
768
			$value |= ord($hash[$i]) << 16;
769
770
		$output .= $range[($value >> 12) & 0x3f];
771
772
		if ($i++ >= 16)
773
			break;
774
775
		$output .= $range[($value >> 18) & 0x3f];
776
	}
777
778
	// Return now.
779
	return $output;
780
}
781
782
/**
783
 * This protects against brute force attacks on a member's password.
784
 * Importantly, even if the password was right we DON'T TELL THEM!
785
 *
786
 * @param int $id_member The ID of the member
787
 * @param string $member_name The name of the member.
788
 * @param bool|string $password_flood_value False if we don't have a flood value, otherwise a string with a timestamp and number of tries separated by a |
789
 * @param bool $was_correct Whether or not the password was correct
790
 * @param bool $tfa Whether we're validating for two-factor authentication
791
 */
792
function validatePasswordFlood($id_member, $member_name, $password_flood_value = false, $was_correct = false, $tfa = false)
793
{
794
	global $cookiename, $sourcedir;
795
796
	// As this is only brute protection, we allow 5 attempts every 10 seconds.
797
798
	// Destroy any session or cookie data about this member, as they validated wrong.
799
	// Only if they're not validating for 2FA
800
	if (!$tfa)
801
	{
802
		require_once($sourcedir . '/Subs-Auth.php');
803
		setLoginCookie(-3600, 0);
804
805
		if (isset($_SESSION['login_' . $cookiename]))
806
			unset($_SESSION['login_' . $cookiename]);
807
	}
808
809
	// We need a member!
810
	if (!$id_member)
811
	{
812
		// Redirect back!
813
		redirectexit();
814
815
		// Probably not needed, but still make sure...
816
		fatal_lang_error('no_access', false);
817
	}
818
819
	// Right, have we got a flood value?
820
	if ($password_flood_value !== false)
821
		@list ($time_stamp, $number_tries) = explode('|', $password_flood_value);
0 ignored issues
show
It seems like $password_flood_value can also be of type true; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

821
		@list ($time_stamp, $number_tries) = explode('|', /** @scrutinizer ignore-type */ $password_flood_value);
Loading history...
822
823
	// Timestamp or number of tries invalid?
824
	if (empty($number_tries) || empty($time_stamp))
825
	{
826
		$number_tries = 0;
827
		$time_stamp = time();
828
	}
829
830
	// They've failed logging in already
831
	if (!empty($number_tries))
832
	{
833
		// Give them less chances if they failed before
834
		$number_tries = $time_stamp < time() - 20 ? 2 : $number_tries;
835
836
		// They are trying too fast, make them wait longer
837
		if ($time_stamp < time() - 10)
838
			$time_stamp = time();
839
	}
840
841
	$number_tries++;
842
843
	// Broken the law?
844
	if ($number_tries > 5)
845
		fatal_lang_error('login_threshold_brute_fail', 'login', [$member_name]);
846
847
	// Otherwise set the members data. If they correct on their first attempt then we actually clear it, otherwise we set it!
848
	updateMemberData($id_member, array('passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries));
849
850
}
851
852
?>