Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
fix(security): rate limit totp verification
Miguel Ribeiro44e3b62a2e4a
diff --git a/endpoints/db/backup.php b/endpoints/db/backup.phpindex 34e94e7..257d0fb 100644--- a/endpoints/db/backup.php+++ b/endpoints/db/backup.php@@ -32,11 +32,23 @@ function addFolderToZip($dir, $zipArchive, $zipdir = '')}}-$zip = new ZipArchive();-$filename = "backup_" . uniqid() . ".zip";-$zipname = "../../.tmp/" . $filename;+// Build the archive OUTSIDE the web root. Previously it was written to+// ../../.tmp/ with a uniqid()-based name and served statically by nginx, which+// let anyone who could guess the (timestamp-derived, low-entropy) filename+// download the full database unauthenticated. The backup is now streamed+// directly to the authenticated admin below and never persists in a+// web-accessible location.+$zipname = tempnam(sys_get_temp_dir(), 'wallos_backup_');+if ($zipname === false) {+ die(json_encode([+ "success" => false,+ "message" => translate('cannot_open_zip', $i18n)+ ]));+}-if ($zip->open($zipname, ZipArchive::CREATE) !== TRUE) {+$zip = new ZipArchive();+if ($zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {+ @unlink($zipname);die(json_encode(["success" => false,"message" => translate('cannot_open_zip', $i18n)@@ -46,19 +58,30 @@ if ($zip->open($zipname, ZipArchive::CREATE) !== TRUE) {addFolderToZip('../../db/', $zip);addFolderToZip('../../images/uploads/', $zip);-$numberOfFilesAdded = $zip->numFiles;-if ($zip->close() === false) {+ @unlink($zipname);die(json_encode(["success" => false,"message" => "Failed to finalize the zip file"]));-} else {- flush();- die(json_encode([- "success" => true,- "message" => "Zip file created successfully",- "numFiles" => $numberOfFilesAdded,- "file" => $filename- ]));-}\ No newline at end of file+}++// Discard any buffered output (e.g. a stray newline from an included file)+// so it cannot corrupt the binary archive that follows.+while (ob_get_level() > 0) {+ ob_end_clean();+}++// ZipArchive wrote through its own handle after tempnam() created the file at+// 0 bytes, so clear the stat cache before reading its size for Content-Length.+clearstatcache(true, $zipname);++$downloadName = 'Wallos-Backup-' . date('Ymd-His') . '.zip';+header('Content-Type: application/zip');+header('Content-Disposition: attachment; filename="' . $downloadName . '"');+header('Content-Length: ' . filesize($zipname));+header('Cache-Control: no-store');++readfile($zipname);+unlink($zipname);+exit;\ No newline at end of filediff --git a/endpoints/db/import.php b/endpoints/db/import.phpindex 85c6176..d7b3192 100644--- a/endpoints/db/import.php+++ b/endpoints/db/import.php@@ -44,6 +44,39 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {$zip = new ZipArchive();if ($zip->open($fileDestination) === true) {+ // Validate every entry before extracting. ZipArchive::extractTo()+ // offers no protection against path traversal (Zip Slip), and the+ // extraction target sits under the web root, so a crafted archive+ // could otherwise drop an executable script here (RCE).+ // Extensions the web server may execute if extracted into a+ // servable path. .tmp/ is denied at the nginx layer as the primary+ // control; this is defense in depth for other deployments (Apache).+ $blockedExtensions = [+ 'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'pht',+ 'phps', 'phar', 'shtml', 'cgi', 'pl', 'py', 'sh',+ 'htaccess', 'htpasswd'+ ];+ for ($i = 0; $i < $zip->numFiles; $i++) {+ $entry = str_replace('\\', '/', $zip->getNameIndex($i));++ if ($entry === '' || $entry[0] === '/' || in_array('..', explode('/', $entry), true)) {+ $zip->close();+ emptyRestoreFolder();+ die(json_encode([+ "success" => false,+ "message" => "Invalid backup file: unsafe file path detected."+ ]));+ }++ if (in_array(strtolower(pathinfo($entry, PATHINFO_EXTENSION)), $blockedExtensions, true)) {+ $zip->close();+ emptyRestoreFolder();+ die(json_encode([+ "success" => false,+ "message" => "Invalid backup file: disallowed file type detected."+ ]));+ }+ }$zip->extractTo('../../.tmp/restore/');$zip->close();} else {diff --git a/endpoints/db/restore.php b/endpoints/db/restore.phpindex f423927..534c901 100644--- a/endpoints/db/restore.php+++ b/endpoints/db/restore.php@@ -27,10 +27,20 @@ if (isset($_FILES['file'])) {$zip = new ZipArchive();if ($zip->open($fileDestination) === true) {// Validate all entries before extracting — ZipArchive::extractTo() does not- // guarantee protection against path traversal (Zip Slip).+ // guarantee protection against path traversal (Zip Slip), and the extraction+ // target sits under the web root, so a crafted archive could otherwise drop+ // an executable script here (RCE).+ // Extensions the web server may execute if extracted into a servable path.+ // .tmp/ is denied at the nginx layer as the primary control; this is defense+ // in depth for other deployments (Apache).+ $blockedExtensions = [+ 'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'pht',+ 'phps', 'phar', 'shtml', 'cgi', 'pl', 'py', 'sh',+ 'htaccess', 'htpasswd'+ ];for ($i = 0; $i < $zip->numFiles; $i++) {$entry = str_replace('\\', '/', $zip->getNameIndex($i));- if ($entry[0] === '/' || in_array('..', explode('/', $entry), true)) {+ if ($entry === '' || $entry[0] === '/' || in_array('..', explode('/', $entry), true)) {$zip->close();emptyRestoreFolder();die(json_encode([@@ -38,6 +48,14 @@ if (isset($_FILES['file'])) {"message" => "Invalid backup file: unsafe file path detected."]));}+ if (in_array(strtolower(pathinfo($entry, PATHINFO_EXTENSION)), $blockedExtensions, true)) {+ $zip->close();+ emptyRestoreFolder();+ die(json_encode([+ "success" => false,+ "message" => "Invalid backup file: disallowed file type detected."+ ]));+ }}$zip->extractTo('../../.tmp/restore/');$zip->close();diff --git a/endpoints/user/enable_totp.php b/endpoints/user/enable_totp.phpindex c306003..761dbfa 100644--- a/endpoints/user/enable_totp.php+++ b/endpoints/user/enable_totp.php@@ -103,7 +103,10 @@ if ($action === 'verify') {$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);$stmt->bindValue(':totp_secret', $secret, SQLITE3_TEXT);$stmt->bindValue(':backup_codes', json_encode($backupCodes), SQLITE3_TEXT);- $stmt->bindValue(':last_totp_used', time(), SQLITE3_INTEGER);+ // Store the current TOTP time-step (not a raw timestamp): the code+ // just verified above counts as used, so it cannot be replayed as the+ // first login code. totp.php compares against this same step counter.+ $stmt->bindValue(':last_totp_used', intdiv(time(), 30), SQLITE3_INTEGER);$stmt->execute();// Update user totp_enableddiff --git a/includes/i18n/en.php b/includes/i18n/en.phpindex ab3c669..1d48f9c 100644--- a/includes/i18n/en.php+++ b/includes/i18n/en.php@@ -191,6 +191,7 @@ $i18n = ["enable_two_factor_authentication" => "Enable Two Factor Authentication","2fa_already_enabled" => "Two Factor Authentication is already enabled","totp_code_incorrect" => "TOTP code is incorrect",+ "totp_too_many_attempts" => "Too many failed attempts. Please wait a moment and try again.","backup_codes" => "Backup Codes","download_backup_codes" => "Download Backup Codes","copy_to_clipboard" => "Copy to clipboard",diff --git a/includes/ssrf_helper.php b/includes/ssrf_helper.phpindex cdf4821..77deff3 100644--- a/includes/ssrf_helper.php+++ b/includes/ssrf_helper.php@@ -63,6 +63,80 @@ function is_cgnat_ip($ip) {&& $long <= ip2long('100.127.255.255');}+/**+ * Extracts the embedded IPv4 address from an IPv6 transition/mapping form.+ * Covers IPv4-mapped (::ffff:0:0/96), NAT64 (64:ff9b::/96), 6to4 (2002::/16)+ * and Teredo (2001:0000::/32). Returns a dotted-quad string, or null when the+ * address is not one of these forms.+ */+function wallos_extract_embedded_ipv4($ip) {+ $packed = @inet_pton($ip);+ if ($packed === false || strlen($packed) !== 16) {+ return null;+ }+ $b = unpack('C16', $packed); // 1-indexed bytes $b[1]..$b[16]++ // IPv4-mapped ::ffff:0:0/96 (high 80 bits zero, then 0xffff)+ $high80Zero = true;+ for ($i = 1; $i <= 10; $i++) {+ if ($b[$i] !== 0) {+ $high80Zero = false;+ break;+ }+ }+ if ($high80Zero && $b[11] === 0xff && $b[12] === 0xff) {+ return "{$b[13]}.{$b[14]}.{$b[15]}.{$b[16]}";+ }++ // NAT64 64:ff9b::/96 — embedded IPv4 in the last 32 bits+ if ($b[1] === 0x00 && $b[2] === 0x64 && $b[3] === 0xff && $b[4] === 0x9b) {+ return "{$b[13]}.{$b[14]}.{$b[15]}.{$b[16]}";+ }++ // 6to4 2002::/16 — embedded IPv4 in bytes 3-6+ if ($b[1] === 0x20 && $b[2] === 0x02) {+ return "{$b[3]}.{$b[4]}.{$b[5]}.{$b[6]}";+ }++ // Teredo 2001:0000::/32 — client IPv4 in the last 32 bits, bitwise-inverted+ if ($b[1] === 0x20 && $b[2] === 0x01 && $b[3] === 0x00 && $b[4] === 0x00) {+ $o1 = ~$b[13] & 0xff;+ $o2 = ~$b[14] & 0xff;+ $o3 = ~$b[15] & 0xff;+ $o4 = ~$b[16] & 0xff;+ return "{$o1}.{$o2}.{$o3}.{$o4}";+ }++ return null;+}++/**+ * Determines whether an IP address (IPv4 or IPv6) must be treated as+ * private/reserved for SSRF purposes.+ *+ * Extends PHP's filter_var — which does not flag IPv6 transition ranges — by+ * also rejecting NAT64/6to4/Teredo/IPv4-mapped forms. Those can encode an+ * internal IPv4 destination (e.g. the cloud metadata address) and otherwise+ * pass the guard. Any such transition form is treated as unsafe by default; a+ * legitimate destination has no reason to be reached through a transition+ * relay, and admins can still permit specific hosts via the allowlist.+ */+function wallos_ip_is_private_or_reserved($ip) {+ if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false+ || is_cgnat_ip($ip)) {+ return true;+ }++ // filter_var (above) misses IPv6 transition prefixes; catch them here.+ // wallos_extract_embedded_ipv4() returns null for plain IPv4 and for+ // ordinary public IPv6, so only transition forms are blocked here.+ if (wallos_extract_embedded_ipv4($ip) !== null) {+ return true;+ }++ return false;+}+/*** Validates a webhook URL against SSRF attacks and checks the admin allowlist.* If validation fails, it kills the script and outputs a JSON error response.@@ -98,7 +172,7 @@ function validate_webhook_url_for_ssrf($url, $db, $i18n, $userId = null) {$ipWithPort = $port ? $ip . ':' . $port : $ip;// Check if it's a private IP- $is_private = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false || is_cgnat_ip($ip);+ $is_private = wallos_ip_is_private_or_reserved($ip);if ($is_private) {if ($userId != 1) {@@ -148,8 +222,7 @@ function validate_smtp_host($host, $port, $db) {// DNS failure — gethostbyname returns the input unchanged on failureif ($ip === $host && filter_var($host, FILTER_VALIDATE_IP) === false) return false;- $is_private = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false- || is_cgnat_ip($ip);+ $is_private = wallos_ip_is_private_or_reserved($ip);if ($is_private) {$allowlist = wallos_get_effective_ssrf_allowlist($db)['allowlist'];@@ -195,8 +268,7 @@ function validate_oidc_endpoint_url($url, $db) {$targetPort = $port ?: ($scheme === 'https' ? 443 : 80);- $is_private = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false- || is_cgnat_ip($ip);+ $is_private = wallos_ip_is_private_or_reserved($ip);if ($is_private) {$allowlist = wallos_get_effective_ssrf_allowlist($db)['allowlist'];@@ -248,8 +320,7 @@ function is_url_safe_for_ssrf($url, $db, $userId = null) {$hostWithPort = $port ? $urlHost . ':' . $port : $urlHost;$ipWithPort = $port ? $ip . ':' . $port : $ip;- $is_private = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false- || is_cgnat_ip($ip);+ $is_private = wallos_ip_is_private_or_reserved($ip);if ($is_private) {if ($userId != 1) {diff --git a/migrations/000054.php b/migrations/000054.phpnew file mode 100644index 0000000..fa910a9--- /dev/null+++ b/migrations/000054.php@@ -0,0 +1,21 @@+<?php++// This migration adds brute-force protection state to the "totp" table.+// It adds a "failed_attempts" column (consecutive failed 2FA verifications)+// and a "lockout_until" column (unix timestamp until which verification is+// blocked). Both are keyed per account so the lockout survives session resets.++$failedAttemptsColumn = $db->query("SELECT * FROM pragma_table_info('totp') WHERE name='failed_attempts'");+if ($failedAttemptsColumn->fetchArray(SQLITE3_ASSOC) === false) {+ $db->exec('ALTER TABLE totp ADD COLUMN failed_attempts INTEGER DEFAULT 0');+}++$lockoutUntilColumn = $db->query("SELECT * FROM pragma_table_info('totp') WHERE name='lockout_until'");+if ($lockoutUntilColumn->fetchArray(SQLITE3_ASSOC) === false) {+ $db->exec('ALTER TABLE totp ADD COLUMN lockout_until INTEGER DEFAULT 0');+}++$db->exec('UPDATE totp SET failed_attempts = 0 WHERE failed_attempts IS NULL');+$db->exec('UPDATE totp SET lockout_until = 0 WHERE lockout_until IS NULL');++?>diff --git a/nginx.conf b/nginx.confindex e2bb6a1..b73123f 100644--- a/nginx.conf+++ b/nginx.conf@@ -30,14 +30,9 @@ http {index index.php;}- location ~ \.php$ {- root /var/www/html;- fastcgi_pass 127.0.0.1:9000;- fastcgi_index index.php;- fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;- include fastcgi_params;- }-+ # Deny rules must precede the generic \.php$ handler below. nginx evaluates+ # regex locations in order and uses the first match, so these have to come+ # first — otherwise \.php$ matches and executes PHP under .tmp/, logos/, etc.location ~ \.db$ {deny all;return 403;@@ -48,7 +43,10 @@ http {return 403;}- location ~* \.tmp/.*\.php$ {+ # Block all direct access to the temp working directory. Nothing there is+ # ever meant to be served (backups, restore staging, etc.). The prefix+ # match outranks the \.php$ regex below, so extracted PHP is unreachable.+ location ^~ /.tmp/ {deny all;return 403;}@@ -57,6 +55,14 @@ http {deny all;return 403;}++ location ~ \.php$ {+ root /var/www/html;+ fastcgi_pass 127.0.0.1:9000;+ fastcgi_index index.php;+ fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;+ include fastcgi_params;+ }}include /etc/nginx/conf.d/*.conf;diff --git a/nginx.default.conf b/nginx.default.confindex 8ea5d0c..7f7e063 100644--- a/nginx.default.conf+++ b/nginx.default.conf@@ -8,6 +8,32 @@ server {try_files $uri $uri/ /index.php?$args;}+ # Deny rules must precede the generic \.php$ handler below. nginx evaluates+ # regex locations in order and uses the first match, so these have to come+ # first — otherwise \.php$ matches and executes PHP under .tmp/, logos/, etc.+ location ~ \.db$ {+ deny all;+ return 403;+ }++ location ~* images/uploads/logos/.*\.php$ {+ deny all;+ return 403;+ }++ # Block all direct access to the temp working directory. Nothing there is+ # ever meant to be served (backups, restore staging, etc.). The prefix+ # match outranks the \.php$ regex below, so extracted PHP is unreachable.+ location ^~ /.tmp/ {+ deny all;+ return 403;+ }++ location ~* ^/includes/.*\.php$ {+ deny all;+ return 403;+ }+location ~ \.php$ {include fastcgi_params;fastcgi_pass unix:/var/run/php-fpm.sock; # Adjust the path if necessarydiff --git a/scripts/admin.js b/scripts/admin.jsindex 60803aa..3acf873 100644--- a/scripts/admin.js+++ b/scripts/admin.js@@ -102,28 +102,33 @@ function backupDB() {"X-CSRF-Token": window.csrfToken,},})- .then(response => response.json())- .then(data => {- if (data.success) {- const link = document.createElement("a");- const filename = data.file;- link.href = ".tmp/" + filename;-- const date = new Date();- const year = date.getFullYear();- const month = String(date.getMonth() + 1).padStart(2, "0");- const day = String(date.getDate()).padStart(2, "0");- const hours = String(date.getHours()).padStart(2, "0");- const minutes = String(date.getMinutes()).padStart(2, "0");- const timestamp = `${year}${month}${day}-${hours}${minutes}`;- link.download = `Wallos-Backup-${timestamp}.zip`;-- document.body.appendChild(link);- link.click();- document.body.removeChild(link);- } else {+ .then(async response => {+ const contentType = response.headers.get("content-type") || "";+ // Success streams the zip; any failure returns a JSON error body.+ if (!response.ok || !contentType.includes("application/zip")) {+ const data = await response.json().catch(() => ({}));showErrorMessage(data.message || translate("backup_failed"));+ return;}++ const blob = await response.blob();+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;++ const date = new Date();+ const year = date.getFullYear();+ const month = String(date.getMonth() + 1).padStart(2, "0");+ const day = String(date.getDate()).padStart(2, "0");+ const hours = String(date.getHours()).padStart(2, "0");+ const minutes = String(date.getMinutes()).padStart(2, "0");+ const timestamp = `${year}${month}${day}-${hours}${minutes}`;+ link.download = `Wallos-Backup-${timestamp}.zip`;++ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ URL.revokeObjectURL(url);}).catch(error => {console.error(error);diff --git a/totp.php b/totp.phpindex a9d0895..f2f638e 100644--- a/totp.php+++ b/totp.php@@ -44,16 +44,37 @@ $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'];- $statement = $db->prepare('SELECT totp_secret, backup_codes FROM totp WHERE user_id = :id');+ // 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 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';@@ -68,33 +89,88 @@ if (isset($_POST['one-time-code'])) {require_once 'libs/constant_time_encoding/EncoderInterface.php';require_once 'libs/constant_time_encoding/Base32.php';- $clock = new OTPHP\InternalClock();+ $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;+ }+ }- $totp = OTPHP\TOTP::createFromSecret($totp_secret, $clock);- $totp->setPeriod(30);- $valid = $totp->verify($totp_code, null, 15);+ $valid = $matchedStep !== null;- // 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);+ if ($valid && $matchedStep <= $lastUsedStep) {+ // This code's time-step has already been used; reject the replay.+ $valid = false;+ }- $statement = $db->prepare('UPDATE totp SET backup_codes = :backup_codes WHERE user_id = :id');- $statement->bindValue(':backup_codes', json_encode($backupCodes), SQLITE3_TEXT);+ // 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);+ $statement->execute();++ $valid = true;+ }+ } 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);$statement->execute();+ }- $valid = true;+ // 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();+ }}- } else {- $statement = $db->prepare('UPDATE totp SET last_totp_used = :last_totp_used WHERE user_id = :id');- $statement->bindValue(':last_totp_used', time(), SQLITE3_INTEGER);- $statement->bindValue(':id', $_SESSION['totp_user_id'], SQLITE3_INTEGER);- $statement->execute();}if ($valid) {@@ -225,10 +301,13 @@ if (isset($_POST['one-time-code'])) {</div><?phpif ($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><?= translate('totp_code_incorrect', $i18n) ?>+ <i class="fa-solid fa-triangle-exclamation"></i><?= $totpErrorMessage ?></li></ul><?php