Skip to content
md ~/writing/hesabi-onceden-ele-gecirme-account-pre-hijacking
All posts

· 8 min read

Account Pre-Hijacking: Why My First Fix Fell Short

Account Pre-Hijacking: Why My First Fix Fell Short

A sign-up form with e-mail confirmation looks safe: the account cannot be used until the owner of the address opens the link. But if the code does not clearly answer "once the address is confirmed, whose password does the account have?", someone who signs up first with another person's address can take that account over. This is called account pre-hijacking. This post is about how I found it in Seans, my cinema booking site, why my first fix fell short, and how I finally redesigned the sign-up flow.

The sign-up flow and the old code

The first sign-up flow in Seans was the usual one: the user enters name, e-mail and password, the account is created unconfirmed, a link goes to the address, opening it confirms the address and logs the user in. The form never reveals whether an address is registered; it always says "check your e-mail".

There was an edge case: what if someone signs up again with an unconfirmed address? The first attempt might have had a mistyped password, so sending a new link seemed sensible:

if (existing.emailVerifiedAt) {
  // confirmed: send the owner a password reset link
} else {
  // Not confirmed yet: the first registration may have had a typo'd password; resend the link.
  const verifyToken = await createEmailToken(db(), existing.id, 'VERIFY_EMAIL');
  await mail(existing, 'verify', input.lang, link('/verify-email', verifyToken));
}

With that code, this was possible:

  1. An attacker signs up with Ayşe's address and their own password. The link goes to Ayşe's inbox; she doesn't open it.
  2. One day Ayşe signs up with her own password. The code sends a new link but does not change the password.
  3. Ayşe opens the link, the address is confirmed, she is logged in and suspects nothing.
  4. The attacker logs into Ayşe's account with their own password.

First fix: each link carries its own password

I found this in the final review before release. My first fix: every sign-up attempt ties its own password to its own link. The link's database record got the hash of the password chosen in that sign-up, and opening the link set the account's password to the one the link carried. I turned the scenario into a test: the attacker signs up, Ayşe signs up, the attacker signs up again, Ayşe opens her own link. The test was red on the old code and green on the new one.

The fix was incomplete, and I noticed twelve days later while rereading the code to write this post.

Why it was incomplete

The test's assumption says it all: "Ayşe opens her own link." In reality Ayşe's inbox held two e-mails: one from her sign-up and one triggered by the attacker. Their subject, text and button were identical. If the attacker signed up after Ayşe, the top e-mail was the link carrying the attacker's password:

  1. Ayşe signs up with her own password.
  2. The attacker signs up with Ayşe's address and their own password. A second link lands in Ayşe's inbox.
  3. Ayşe opens the newest e-mail. The account is confirmed with the attacker's password.

The "send the confirmation e-mail again" button led to the same place: that link carried no password and kept the account's latest one, which could be the attacker's.

The root of the bug had not moved: the account's password still came from whoever filled in the sign-up form. I had only changed the answer to "which form's password". As long as the attacker could also decide whose link landed in the inbox, that answer was not safe.

The real fix: the inbox owner chooses the password

This time I asked the question the other way round: what is the one thing in this flow the attacker cannot reach? Ayşe's inbox. So every piece of information that decides anything about the account has to be entered after the link in that inbox is opened.

The sign-up form now asks only for the e-mail address. The account is created with neither a name nor a password:

// Not confirmed yet (a first try, or someone else typing this address): nothing about the
// account is set here, so a sign-up form cannot plant a name or password on it.
const user = existing ?? (await db().user.create({ data: { email: input.email, name: '' } }));
const verifyToken = await createEmailToken(db(), user.id, 'VERIFY_EMAIL');
await mail(user, 'verify', input.lang, link('/verify-email', verifyToken));

The link opens a "Create your account" page where the name and password are chosen. Password rules are checked before the link is used up, so a weak password can be fixed and retried:

const record = await findEmailToken(db(), input.token, 'VERIFY_EMAIL');
// An address that is already confirmed is set up; a leftover sign-up link must not change it.
if (!record || record.user.emailVerifiedAt) throw new AppError(400, 'invalid_or_expired_link');
// Check the password before using up the link, so a weak one can be retried.
const problem = passwordProblem(input.password, { email: record.user.email, name: input.name });
if (problem) throw new AppError(400, problem);
const passwordHash = await hashPassword(input.password);

const userId = await consumeEmailToken(db(), input.token, 'VERIFY_EMAIL');
if (!userId) throw new AppError(400, 'invalid_or_expired_link');
const user = await db().user.update({
  where: { id: userId },
  data: { name: input.name, passwordHash, emailVerifiedAt: new Date() },
});
// The address is confirmed: other sign-up links for it are no longer needed.
await db().emailToken.deleteMany({ where: { userId: user.id, type: 'VERIFY_EMAIL', usedAt: null } });

Now, whichever link in her inbox Ayşe opens, she sets up the account with her own name and password. There is nothing the attacker can write to the account through the sign-up form. The name moved to this page for a reason too: in the old flow, the name the attacker typed appeared in the e-mail sent to Ayşe ("Hello …") and became the account's display name.

Two edge cases the new flow created are covered as well:

  • Logging into an account with no password: if a sign-up was never finished, the account has no password. A login attempt returns the same error as an unknown address and takes the same time; to keep the timing from revealing that the address exists, a password check is run for unknown addresses too.
  • "Forgot password" on an unfinished sign-up: there is no password to reset, and a reset link would have confirmed the account without a name. In that case the create-account link is sent instead.

Tests: both orders this time

The lesson of the first fix went into the tests. The attacker can sign up before or after Ayşe, and Ayşe opens the newest e-mail:

for (const order of ['attacker first', 'attacker last']) {
  test(`a sign-up with my address by someone else cannot take over my account (${order})`, async () => {
    if (order === 'attacker first') await register(request(app));
    await register(request(app)); // my own sign-up
    if (order === 'attacker last') await register(request(app));
    // The newest e-mail in my inbox may be the one the attacker triggered; I open that one.
    const newest = tokenFromMail();
    // ...
    await complete(request(app), newest).expect(200);
    await login(PASSWORD).expect(200);
    assert.equal((await login(ATTACKER)).body.error, 'invalid_credentials');
  });
}

There are separate tests for the resent link, for a weak password not using up the link, and for "forgot password" on an unfinished sign-up. I broke the protections on purpose: removing the name update broke three tests, and removing both the deletion of leftover links and the "already set up" check broke the two attack tests.

Shipping without breaking the live site

The change also touched the database schema: a user's password now had to be allowed to be empty, and the password column on links was no longer needed. Doing both at once would have broken the site for the few minutes of the release. The live old code kept writing to the link column, and the new code could not create a user without a password. So I split the release into steps:

  1. First, on the live database, I only allowed the password column to be empty. That change works with the old code too.
  2. I released the new code.
  3. Once the new code was live, a second, small change removed the unused column. Here the order was reversed: the old code read that column, so dropping it earlier would have broken login on the live site.

Before each step I backed up the affected tables and tried the change on the test database first.

What I took away

  • E-mail confirmation proves the address, not the password. Everything applied to the account at confirmation time has to come from the person who has access to the inbox. The most robust way is to ask for it after the link in that inbox is opened.
  • Testing an attack in one order is not enough. My first test tried the order I chose, not the attacker. If the attacker can choose the order, the test has to try every order.
  • A fix can change the symptom instead of the root. The first fix changed "which password" but not who decides it.
  • A schema change has to be thought through together with the old code still running. Changes that add or loosen go before the code; changes that remove go after it.