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

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

847
		@list ($time_stamp, $number_tries) = explode('|', /** @scrutinizer ignore-type */ $password_flood_value);
Loading history...
848
849
	// Timestamp or number of tries invalid?
850
	if (empty($number_tries) || empty($time_stamp))
851
	{
852
		$number_tries = 0;
853
		$time_stamp = time();
854
	}
855
856
	// They've failed logging in already
857
	if (!empty($number_tries))
858
	{
859
		// Give them less chances if they failed before
860
		$number_tries = $time_stamp < time() - 20 ? 2 : $number_tries;
861
862
		// They are trying too fast, make them wait longer
863
		if ($time_stamp < time() - 10)
864
			$time_stamp = time();
865
	}
866
867
	$number_tries++;
868
869
	// Broken the law?
870
	if ($number_tries > 5)
871
		fatal_lang_error('login_threshold_brute_fail', 'login', [$member_name]);
872
873
	// Otherwise set the members data. If they correct on their first attempt then we actually clear it, otherwise we set it!
874
	updateMemberData($id_member, array('passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries));
875
876
}
877
878
?>