Skip to content

Commit f2133b8

Browse files
l1kgregkh
authored andcommitted
crypto: ecdsa - Harden against integer overflows in DIV_ROUND_UP()
commit b16510a upstream. Herbert notes that DIV_ROUND_UP() may overflow unnecessarily if an ecdsa implementation's ->key_size() callback returns an unusually large value. Herbert instead suggests (for a division by 8): X / 8 + !!(X & 7) Based on this formula, introduce a generic DIV_ROUND_UP_POW2() macro and use it in lieu of DIV_ROUND_UP() for ->key_size() return values. Additionally, use the macro in ecc_digits_from_bytes(), whose "nbytes" parameter is a ->key_size() return value in some instances, or a user-specified ASN.1 length in the case of ecdsa_get_signature_rs(). Link: https://lore.kernel.org/r/Z3iElsILmoSu6FuC@gondor.apana.org.au/ Signed-off-by: Lukas Wunner <lukas@wunner.de> Signed-off-by: Lukas Wunner <lukas@wunner.de> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
1 parent 59923d5 commit f2133b8

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

crypto/ecc.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ EXPORT_SYMBOL(ecc_get_curve);
7171
void ecc_digits_from_bytes(const u8 *in, unsigned int nbytes,
7272
u64 *out, unsigned int ndigits)
7373
{
74-
int diff = ndigits - DIV_ROUND_UP(nbytes, sizeof(u64));
74+
int diff = ndigits - DIV_ROUND_UP_POW2(nbytes, sizeof(u64));
7575
unsigned int o = nbytes & 7;
7676
__be64 msd = 0;
7777

include/linux/math.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,18 @@
3434
*/
3535
#define round_down(x, y) ((x) & ~__round_mask(x, y))
3636

37+
/**
38+
* DIV_ROUND_UP_POW2 - divide and round up
39+
* @n: numerator
40+
* @d: denominator (must be a power of 2)
41+
*
42+
* Divides @n by @d and rounds up to next multiple of @d (which must be a power
43+
* of 2). Avoids integer overflows that may occur with __KERNEL_DIV_ROUND_UP().
44+
* Performance is roughly equivalent to __KERNEL_DIV_ROUND_UP().
45+
*/
46+
#define DIV_ROUND_UP_POW2(n, d) \
47+
((n) / (d) + !!((n) & ((d) - 1)))
48+
3749
#define DIV_ROUND_UP __KERNEL_DIV_ROUND_UP
3850

3951
#define DIV_ROUND_DOWN_ULL(ll, d) \

0 commit comments

Comments
 (0)