Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Brute force and two-factor authentication

By the end of this chapter, you'll be able to

  • Limit login attempts to slow down brute force
  • Explain the principle of two-factor authentication
  • Compute a TOTP one-time code like an authenticator app
  • Write error messages that do not inform the attacker

Slowing down brute force

A brute-force attack tries passwords one after another. The simplest defence: count recent failures and impose a wait that grows with each failure. A user who gets it wrong twice notices nothing; a bot that wants to test 10,000 passwords is in for years.

def wait_time(failures):
    """Seconds to wait before the next attempt."""
    if failures < 3:
        return 0
    return min(2 ** (failures - 3), 3600)

for n in (1, 3, 5, 8, 15, 20):
    print(f"{n:>2} failures → wait {wait_time(n)} s")
 1 failures → wait 0 s
 3 failures → wait 1 s
 5 failures → wait 4 s
 8 failures → wait 32 s
15 failures → wait 3600 s
20 failures → wait 3600 s

The wait doubles with each failure from the third one, capped at one hour: this is exponential backoff. It is counted per account and per IP address, to also hinder the bot that tries a single password on thousands of accounts. Locking the account permanently would be a bad idea: anyone could lock anyone's account by failing on purpose.

The second factor

Two-factor authentication (2FA) asks for two proofs of different kinds: something you know (the password) and something you have (your phone). The most widespread is the 6-digit TOTP code (Time-based One-Time Password) shown by an authenticator app, which changes every 30 seconds.

On activation, the server and the app share a secret (often via a QR code). Then each one computes the code on its own side from the secret and the time, without communicating:

import hmac, struct

def totp(secret, instant, digits=6, period=30):
    counter = int(instant // period)
    digest = hmac.new(secret, struct.pack(">Q", counter), "sha1").digest()
    offset = digest[-1] & 0x0F
    number = int.from_bytes(digest[offset:offset + 4], "big") & 0x7FFFFFFF
    return str(number % 10 ** digits).zfill(digits)

secret = b"12345678901234567890"
print(totp(secret, 59, digits=8))
print(totp(secret, 1111111109, digits=8))
print(totp(secret, 1111111109))
94287082
07081804
081804
  • the time (in seconds since 1970) is divided by 30: as long as we stay in the same 30-second slice, the counter does not change;
  • an HMAC of the counter, computed with the secret, gives a 20-byte digest;
  • 4 bytes are extracted at a position that depends on the last byte, and the last 6 digits are kept.

The first two results are the test values published in the RFC 6238 standard: our function computes exactly what your authenticator app computes. The test secret, of course, must not be used anywhere else.

The server accepts the code, often also the previous slice's, to tolerate a slight clock drift.

Step 5 of 5
Text description of the animation
  1. At activation, the secret is sent to the phone once, then kept on both sides.
  2. Each side divides the current time by 30: same slice, same counter.
  3. The digest depends on the secret: without it, the code cannot be predicted.
  4. A few operations on the bytes give a 6-digit number.
  5. The server accepts the code, often also the previous slice's, to tolerate a slight clock drift.

A stolen code is only useful for about thirty seconds, and the password alone is no longer enough. Physical security keys and passkeys go even further, as they also resist phishing; SMS is the weakest second factor (number hijacking), but still far better than nothing.

Mini-lab: your own code generatorPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: an attempt limiter

Write a Limiter class that remembers, for each username, the number of failures. Its attempt(username, success) method returns "ok" on success (and resets the counter), "denied" on failure, and "locked" without even checking the password if the username already has 5 failures. Simulate 7 failed attempts on Kofi's account, then a successful one.

Hint 1
A self.failures dictionary with get(username, 0) avoids checking whether the key exists.
Hint 2
The “locked” check comes first in attempt, before looking at whether the attempt succeeded.
Show the solution and common mistakes
class Limiter:
    def __init__(self, maximum=5):
        self.maximum = maximum
        self.failures = {}

    def attempt(self, username, success):
        if self.failures.get(username, 0) >= self.maximum:
            return "locked"
        if success:
            self.failures[username] = 0
            return "ok"
        self.failures[username] = self.failures.get(username, 0) + 1
        return "denied"

limiter = Limiter()
results = [limiter.attempt("kofi", False) for _ in range(7)]
results.append(limiter.attempt("kofi", True))
print(results)
['denied', 'denied', 'denied', 'denied', 'denied', 'locked', 'locked', 'locked']

Even the right password is refused once the threshold is reached: otherwise, the bot would know it had found it. In a real application, the lock would be temporary (the exponential backoff seen above) and also counted per IP address.

Common mistakes:

  • Checking the password before the lock: an attacker could keep trying and recognise the right answer.
  • Resetting the counter on every failure, or never resetting it after a success: in the first case the limit is useless, in the second an honest user ends up locked out.

Summary

  1. 1A wait that grows with each failure makes brute force impractical without bothering users.
  2. 22FA combines what you know (password) and what you have (phone, key).
  3. 3A TOTP code is an HMAC of the shared secret and the time cut into 30-second slices.
  4. 4The same error message for an unknown account and a wrong password prevents enumeration.
  5. 5An attempt limit must apply before even checking the password.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.