Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bn_assert_fits_in_bytes for big-endian #1258

Merged
merged 1 commit into from
Nov 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions crypto/fipsmodule/bn/bytes.c
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,31 @@ static int fits_in_bytes(const BN_ULONG *words, size_t num_words,
return mask == 0;
}

// Asserts that the BIGNUM can be represented within |num| bytes.
// The logic is consistent with `fits_in_bytes` but assertions will fail when false.
void bn_assert_fits_in_bytes(const BIGNUM *bn, size_t num) {
const uint8_t *bytes = (const uint8_t *)bn->d;
size_t tot_bytes = bn->width * sizeof(BN_ULONG);
justsmth marked this conversation as resolved.
Show resolved Hide resolved
if (tot_bytes > num) {
CONSTTIME_DECLASSIFY(bytes + num, tot_bytes - num);
#ifdef OPENSSL_BIG_ENDIAN
for (int i = num / BN_BYTES; i < bn->width; i++) {
BN_ULONG word = bn->d[i];
for (size_t j = 0; j < BN_BYTES; j++) {
if ((i * BN_BYTES) + j < num) {
// For the first word we don't need to check any bytes shorter than len
continue;
} else {
uint8_t byte = (word >> (j * 8)) & 0xff;
assert(byte == 0);
}
}
}
#else
for (size_t i = num; i < tot_bytes; i++) {
assert(bytes[i] == 0);
}
#endif
(void)bytes;
}
}
Expand Down
Loading