Back
+30 XP
Concept

Anti-Brute-Force Lockout State Machine

Automated credential-stuffing bots test thousands of breached password pairs against login endpoints. An account lockout state machine tracks consecutive failed authentication attempts, transitioning the account to a temporary locked state when failure thresholds are breached.

python
# State transitions:
# UNLOCKED -(failed >= threshold)-> LOCKED -(lockout expired)-> UNLOCKED
# UNLOCKED -(successful login)-> Reset failure counter

# Anti-Brute-Force Account Lockout State Machine When credential lists leaked from other websites hit the dark web, automated credential-stuffing bots test hundreds of passwords against your API every second. Without rate limits or lockout guards, weak passwords will be cracked within hours. 🛑🛡️ An **Anti-Brute-Force Lockout State Machine** regulates authentication: - **`record_attempt(username, success)`**: - If the account is currently within a lockout window, immediately return `"LOCKED"`. - On `success=True`: reset the failure counter and return `"ALLOWED"`. - On `success=False`: increment failures. If failures hit `max_attempts`, set `locked_until = now + lockout_sec` and transition to `"LOCKED"`. - **Loss Aversion Note**: Avoid permanent locks! Permanent locks let an attacker deliberately lock out every executive in your company just by sending 5 wrong passwords. Use escalating exponential backoff or temporary cooling-off periods. ```python import time # State tracking: # records[user] = {"fails": int, "locked_until": float} ``` ## Pop Quiz Why should account lockout mechanisms enforce temporary time-based locks rather than permanent locks? - [ ] Permanent lockouts create a trivial denial-of-service vulnerability where attackers intentionally lock out legitimate user accounts. - [ ] Permanent locks corrupt relational database transaction logs during rollback. - [ ] Temporary lockouts allow operating system kernels to flush thread pools to disk. - [ ] Because cryptographic algorithms expire after 24 hours of inactivity. ## Real-World Challenge Implement `AccountLockoutManager(max_attempts: int = 3, lockout_sec: float = 60.0)`: - `record_attempt(username: str, success: bool) -> str`: Returns `"ALLOWED"`, `"FAILED"`, or `"LOCKED"`. - `is_locked(username: str) -> bool`: Returns `True` if currently locked. - Automatically restore `"ALLOWED"` state once `lockout_sec` has elapsed. <details> <summary>Solution</summary> ```python import time class AccountLockoutManager: def __init__(self, max_attempts: int = 3, lockout_sec: float = 0.05): self.max_attempts = max_attempts self.lockout_sec = lockout_sec self._accounts = {} # username -> {"fails": int, "locked_until": float} def record_attempt(self, username: str, success: bool) -> str: now = time.time() record = self._accounts.setdefault(username, {"fails": 0, "locked_until": 0.0}) # Check if already locked if now < record["locked_until"]: return "LOCKED" if success: record["fails"] = 0 record["locked_until"] = 0.0 return "ALLOWED" else: record["fails"] += 1 if record["fails"] >= self.max_attempts: record["locked_until"] = now + self.lockout_sec record["fails"] = 0 return "LOCKED" return "FAILED" def is_locked(self, username: str) -> bool: record = self._accounts.get(username) if not record: return False return time.time() < record["locked_until"] # Verification manager = AccountLockoutManager(max_attempts=3, lockout_sec=0.05) # Attempt 1: Fail assert manager.record_attempt("analyst_bob", success=False) == "FAILED" assert manager.is_locked("analyst_bob") is False # Attempt 2: Fail assert manager.record_attempt("analyst_bob", success=False) == "FAILED" # Attempt 3: Fail -> Reaches max_attempts, locks account assert manager.record_attempt("analyst_bob", success=False) == "LOCKED" assert manager.is_locked("analyst_bob") is True # Even correct credentials fail during active lockout assert manager.record_attempt("analyst_bob", success=True) == "LOCKED" # After lockout window expires, account unlocks and accepts valid login time.sleep(0.06) assert manager.is_locked("analyst_bob") is False assert manager.record_attempt("analyst_bob", success=True) == "ALLOWED" ``` </details>