DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

Stopping replayed activation requests

Capture one successful online activation on the wire — the POST that carries a license key and a device fingerprint and comes back with a signed entitlement — and replay it. If your activation endpoint treats that second, byte-identical request the way it treated the first, you have just minted a second activation from one purchase. No key was cracked, no signature forged; the attacker only pressed "send" twice. Node-locking, seat counting, and signed entitlements all assume each activation request is a distinct event, and a replayed packet quietly breaks that assumption.

The real question

The reflex is to reach for the idempotency key you already added for retry safety. It is the wrong tool, and seeing why is the whole point. An idempotency key makes a duplicate succeed: an honest client that lost the response retries, and the server returns the first result without redoing the work. Replay protection must make a duplicate fail: an attacker resends a captured request, and the server rejects it. Same input on the wire, opposite required outputs. One mechanism cannot be both.

So the real question is how to make a captured activation request fail on reuse while an honest client can still retry. The answer is a server-issued single-use nonce: turn activation into a two-step handshake where the client must first obtain a fresh challenge, and the activation that follows is valid exactly once.

Step one: the server mints a challenge

The client cannot activate cold. It first asks for a challenge, sending only the product and its device fingerprint — nothing secret. The server mints a random nonce, stores it as unconsumed with a short time-to-live, binds it to that device and product, and returns it.

CREATE TABLE activation_challenge (
    nonce        text        PRIMARY KEY,
    product      text        NOT NULL,
    device_hash  text        NOT NULL,
    created_at   timestamptz NOT NULL DEFAULT now(),
    expires_at   timestamptz NOT NULL,
    consumed_at  timestamptz          -- NULL until the activation consumes it
);
Enter fullscreen mode Exit fullscreen mode
public async Task<Challenge> IssueChallengeAsync(string product, string deviceHash)
{
    // 256 bits of CSPRNG output — unguessable, not a counter.
    var nonce     = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
    var expiresAt = _clock.UtcNow.AddMinutes(2);          // short TTL

    await _db.ExecuteAsync(
        """
        INSERT INTO activation_challenge (nonce, product, device_hash, expires_at)
        VALUES (@nonce, @product, @deviceHash, @expiresAt)
        """,
        new { nonce, product, deviceHash, expiresAt });

    return new Challenge(nonce, expiresAt);
}
Enter fullscreen mode Exit fullscreen mode

Two decisions here carry the whole design. The nonce is server-issued, not client-chosen: the server is the party that must guarantee single use, and it can only do that for values it minted and recorded. Written to storage as unconsumed, with an expires_at whose clock is the server's own, the nonce's freshness and single-use both rest on server state rather than on trusting the caller. And it is bound to the device fingerprint and product at mint time, so a nonce handed to one machine cannot be lifted onto an activation for another.

Step two: consume it, atomically

The client now sends the real activation request carrying the nonce it was given. The server's job is to consume that nonce exactly once and reject every later presentation of it. The temptation is to read the row, check consumed_at IS NULL, then update it — but that read-then-write races: two replays landing together both read NULL and both proceed. The fix is a single conditional UPDATE, a compare-and-set that the database serialises under the row lock:

UPDATE activation_challenge
   SET consumed_at = now()
 WHERE nonce       = @nonce
   AND product     = @product
   AND device_hash = @deviceHash
   AND consumed_at IS NULL        -- only if still unconsumed
   AND expires_at  > now()        -- and not expired
Enter fullscreen mode Exit fullscreen mode

The number of rows affected is the entire verdict. One row means this caller is the one that flipped it from unconsumed to consumed, and may proceed. Zero rows means the nonce was already consumed, is expired, or was never bound to this device and product — all of which are refusals. Because consumed_at IS NULL is part of the WHERE clause and the UPDATE is a single statement, two concurrent attempts cannot both win: the first flips the row, the second matches nothing.

public async Task<bool> TryConsumeAsync(string nonce, string product, string deviceHash)
{
    int rows = await _db.ExecuteAsync(
        """
        UPDATE activation_challenge
           SET consumed_at = now()
         WHERE nonce       = @nonce
           AND product     = @product
           AND device_hash = @deviceHash
           AND consumed_at IS NULL
           AND expires_at  > now()
        """,
        new { nonce, product, deviceHash });

    return rows == 1;   // 0 → replayed, expired, or wrong device/product
}

