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

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

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