Articles / Security

  • go
  • argon2
  • timing-attack
  • authentication
  • username-enumeration
  • security

Constant-Time Password Checks Still Reveal Which Accounts Exist

You used subtle.ConstantTimeCompare on the hashes, the code review nodded, and the login endpoint still tells an attacker which usernames are real. The compare was never the problem. The problem is the line above it that returns early when the user is not found.

The bug is the early return

Here is the shape of code I see a lot:

func verify(users map[string]User, name, password string) bool {
	u, ok := users[name]
	if !ok {
		return false // fast path: no hash computed
	}
	got := argon2.IDKey([]byte(password), u.Salt, 1, 64*1024, 4, 32)
	return subtle.ConstantTimeCompare(got, u.Hash) == 1
}

For an unknown user this returns in microseconds. For a known user it runs Argon2id, which is deliberately slow, so tens of milliseconds. The slow hash is the oracle: the response time says "this account exists" long before any byte comparison happens.

Why the constant-time compare is beside the point

Comparing two 32-byte slices takes nanoseconds either way. The difference between a leaky and a non-leaky compare is invisible next to a 50ms hash, and it only matters once the attacker already has a username and is guessing the hash bytes, which they cannot do remotely anyway since they never see the stored hash.

So the constant-time compare protects a small thing, and the early return exposes a big thing. Both belong in the review, but only one is measurable over a network.

Measure it before you fix it

A quick check with a benchmark against your own handler is worth more than reasoning about it. Something like this, run against a test server, will show two clearly separate clusters:

func timeLogin(client *http.Client, url, user string) time.Duration {
	body := strings.NewReader("username=" + user + "&password=wrong")
	start := time.Now()
	resp, err := client.Post(url, "application/x-www-form-urlencoded", body)
	if err == nil {
		resp.Body.Close()
	}
	return time.Since(start)
}

Take the median of a few hundred requests for a real user and for a made-up one. Medians beat means here because network jitter produces long tails. If the two medians differ by anything close to your hash cost, you have the leak.

The fix: always do the work

Hash against a dummy record when the user is missing, then discard the result. Build the dummy once at startup with the same parameters as real records:

var dummy = newDummy()

func newDummy() User {
	salt := make([]byte, 16)
	if _, err := rand.Read(salt); err != nil {
		panic(err)
	}
	return User{Salt: salt, Hash: argon2.IDKey([]byte("dummy"), salt, 1, 64*1024, 4, 32)}
}

func verify(users map[string]User, name, password string) bool {
	u, ok := users[name]
	if !ok {
		u = dummy
	}
	got := argon2.IDKey([]byte(password), u.Salt, 1, 64*1024, 4, 32)
	match := subtle.ConstantTimeCompare(got, u.Hash) == 1
	return ok && match
}

Note the last line: ok && match. Even if someone guesses the dummy password, the missing user still fails.

Quick detour: why a dummy and not a sleep

A tempting alternative is time.Sleep(50 * time.Millisecond) on the miss path. It is worse. Hashing uses CPU and memory, and a sleep uses neither, so under load the two paths diverge: real logins queue behind each other for CPU while fake ones sail through. Doing the same work keeps the timing curves matched even when the server is busy.

It also matches in cost for memory-hard hashes. Argon2 at 64 MiB per attempt stresses allocation in a way a sleep never will.

Parameters have to match, per record

If you store the cost parameters alongside each hash (you should, so you can raise them over time), the dummy needs to match what a typical real record uses. A dummy at time=1 against real users at time=3 recreates the gap at a smaller size, which is still detectable with enough samples.

The practical rule: when you change your default parameters, regenerate the dummy from the same constants. Better still, make one function that produces both, so they cannot drift apart.

Other places the same leak hides

Once the hash timing is level, look at everything else that differs between "no such user" and "wrong password":

  • the error text or status code (one says "unknown user", the other "bad password")
  • response size or headers, including a Set-Cookie that only appears for real accounts
  • the database query itself, if the lookup hits an index for one case and a full scan for another
  • lockout or rate-limit behaviour that only applies to existing accounts
  • work done after a failure, such as writing an audit row or sending an alert email

The lockout one is sneaky. If five bad passwords lock a real account but never a fake one, an attacker can tell them apart by trying six times. Track failures per username string whether or not the account exists.

What this does not fix

Registration and password reset are separate oracles. "That email is already registered" tells the attacker exactly what you tried to hide at login. The usual answer is a neutral message ("if that address exists, we have sent a link") with identical timing, which means queueing the email asynchronously for both cases.

And the dummy hash costs you real CPU on every probe for a nonexistent user. That is the price of looking identical, and it is the reason to keep a rate limit in front of the endpoint as well.