Commit 1768a5a1be for openssl.org
commit 1768a5a1be8895f3cf54d418093c337ea1f3238d
Author: Tomas Mraz <tomas@openssl.foundation>
Date: Fri Jul 10 11:09:09 2026 +0200
Avoid undefined behavior adding or subtracting two BN_zero() values
Reviewed-by: Dmitry Belyavskiy <beldmit@gmail.com>
Reviewed-by: Nikola Pajkovsky <nikolap@openssl.org>
MergeDate: Fri Jul 10 14:54:48 2026
(Merged from https://github.com/openssl/openssl/pull/31916)
diff --git a/crypto/bn/bn_add.c b/crypto/bn/bn_add.c
index 88d77c534f..24151d0e13 100644
--- a/crypto/bn/bn_add.c
+++ b/crypto/bn/bn_add.c
@@ -97,6 +97,8 @@ int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
return 0;
r->top = max;
+ if (max == 0)
+ goto end;
ap = a->d;
bp = b->d;
@@ -116,6 +118,7 @@ int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
*rp = carry;
r->top += (int)carry;
+end:
r->neg = 0;
bn_check_top(r);
return 1;
@@ -143,6 +146,9 @@ int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
if (bn_wexpand(r, max) == NULL)
return 0;
+ if (max == 0)
+ goto end;
+
ap = a->d;
bp = b->d;
rp = r->d;
@@ -162,6 +168,7 @@ int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
while (max && *--rp == 0)
max--;
+end:
r->top = max;
r->neg = 0;
bn_pollute(r);