Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Enforce lockout and single use at 2FA verify

Juan Denisf6ee8befa1ad
diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.py
index 9d85ec68..cfa1581e 100644
--- a/backend/app/api/two_factor.py
+++ b/backend/app/api/two_factor.py
@@ -5,6 +5,8 @@ Provides endpoints for enabling, disabling, and managing 2FA.
"""
import logging
+import threading
+import time
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import limiter
@@ -19,6 +21,27 @@ logger = logging.getLogger(__name__)
two_factor_bp = Blueprint('two_factor', __name__)
+# Codes and temp tokens already spent at /verify. A TOTP code stays valid for
+# its whole window (~90 s with valid_window=1), so without this a code seen
+# over a shoulder or in a proxy log logs in a second time. Process-local is
+# enough: the panel runs a single worker, and entries outlive their validity.
+_spent = {}
+_spent_lock = threading.Lock()
+_TOTP_REPLAY_SECONDS = 120
+_TEMP_TOKEN_SECONDS = 6 * 60
+
+
+def _spend_once(key, ttl):
+ """Record *key* as used; False if it already was (and hasn't expired)."""
+ now = time.monotonic()
+ with _spent_lock:
+ for k in [k for k, exp in _spent.items() if exp <= now]:
+ del _spent[k]
+ if key in _spent:
+ return False
+ _spent[key] = now + ttl
+ return True
+
@two_factor_bp.route('/status', methods=['GET'])
@jwt_required()
@@ -215,8 +238,19 @@ def verify_2fa_code():
if not user.totp_enabled:
return jsonify({'error': '2FA is not enabled for this account'}), 400
+ # The lockout login enforces applies here too: failed codes count
+ # toward it, so it must also stop the guessing.
+ if user.is_locked:
+ return jsonify({'error': 'Account is locked. Try again later.'}), 429
+
+ jti = token_data.get('jti') or temp_token
+ normalized = str(code).replace(' ', '').replace('-', '')
+
# Try TOTP code first
- if TOTPService.verify_code(user.totp_secret, code):
+ if (TOTPService.verify_code(user.totp_secret, code)
+ and _spend_once(('totp', user.id, normalized), _TOTP_REPLAY_SECONDS)):
+ if not _spend_once(('temp', jti), _TEMP_TOKEN_SECONDS):
+ return jsonify({'error': 'Invalid or expired token'}), 401
# Success - issue real tokens
auth_throttle_service.reset(client_ip)
user.reset_failed_login()
@@ -235,6 +269,8 @@ def verify_2fa_code():
matched_hash = TOTPService.verify_backup_code(code, backup_codes)
if matched_hash:
+ if not _spend_once(('temp', jti), _TEMP_TOKEN_SECONDS):
+ return jsonify({'error': 'Invalid or expired token'}), 401
# Valid backup code - remove it (one-time use)
auth_throttle_service.reset(client_ip)
user.use_backup_code(matched_hash)
diff --git a/backend/tests/test_2fa_verify_hardening.py b/backend/tests/test_2fa_verify_hardening.py
new file mode 100644
index 00000000..31cc1691
--- /dev/null
+++ b/backend/tests/test_2fa_verify_hardening.py
@@ -0,0 +1,65 @@
+"""/2fa/verify must honour the account lockout and must not accept the same
+TOTP code, or the same pending-login token, twice."""
+import time
+from datetime import datetime, timedelta
+
+import pyotp
+import pytest
+
+from factories import make_user
+
+
[email protected](autouse=True)
+def _fresh_state(app):
+ from app import limiter
+ from app.api import two_factor
+ spent = getattr(two_factor, '_spent', {})
+ limiter.reset()
+ spent.clear()
+ yield
+ limiter.reset()
+ spent.clear()
+
+
+def mfa_user(db_session):
+ return make_user(db_session, password='password123', totp_enabled=True,
+ totp_secret=pyotp.random_base32())
+
+
+def _pending(client, user):
+ resp = client.post('/api/v1/auth/login', json={'email': user.email, 'password': 'password123'})
+ assert resp.status_code == 200 and resp.get_json()['requires_2fa']
+ return resp.get_json()['temp_token']
+
+
+def _verify(client, temp_token, code):
+ return client.post('/api/v1/auth/2fa/verify', json={'temp_token': temp_token, 'code': code})
+
+
+def test_a_totp_code_logs_in_only_once(client, mfa_user):
+ code = pyotp.TOTP(mfa_user.totp_secret).now()
+ assert _verify(client, _pending(client, mfa_user), code).status_code == 200
+ replay = _verify(client, _pending(client, mfa_user), code)
+ assert replay.status_code == 401
+ assert 'access_token' not in replay.get_json()
+
+
+def test_a_pending_token_completes_only_one_login(client, mfa_user):
+ totp = pyotp.TOTP(mfa_user.totp_secret)
+ temp = _pending(client, mfa_user)
+ assert _verify(client, temp, totp.now()).status_code == 200
+ # A different code that is also inside the valid window.
+ again = _verify(client, temp, totp.at(time.time() + 30))
+ assert again.status_code == 401
+ assert 'access_token' not in again.get_json()
+
+
+def test_a_locked_account_cannot_finish_with_a_correct_code(client, mfa_user):
+ from app import db
+ temp = _pending(client, mfa_user)
+ mfa_user.locked_until = datetime.utcnow() + timedelta(minutes=15)
+ db.session.commit()
+ resp = _verify(client, temp, pyotp.TOTP(mfa_user.totp_secret).now())
+ assert resp.status_code == 429
+ assert 'access_token' not in resp.get_json()