chunk: Improve constant time comparison for chunks with unequal length

While for most uses the length is fixed and public (e.g. PRF/MAC outputs),
there are a few (e.g. in xauth-generic) that compare variable length
data.

The previous code directly leaked a differing length by short-circuiting
before comparing anything.  While we could limit the comparison by the
minimum length (and call `memeq_const()`), that could still leak the
length because the time will plateau once the secret's length is reached.
Similarly, if the comparison was bound by the longer chunk (would prevent
the use of `memeq_const()`), the length could also be revealed once the
input gets longer than the secret and the time increases.

This changes the semantics of the function by declaring the first
argument the expected/reference secret and the second the variable input.
This strictly makes the function constant-time, bound by the secret's
length.  So the length can't be guessed by providing different input (but
if an attacker can trigger the comparison against different secrets, of
potentially known lengths, it might still be possible).  If the chunks
are known to have the same length, the order doesn't matter.

Callers of this function have been updated accordingly.
This commit is contained in:
Tobias Brunner
2026-07-24 08:47:39 +02:00
parent 11241a8379
commit 459fcabd9e
14 changed files with 48 additions and 26 deletions
@@ -426,7 +426,7 @@ static status_t process_challenge(private_eap_aka_server_t *this,
enumerator->destroy(enumerator);
/* compare received RES against stored XRES */
if (!chunk_equals_const(res, this->xres))
if (!chunk_equals_const(this->xres, res))
{
DBG1(DBG_IKE, "received RES does not match XRES");
return FAILED;
@@ -487,7 +487,7 @@ static status_t process_reauthentication(private_eap_aka_server_t *this,
this->crypto->clear_keys(this->crypto);
return challenge(this, out);
}
if (!chunk_equals_const(counter, this->counter))
if (!chunk_equals_const(this->counter, counter))
{
DBG1(DBG_IKE, "received counter does not match");
return FAILED;
@@ -263,7 +263,7 @@ static status_t process_reauthentication(private_eap_sim_server_t *this,
this->crypto->clear_keys(this->crypto);
return initiate(this, out);
}
if (!chunk_equals_const(counter, this->counter))
if (!chunk_equals_const(this->counter, counter))
{
DBG1(DBG_IKE, "received counter does not match");
return FAILED;