[HttpPost("/v1/activation")]
public async Task<IActionResult> Activate(ActivateRequest req)
{
    if (!await _challenges.TryConsumeAsync(req.Nonce, req.Product, req.DeviceHash))
        return Problem(statusCode: StatusCodes.Status409Conflict,
                       title: "activation challenge already used or expired");

    // Nonce consumed exactly once: now do the real work — verify the key,
    // claim a seat, mint and sign the entitlement — knowing this request
    // cannot be a replay of one you already honoured.
    return Ok(await _activations.ActivateAsync(req));
}
Enter fullscreen mode Exit fullscreen mode





The compare-and-set is the whole defence: the first activation flips consumed_at from NULL and affects one row; the replayed request matches nothing and is rejected with 409.

If you prefer not to carry a consumed_at column, the same compare-and-set is an INSERT into a consumed_nonce table with nonce as the primary key: the first insert wins, the replay hits the unique-constraint violation, and you catch it as the rejection. Both are the single atomic step the design needs; pick whichever your schema already favours.

How the SDK uses it

In the Keyright SDK the two-step handshake is internal. The caller still writes one line; the SDK fetches the challenge, attaches the nonce to the activation, and surfaces a replay rejection as a normal failed LicenseInfo:

var client = KeyrightClient.Initialize(new KeyrightOptions
{
    Product         = "acme-suite",
    PublicKeyBase64 = config["Keyright:PublicKey"],   // verify-only, not a secret
    ServiceUrl      = config["Keyright:ServiceUrl"],   // your self-hosted instance
});

LicenseInfo info = await client.ActivateAsync(userKey);

if (!info.IsValid)
    return Gate.Deny(info.Reason);
Enter fullscreen mode Exit fullscreen mode

The TTL is the one knob worth thinking about. It has to outlast a real round trip over a slow link — a minute or two is generous — yet stay short enough that a captured challenge is useless almost immediately. Because expires_at and now() are both evaluated on the server, the comparison uses a single clock; there is no client/server skew in the consume itself. A short TTL also keeps the challenge table self-pruning: expired rows match nothing and a periodic sweep deletes them.

When it breaks

A single-use nonce defeats one specific attack — passive capture and resend — and it is worth being precise about what it does not cover.

A legitimate retry inside the TTL looks exactly like a replay. If the client sends the activation, the server consumes the nonce and commits, and the response is then lost, the client's retry with the same nonce will be rejected — correctly, because the server cannot tell it apart from a hostile replay. The client recovers by fetching a fresh challenge and activating again, and that is safe only because activation is idempotent per (license key, device fingerprint): re-activating returns the existing seat rather than consuming a second one. This is the complement, not a contradiction — the nonce stops the attacker's replay, idempotency keeps the honest retry correct.

An active man-in-the-middle is not stopped by this alone. An attacker who can sit in the path can read the fresh challenge, alter the body, and forward a request the server accepts; the nonce says nothing about who sent it or whether the bytes were tampered with. That is the job of TLS (so the attacker cannot impersonate the server) and request signing or channel binding (so the body cannot be edited in flight). The nonce assumes your request reaches the real server intact.

The TTL rests on the server's clock. The consume is skew-free because one clock evaluates both sides of the comparison, but if the server's own time is wrong — a bad NTP sync — every TTL shifts with it. Keep the window generous enough that legitimate clients are never caught by a minute of drift.

Takeaway

Replay protection and idempotency look like the same feature until you notice they want opposite answers to a duplicate request. A server-issued single-use nonce supplies the "reject the second one" half: the server mints a random challenge bound to the device and product, stores it unconsumed with a short TTL, and the activation consumes it with one atomic compare-and-set so a replayed packet affects zero rows and fails. Pair it with idempotent activation for honest retries, TLS and request signing for the MITM, and a captured activation call on the wire buys the attacker nothing.

Keyright is a self-hosted .NET licensing system — an issuing service plus SDK — with a free Community Edition. The activation handshake and its storage model are covered in the Keyright docs; for the air-gapped variant where the client generates the nonce, see activating on an air-gapped machine.

Top comments (0)