Repository navigation
Expand file tree
/
Copy pathtotp.php
More file actions
332 lines (290 loc) · 14.2 KB
/
Copy pathtotp.php
File metadata and controls
332 lines (290 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
<?php
require_once 'includes/connect.php';
require_once 'includes/checkuser.php';
require_once 'includes/i18n/languages.php';
require_once 'includes/i18n/getlang.php';
require_once 'includes/i18n/' . $lang . '.php';
require_once 'includes/version.php';
require_once 'includes/theme_helpers.php';
if ($userCount == 0) {
header("Location: registration.php");
exit();
}
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
$db->close();
header("Location: .");
exit();
}
if (!isset($_SESSION['totp_user_id'])) {
$db->close();
header("Location: login.php");
exit();
}
$theme = "light";
$updateThemeSettings = false;
if (isset($_COOKIE['theme'])) {
$theme = sanitize_theme_mode($_COOKIE['theme']);
} else {
$updateThemeSettings = true;
}
$colorTheme = "blue";
if (isset($_COOKIE['colorTheme'])) {
$colorTheme = sanitize_color_theme($_COOKIE['colorTheme']);
}
$demoMode = getenv('DEMO_MODE');
$cookieExpire = time() + (30 * 24 * 60 * 60);
$invalidTotp = false;
$totpLocked = false;
if (isset($_POST['one-time-code'])) {
$totp_code = $_POST['one-time-code'];
// Brute-force protection: after too many consecutive failed verifications,
// lock the account for a short period. State is persisted per account (not
// per session) so it cannot be reset by re-doing the password step.
$maxTotpAttempts = 5;
$totpLockoutSeconds = 30;
$statement = $db->prepare('SELECT totp_secret, backup_codes, failed_attempts, lockout_until, last_totp_used FROM totp WHERE user_id = :id');
$statement->bindValue(':id', $_SESSION['totp_user_id'], SQLITE3_INTEGER);
$result = $statement->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
$totp_secret = $row['totp_secret'];
$backupCodes = json_decode($row['backup_codes'], true);
$failedAttempts = (int) ($row['failed_attempts'] ?? 0);
$lockoutUntil = (int) ($row['lockout_until'] ?? 0);
$totpLocked = $lockoutUntil > time();
// Interpret last_totp_used as a TOTP time-step counter (used to reject reuse
// of an already-consumed code). Legacy installs stored a raw unix timestamp
// here, which is far larger than any current step, so normalise those by
// dividing by the period.
$currentStep = intdiv(time(), 30);
$lastUsedStep = (int) ($row['last_totp_used'] ?? 0);
if ($lastUsedStep > $currentStep) {
$lastUsedStep = intdiv($lastUsedStep, 30);
}
require_once 'libs/OTPHP/FactoryInterface.php';
require_once 'libs/OTPHP/Factory.php';
require_once 'libs/OTPHP/ParameterTrait.php';
require_once 'libs/OTPHP/OTPInterface.php';
require_once 'libs/OTPHP/OTP.php';
require_once 'libs/OTPHP/TOTPInterface.php';
require_once 'libs/OTPHP/TOTP.php';
require_once 'libs/Psr/Clock/ClockInterface.php';
require_once 'libs/OTPHP/InternalClock.php';
require_once 'libs/constant_time_encoding/Binary.php';
require_once 'libs/constant_time_encoding/EncoderInterface.php';
require_once 'libs/constant_time_encoding/Base32.php';
$valid = false;
if ($totpLocked) {
// Account is temporarily locked out; do not evaluate the submitted code.
$invalidTotp = true;
} else {
$clock = new OTPHP\InternalClock();
$totp = OTPHP\TOTP::createFromSecret($totp_secret, $clock);
$totp->setPeriod(30);
// Verify the code ourselves so we know which time-step matched. The
// library's verify() only returns a boolean, but we need the step to
// reject reuse of an already-consumed code (replay). This mirrors the
// library's leeway logic: check the previous, current and next step.
$totpPeriod = 30;
$totpLeeway = 15;
$now = time();
$matchedStep = null;
foreach ([$now - $totpLeeway, $now, $now + $totpLeeway] as $candidate) {
if ($candidate < 0) {
continue;
}
if (hash_equals($totp->at($candidate), (string) $totp_code)) {
$matchedStep = intdiv($candidate, $totpPeriod);
break;
}
}
$valid = $matchedStep !== null;
if ($valid && $matchedStep <= $lastUsedStep) {
// This code's time-step has already been used; reject the replay.
$valid = false;
}
// If totp is not valid check backup codes
if (!$valid) {
if (in_array($totp_code, $backupCodes)) {
$key = array_search($totp_code, $backupCodes);
unset($backupCodes[$key]);
$backupCodes = array_values($backupCodes);
$statement = $db->prepare('UPDATE totp SET backup_codes = :backup_codes WHERE user_id = :id');
$statement->bindValue(':backup_codes', json_encode($backupCodes), SQLITE3_TEXT);
$statement->bindValue(':id', $_SESSION['totp_user_id'], SQLITE3_INTEGER);
// A backup code is single-use, so it counts only once it has
// actually been struck off. Honouring one whose removal failed
// would leave it usable indefinitely.
$valid = $statement->execute() !== false;
}
} else {
// Record the matched time-step so the same code cannot be reused.
$statement = $db->prepare('UPDATE totp SET last_totp_used = :last_totp_used WHERE user_id = :id');
$statement->bindValue(':last_totp_used', $matchedStep, SQLITE3_INTEGER);
$statement->bindValue(':id', $_SESSION['totp_user_id'], SQLITE3_INTEGER);
// The login still proceeds if this cannot be stored — the code was
// genuine — but the replay window is then unguarded, so say so.
if ($statement->execute() === false) {
error_log('Wallos: could not record the used TOTP step for user '
. (int) $_SESSION['totp_user_id'] . '; this code stays replayable until it expires');
}
}
// Update brute-force counters based on the result of this attempt.
if ($valid) {
$counterStmt = $db->prepare('UPDATE totp SET failed_attempts = 0, lockout_until = 0 WHERE user_id = :id');
$counterStmt->bindValue(':id', $_SESSION['totp_user_id'], SQLITE3_INTEGER);
$counterStmt->execute();
} else {
$invalidTotp = true;
$failedAttempts++;
if ($failedAttempts >= $maxTotpAttempts) {
// Trip the lockout and reset the counter so a fresh window
// begins once the lockout expires.
$counterStmt = $db->prepare('UPDATE totp SET failed_attempts = 0, lockout_until = :lockout WHERE user_id = :id');
$counterStmt->bindValue(':lockout', time() + $totpLockoutSeconds, SQLITE3_INTEGER);
$counterStmt->bindValue(':id', $_SESSION['totp_user_id'], SQLITE3_INTEGER);
$counterStmt->execute();
$totpLocked = true;
} else {
$counterStmt = $db->prepare('UPDATE totp SET failed_attempts = :attempts WHERE user_id = :id');
$counterStmt->bindValue(':attempts', $failedAttempts, SQLITE3_INTEGER);
$counterStmt->bindValue(':id', $_SESSION['totp_user_id'], SQLITE3_INTEGER);
$counterStmt->execute();
}
}
}
if ($valid) {
$query = "SELECT id, username, main_currency, language FROM user WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->bindValue(':id', $_SESSION['totp_user_id'], SQLITE3_INTEGER);
$result = $stmt->execute();
$user = $result->fetchArray(SQLITE3_ASSOC);
session_regenerate_id(true);
$_SESSION['username'] = $user['username'];
$_SESSION['loggedin'] = true;
$_SESSION['main_currency'] = $user['main_currency'];
$_SESSION['userId'] = $user['id'];
if (!empty($_SESSION['pending_remember_me'])) {
$token = bin2hex(random_bytes(32));
$addLoginTokens = "INSERT INTO login_tokens (user_id, token) VALUES (:userId, :token)";
$addLoginTokensStmt = $db->prepare($addLoginTokens);
$addLoginTokensStmt->bindParam(':userId', $user['id'], SQLITE3_INTEGER);
$addLoginTokensStmt->bindParam(':token', $token, SQLITE3_TEXT);
$addLoginTokensStmt->execute();
$_SESSION['token'] = $token;
$cookieExpire = time() + (30 * 24 * 60 * 60);
$cookieValue = $user['username'] . "|" . $token . "|" . $user['main_currency'];
setcookie('wallos_login', $cookieValue, [
'expires' => $cookieExpire,
'samesite' => 'Lax',
'httponly' => true,
]);
unset($_SESSION['pending_remember_me']);
}
setcookie('language', $user['language'], [
'expires' => $cookieExpire,
'samesite' => 'Lax'
]);
if (!isset($_COOKIE['sortOrder'])) {
setcookie('sortOrder', 'next_payment', [
'expires' => $cookieExpire,
'samesite' => 'Lax'
]);
}
$query = "SELECT color_theme FROM settings WHERE user_id = :id";
$stmt = $db->prepare($query);
$stmt->bindValue(':id', $_SESSION['totp_user_id'], SQLITE3_INTEGER);
$result = $stmt->execute();
$settings = $result->fetchArray(SQLITE3_ASSOC);
setcookie('colorTheme', $settings['color_theme'], [
'expires' => $cookieExpire,
'samesite' => 'Lax'
]);
unset($_SESSION['totp_user_id']);
$db->close();
header("Location: .");
exit();
}
}
?>
<!DOCTYPE html>
<html dir="<?= $languages[$lang]['dir'] ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="theme-color" content="<?= $theme == "light" ? "#FFFFFF" : "#12151C" ?>" id="theme-color" />
<meta name="apple-mobile-web-app-title" content="Wallos">
<title>Wallos - Subscription Tracker</title>
<link rel="icon" type="image/png" href="images/icon/favicon.ico" sizes="16x16">
<link rel="apple-touch-icon" href="images/icon/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="152x152" href="images/icon/apple-touch-icon-152.png">
<link rel="apple-touch-icon" sizes="180x180" href="images/icon/apple-touch-icon-180.png">
<link rel="manifest" href="manifest.php">
<link rel="stylesheet" href="styles/theme.css?<?= $version ?>">
<link rel="stylesheet" href="styles/login.css?<?= $version ?>">
<link rel="stylesheet" href="styles/themes/red.css?<?= $version ?>" id="red-theme" <?= $colorTheme != "red" ? "disabled" : "" ?>>
<link rel="stylesheet" href="styles/themes/green.css?<?= $version ?>" id="green-theme" <?= $colorTheme != "green" ? "disabled" : "" ?>>
<link rel="stylesheet" href="styles/themes/yellow.css?<?= $version ?>" id="yellow-theme" <?= $colorTheme != "yellow" ? "disabled" : "" ?>>
<link rel="stylesheet" href="styles/themes/purple.css?<?= $version ?>" id="purple-theme" <?= $colorTheme != "purple" ? "disabled" : "" ?>>
<link rel="stylesheet" href="styles/font-awesome.min.css">
<link rel="stylesheet" href="styles/barlow.css">
<link rel="stylesheet" href="styles/login-dark-theme.css?<?= $version ?>" id="dark-theme" <?= $theme == "light" ? "disabled" : "" ?>>
<script type="text/javascript">
window.update_theme_settings = "<?= $updateThemeSettings ?>";
window.color_theme = <?= json_encode($colorTheme, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_APOS) ?>;
</script>
<script type="text/javascript" src="scripts/login.js?<?= $version ?>"></script>
<script type="text/javascript" src="scripts/auth-theme.js?<?= $version ?>"></script>
</head>
<body class="<?= $languages[$lang]['dir'] ?>">
<button type="button" class="theme-toggle" id="theme-toggle" title="<?= translate('theme', $i18n) ?>"
aria-label="<?= translate('theme', $i18n) ?>">
<i class="fa-solid <?= $theme == "dark" ? "fa-sun" : "fa-moon" ?>"></i>
</button>
<div class="content auth-split">
<aside class="auth-brand" aria-hidden="true">
<div class="auth-brand-logo">
<?php include "images/siteicons/svg/logo.php"; ?>
</div>
<div class="auth-brand-text">
<h1><?= translate('auth_tagline', $i18n) ?></h1>
<p><?= translate('auth_tagline_sub', $i18n) ?></p>
</div>
<div class="auth-brand-footer">Wallos — Subscription Tracker</div>
</aside>
<section class="container">
<header>
<div class="logo-image" title="Wallos - Subscription Tracker">
<?php include "images/siteicons/svg/logo.php"; ?>
</div>
<p>
<?= translate('insert_totp_code', $i18n) ?>
</p>
</header>
<form action="totp.php" method="post">
<div class="form-group">
<label for="one-time-code"><?= translate('totp_code', $i18n) ?>:</label>
<input type="text" id="one-time-code" name="one-time-code" autocomplete="one-time-code" required>
</div>
<div class="form-group">
<input type="submit" value="<?= translate('login', $i18n) ?>">
</div>
<?php
if ($invalidTotp) {
$totpErrorMessage = $totpLocked
? translate('totp_too_many_attempts', $i18n)
: translate('totp_code_incorrect', $i18n);
?>
<ul class="error-box">
<li>
<i class="fa-solid fa-triangle-exclamation"></i><?= $totpErrorMessage ?>
</li>
</ul>
<?php
}
?>
</form>
</section>
</div>
</body>
</html>