Index | Thread | Search

From:
Kenjiro Nakayama <nakayamakenjiro@gmail.com>
Subject:
[PATCH] LibreSSL: avoid undefined behavior from applying offset to NULL pointers
To:
tech@openbsd.org
Cc:
nakayamakenjiro@gmail.com
Date:
Sat, 12 Apr 2025 12:14:02 +0900

Download raw body.

Thread
In bn_add() and bn_sub(), applying a zero offset (e.g. `r += min_len`)
to a NULL pointer is undefined behavior in C, even if the result is not
dereferenced.

To prevent this, add explicit NULL checks before advancing pointers a,
b, and r. This avoids runtime errors reported by UndefinedBehaviorSanitizer:

  $ ./tests/apitest
  /dev/portable/crypto/bn/bn_add.c:125:5: runtime error: applying zero
  offset to null pointer

These cases typically occur when min_len is zero, but sanitizers still
flag such code as UB due to pointer arithmetic on NULL.

Signed-off-by: Kenjiro Nakayama <nakayamakenjiro@gmail.com>
---
 src/lib/libcrypto/bn/bn_add.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git src/lib/libcrypto/bn/bn_add.c src/lib/libcrypto/bn/bn_add.c
index 86768a312..b199e12cc 100644
--- src/lib/libcrypto/bn/bn_add.c
+++ src/lib/libcrypto/bn/bn_add.c
@@ -121,7 +121,8 @@ bn_add(BN_ULONG *r, int r_len, const BN_ULONG *a, int a_len, const BN_ULONG *b,
 	carry = bn_add_words(r, a, b, min_len);
 
 	a += min_len;
-	b += min_len;
+	if (b != NULL)
+		b += min_len;
 	r += min_len;
 
 	/* XXX - consider doing four at a time to match bn_add_words(). */
@@ -201,9 +202,11 @@ bn_sub(BN_ULONG *r, int r_len, const BN_ULONG *a, int a_len, const BN_ULONG *b,
 
 	borrow = bn_sub_words(r, a, b, min_len);
 
-	a += min_len;
+	if (a != NULL)
+		a += min_len;
 	b += min_len;
-	r += min_len;
+	if (r != NULL)
+		r += min_len;
 
 	/* XXX - consider doing four at a time to match bn_sub_words. */
 	while (diff_len < 0) {
-- 
2.39.5 (Apple Git-154)