Passed
Pull Request — release-2.1 (#5871)
by Jeremy
04:45
created

Logout()   F

Complexity

Conditions 23
Paths 194

Size

Total Lines 89
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 43
c 0
b 0
f 0
nc 194
nop 2
dl 0
loc 89
rs 3.3833

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

738
		setTFACookie((int) $exp - time(), /** @scrutinizer ignore-type */ $salt, hash_salt($user_settings['tfa_backup'], $salt));
Loading history...
739
	}
740
741
	session_destroy();
742
743
	// Off to the merry board index we go!
744
	if ($redirect)
745
	{
746
		if (empty($_SESSION['logout_url']))
747
			redirectexit('', $context['server']['needs_login_fix']);
748
		elseif (!empty($_SESSION['logout_url']) && (strpos($_SESSION['logout_url'], 'http://') === false && strpos($_SESSION['logout_url'], 'https://') === false))
749
		{
750
			unset ($_SESSION['logout_url']);
751
			redirectexit();
752
		}
753
		else
754
		{
755
			$temp = $_SESSION['logout_url'];
756
			unset($_SESSION['logout_url']);
757
758
			redirectexit($temp, $context['server']['needs_login_fix']);
759
		}
760
	}
761
}
762
763
/**
764
 * MD5 Encryption used for older passwords. (SMF 1.0.x/YaBB SE 1.5.x hashing)
765
 *
766
 * @param string $data The data
767
 * @param string $key The key
768
 * @return string The HMAC MD5 of data with key
769
 */
770
function md5_hmac($data, $key)
771
{
772
	$key = str_pad(strlen($key) <= 64 ? $key : pack('H*', md5($key)), 64, chr(0x00));
773
	return md5(($key ^ str_repeat(chr(0x5c), 64)) . pack('H*', md5(($key ^ str_repeat(chr(0x36), 64)) . $data)));
774
}
775
776
/**
777
 * Custom encryption for phpBB3 based passwords.
778
 *
779
 * @param string $passwd The raw (unhashed) password
780
 * @param string $passwd_hash The hashed password
781
 * @return string The hashed version of $passwd
782
 */
783
function phpBB3_password_check($passwd, $passwd_hash)
784
{
785
	// Too long or too short?
786
	if (strlen($passwd_hash) != 34)
787
		return;
788
789
	// Range of characters allowed.
790
	$range = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
791
792
	// Tests
793
	$strpos = strpos($range, $passwd_hash[3]);
794
	$count = 1 << $strpos;
795
	$salt = substr($passwd_hash, 4, 8);
796
797
	$hash = md5($salt . $passwd, true);
798
	for (; $count != 0; --$count)
799
		$hash = md5($hash . $passwd, true);
800
801
	$output = substr($passwd_hash, 0, 12);
802
	$i = 0;
803
	while ($i < 16)
804
	{
805
		$value = ord($hash[$i++]);
806
		$output .= $range[$value & 0x3f];
807
808
		if ($i < 16)
809
			$value |= ord($hash[$i]) << 8;
810
811
		$output .= $range[($value >> 6) & 0x3f];
812
813
		if ($i++ >= 16)
814
			break;
815
816
		if ($i < 16)
817
			$value |= ord($hash[$i]) << 16;
818
819
		$output .= $range[($value >> 12) & 0x3f];
820
821
		if ($i++ >= 16)
822
			break;
823
824
		$output .= $range[($value >> 18) & 0x3f];
825
	}
826
827
	// Return now.
828
	return $output;
829
}
830
831
/**
832
 * This protects against brute force attacks on a member's password.
833
 * Importantly, even if the password was right we DON'T TELL THEM!
834
 *
835
 * @param int $id_member The ID of the member
836
 * @param string $member_name The name of the member.
837
 * @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 |
838
 * @param bool $was_correct Whether or not the password was correct
839
 * @param bool $tfa Whether we're validating for two-factor authentication
840
 */
841
function validatePasswordFlood($id_member, $member_name, $password_flood_value = false, $was_correct = false, $tfa = false)
842
{
843
	global $cookiename, $sourcedir;
844
845
	// As this is only brute protection, we allow 5 attempts every 10 seconds.
846
847
	// Destroy any session or cookie data about this member, as they validated wrong.
848
	// Only if they're not validating for 2FA
849
	if (!$tfa)
850
	{
851
		require_once($sourcedir . '/Subs-Auth.php');
852
		setLoginCookie(-3600, 0);
853
854
		if (isset($_SESSION['login_' . $cookiename]))
855
			unset($_SESSION['login_' . $cookiename]);
856
	}
857
858
	// We need a member!
859
	if (!$id_member)
860
	{
861
		// Redirect back!
862
		redirectexit();
863
864
		// Probably not needed, but still make sure...
865
		fatal_lang_error('no_access', false);
866
	}
867
868
	// Right, have we got a flood value?
869
	if ($password_flood_value !== false)
870
		@list ($time_stamp, $number_tries) = explode('|', $password_flood_value);
0 ignored issues
show
Bug introduced by
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

870
		@list ($time_stamp, $number_tries) = explode('|', /** @scrutinizer ignore-type */ $password_flood_value);
Loading history...
871
872
	// Timestamp or number of tries invalid?
873
	if (empty($number_tries) || empty($time_stamp))
874
	{
875
		$number_tries = 0;
876
		$time_stamp = time();
877
	}
878
879
	// They've failed logging in already
880
	if (!empty($number_tries))
881
	{
882
		// Give them less chances if they failed before
883
		$number_tries = $time_stamp < time() - 20 ? 2 : $number_tries;
884
885
		// They are trying too fast, make them wait longer
886
		if ($time_stamp < time() - 10)
887
			$time_stamp = time();
888
	}
889
890
	$number_tries++;
891
892
	// Broken the law?
893
	if ($number_tries > 5)
894
		fatal_lang_error('login_threshold_brute_fail', 'login', [$member_name]);
895
896
	// Otherwise set the members data. If they correct on their first attempt then we actually clear it, otherwise we set it!
897
	updateMemberData($id_member, array('passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries));
898
899
}
900
901
?>