Saltar al contenido ForoHackers

Constant-time comparison: why memcmp is the wrong tool for secrets

CriptografíaSeguridad del hardwareProgramación segura
#1128 · sp00ky_s1d3ch4nn3l · · Denunciar

Here is the side channel I promised. Compare an authentication tag, a token, or a password hash with memcmp and you have a timing leak:

// leaks: returns at the first mismatch
if (memcmp(received_tag, expected_tag, 32) == 0) { /* ok */ }

memcmp is allowed to stop at the first different byte, and usually does. So a tag that matches the first byte takes slightly longer to reject than one that does not. Over a quiet network that difference is tiny, but it is statistical: with enough samples the noise averages out. Researchers have shown this on local networks and on shared machines. In my own lab I can see it with two processes on the same board and a cycle counter.

The fix is to touch every byte, always, and combine the result without branching:

#include <stddef.h>
#include <stdint.h>

int ct_equal(const uint8_t *a, const uint8_t *b, size_t n) {
    uint8_t diff = 0;
    for (size_t i = 0; i < n; i++)
        diff |= a[i] ^ b[i];
    return diff == 0;
}

Three caveats that matter more than the snippet:

  1. "Constant time" is a property of the machine code, not your source. An optimising compiler is allowed to turn a clever loop back into an early exit. Do not hand-roll it in production.
  2. Use the library function: CRYPTO_memcmp, sodium_memcmp, hmac.compare_digest in Python, crypto.timingSafeEqual in Node. They exist exactly for this and were reviewed by people who care.
  3. The secret-dependent length also leaks. Compare fixed-size values (hash both sides first if you must compare variable-length input).

Being correct on paper was never the problem. The problem is the clock on the wall.

#1843 · ElQueCompilaEnDomingo · · Denunciar

Ojo con lo del compilador: a mí me pasó con un -O3 que convirtió un bucle de comparación "sin ramas" en uno con salida anticipada, porque el optimizador demostró que el resultado era el mismo. Mira el ensamblador que genera tu compilador para esa función, o mejor, usa la de la biblioteca.

#1844 · n0p_sl3d · · Denunciar

Perfect companion to the CTF-style "guess the flag byte by byte" exercises: on your own local challenge, the lesson is that the fix is not "add a random delay" (statistics beat that) but "do the same work every time".

#1845 · ChistorraOverflow · · Denunciar

Y para quien trabaje en web: la comparación de tokens de sesión, de firmas de webhooks y de HMAC se hace con la función de tiempo constante de tu lenguaje, nunca con ==. Es de los fallos más fáciles de arreglar y más difíciles de ver en una revisión de código.

#1846 · legacy_cobol_whisperer · · Denunciar

On the mainframe side, we compared PINs and passwords with a routine that always walked the full field. Nobody called it "constant time" then. It was just "the check that does not get clever".

Inicia sesión o únete para responder.