Securus Journal 43.65°N, 79.38°W

TOTP: the six digits behind two-factor login

How an authenticator app turns a shared secret and the clock into a six-digit code, a working implementation checked against the RFC test vectors, what a server has to get right when it checks one, and the attack the codes cannot stop.

Contents

Why the codes exist

A password is a secret that never changes, which is the trouble with it. Once someone has read it over a shoulder, pulled it from a breach dump or typed it into a fake login page for its owner, it works for them exactly as it works for the owner, for as long as nobody changes it.

A one-time password changes every time. In December 2005 members of the Initiative for Open Authentication (OATH), a group of token and security vendors, wrote RFC 4226, which defined HOTP: a code computed from a shared secret and a counter that goes up by one with each login. In May 2011 RFC 6238 replaced the counter with the clock. That is TOTP, and it is what Google Authenticator, Aegis, Ente Auth, 1Password, Bitwarden and nearly every other authenticator app computes when it shows six digits and a shrinking ring.

Nothing in the scheme is secret except the key. The algorithm is public, the time is public, and the app never talks to the server. The server and the app hold the same key, read the same clock, and arrive at the same six digits independently.

How it actually works

There are four steps, and the first two are the whole difference between TOTP and HOTP.

First, take the current Unix time and divide by 30, discarding the remainder. Everyone in the world agrees on that number for the same 30 seconds. RFC 6238 calls it T, and “RECOMMEND[s] a default time-step size of 30 seconds.”

Second, feed T to HOTP as its counter. HOTP computes HMAC-SHA-1 of the counter, written as eight bytes, using the shared key. The result is 20 bytes.

Third, cut it down. RFC 4226 calls this dynamic truncation: the low four bits of the last byte give an offset between 0 and 15, and the four bytes starting at that offset become a 31-bit number (the top bit is masked off so the number is never negative, whatever the language).

Fourth, keep the last six decimal digits of that number, padding with leading zeros.

The key is usually handed over as a QR code. Inside it is a URI in the format Google documented for its Authenticator app, with the key in Base32 (RFC 4648) so it survives being typed by hand:

otpauth://totp/Example:alice@example.com?secret=JBSWY3DPEHPK3PXP&issuer=Example

Scanning it is the enrolment. From then on the phone needs no network at all.

A working implementation

The standard library has everything needed. This is the complete algorithm:

import base64, hashlib, hmac, struct, time

def hotp(key: bytes, counter: int, digits: int = 6, digest=hashlib.sha1) -> str:
    mac = hmac.new(key, struct.pack(">Q", counter), digest).digest()
    offset = mac[-1] & 0x0F
    code = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
    return str(code % 10 ** digits).zfill(digits)

def totp(key: bytes, now: float | None = None, step: int = 30, digits: int = 6, digest=hashlib.sha1) -> str:
    t = int((time.time() if now is None else now) // step)
    return hotp(key, t, digits, digest)

def key_from_base32(secret: str) -> bytes:
    s = secret.replace(" ", "").upper()
    return base64.b32decode(s + "=" * (-len(s) % 8))

struct.pack(">Q", ...) writes the counter as an unsigned 64-bit big-endian integer, which is what the RFC specifies. The & 0x7FFFFFFF is the masked top bit. zfill is the leading zeros: a code of 012345 is a valid code, and an implementation that drops the zero will reject one login in ten.

Both RFCs end with test vectors, and an implementation that has not been run against them is unfinished. With the ASCII key 12345678901234567890:

k = b"12345678901234567890"

# RFC 4226, Appendix D: HOTP for counters 0 to 9
assert [hotp(k, c) for c in range(10)] == [
    "755224", "287082", "359152", "969429", "338314",
    "254676", "287922", "162583", "399871", "520489"]

# RFC 6238, Appendix B: TOTP with SHA-1, 8 digits
for t, want in [(59, "94287082"), (1111111109, "07081804"),
                (1111111111, "14050471"), (1234567890, "89005924"),
                (2000000000, "69279037"), (20000000000, "65353130")]:
    assert totp(k, t, digits=8) == want

The last vector is a time in the year 2603, which catches anyone who keeps Unix time in a 32-bit integer. One trap in Appendix B: the SHA-256 and SHA-512 rows use longer keys (32 and 64 bytes, the same digits repeated), though the table does not say so. Run them with the 20-byte key and they fail on a correct implementation.

Making a new secret is one line. RFC 4226 says the key “MUST be at least 128 bits” and recommends 160:

import secrets
secret = base64.b32encode(secrets.token_bytes(20)).decode()   # 32 Base32 characters

Checking a code on the server

Computing a code is the easy half. A server that checks them has three more jobs, and each one is a line in an RFC that is easy to skip.

Allow for drift, narrowly. Phones run a few seconds fast or slow, and people type the code just as the ring runs out. RFC 6238 says: “We RECOMMEND that at most one time step is allowed as the network delay.” So accept the current step and the one either side, and no more.

Refuse a code that has already worked. The same RFC: “The verifier MUST NOT accept the second attempt of the OTP after the successful validation has been issued for the first OTP.” A code is otherwise good for up to 90 seconds with the window above, plenty of time for someone watching to use it again. Store the last step that succeeded for each user and accept only later ones.

Limit the guesses. Six digits is a million possibilities, and with a three-step window three of them are right at any moment. RFC 4226 puts an attacker’s chance at about sv/10^Digit, for s accepted codes and v attempts. At ten guesses a second for an hour, that is a little over a ten percent chance of getting in, with no throttling. Section 7.3 asks for a maximum number of attempts, and adds that “the delay or lockout schemes MUST be across login sessions,” so an attacker cannot reset the count by reconnecting.

All three fit in one function:

def verify(key: bytes, code: str, last_step: int, now: float | None = None,
           window: int = 1, step: int = 30) -> int | None:
    t = int((time.time() if now is None else now) // step)
    for s in range(t - window, t + window + 1):
        if s > last_step and hmac.compare_digest(hotp(key, s), code):
            return s      # save this as the user's new last_step
    return None

hmac.compare_digest compares in constant time, so the response time leaks nothing about how many digits matched. The rate limit lives outside the function, in front of it, counted per account.

Gotchas worth knowing

The server keeps the secret in a form it can use. A password can be stored as a slow hash, and a stolen hash still has to be cracked. A TOTP key cannot: the server needs the key itself to compute the codes. Anyone who copies the key table can generate valid codes for every user, forever, without touching a phone. RFC 6238 says “The key store MUST be in a secure area,” which in practice means encrypted at rest with the encryption key kept outside the database. If the table ever leaks, every user has to enrol again.

The clock is part of the security. A server whose clock drifts by more than a step starts refusing good codes, and the usual fix, widening the window, makes guessing easier. Keep the server on NTP and leave the window alone.

The QR code is the key. A screenshot of the enrolment screen, a QR code left in a support ticket, or a secret pasted into chat is the second factor, handed over in full. Show it once, over HTTPS, and never log it.

Recovery codes are passwords. Most services hand out a list of single-use backup codes at enrolment. They skip the second factor entirely, so they need the same care as the key: stored hashed on the server, and somewhere offline by the user.

The attack it cannot stop

TOTP proves that someone has the key now. It cannot prove who is asking for the code.

From March 2022 a group that Group-IB later called 0ktapus sent text messages to employees of Twilio, Cloudflare and well over a hundred other companies, linking to pages made to look like their companies’ Okta login. The pages asked for a username, a password, and then the six-digit code, and passed everything to the attackers in real time, inside the 30 seconds the code was good for. Group-IB’s count, published on 25 August 2022, was 9,931 stolen credentials and 5,441 one-time codes, from 136 email domains.

Cloudflare’s account of its part is the clearest lesson. At least 76 employees got the texts, and three typed their credentials into the fake page. Nobody got in. “Cloudflare does not use TOTP codes”; instead, “every employee at the company is issued a FIDO2-compliant security key.” A FIDO2 key signs a challenge bound to the website’s real origin, so a lookalike domain gets a signature that the real site rejects, and there is no code for a person to read out.

CISA’s October 2022 fact sheet, “Implementing Phishing-Resistant MFA,” draws the same line. FIDO/WebAuthn (security keys and passkeys) and PKI smart cards are phishing-resistant; app-based one-time codes are not. App codes, with push prompts that use number matching, are “the best options for small- and medium-size business that cannot immediately implement phishing-resistant MFA.”

Where it fits

TOTP is a large improvement over a password alone. It defeats reused and leaked passwords, which is what most account takeovers use, and it costs nothing: the phone works offline and is already in everyone’s pocket. For a self-hosted service it is often the only second factor on offer, and turning it on is always better than not.

It is weakest exactly where a phishing page is strongest: a person who believes the page in front of them will type whatever it asks for. Where an account matters and passkeys or security keys are supported, use those, and keep TOTP for everything else. Where TOTP is what you run, the four rules above cover most of the ways it fails: a narrow window, no reuse, a limit on guesses, and a key store treated like the password database it really is.

Sources

  • M’Raihi, D., M. Bellare, F. Hoornaert, D. Naccache and O. Ranen. RFC 4226, “HOTP: An HMAC-Based One-Time Password Algorithm.” December 2005.
  • M’Raihi, D., S. Machani, M. Pei and J. Rydell. RFC 6238, “TOTP: Time-Based One-Time Password Algorithm.” May 2011.
  • Josefsson, S. RFC 4648, “The Base16, Base32, and Base64 Data Encodings.” October 2006.
  • Google. “Key Uri Format.” google-authenticator wiki, GitHub.
  • Group-IB. “Roasting 0ktapus: The phishing campaign going after Okta identity credentials.” 25 August 2022.
  • Cloudflare. “The mechanics of a sophisticated phishing scam and how we stopped it.” 9 August 2022.
  • Cybersecurity and Infrastructure Security Agency. “Implementing Phishing-Resistant MFA.” Fact sheet, October 2022.
  • Python Software Foundation. Documentation for the hmac, hashlib, struct, base64 and secrets modules.