Commit bd9b7d799a for openssl.org
commit bd9b7d799a8705f29ca0c709a316dc35df0d3837
Author: Yasuaki Torimaru <yasuakitorimaru@gmail.com>
Date: Sun Oct 11 16:09:38 2026 +0900
safe_math.h: avoid undefined behaviour in OSSL_SAFE_MATH_MINS/MAXS
OSSL_SAFE_MATH_MINS(type) computed the minimum value of a signed type
as ((type)1 << (sizeof(type) * 8 - 1)), e.g. (int)1 << 31. Shifting
into the sign bit of a signed type is undefined behaviour, and UBSan
reports "left shift of 1 by 31 places cannot be represented in type
'int'" whenever the expression is evaluated.
Rewrite the range macros to compute the maximum first, shifting only
up to the second-to-most-significant bit, and derive the minimum
as -max - 1. The resulting values are identical for int and wider
signed types.
OPENSSL_asc2uni() starts using safe_mul_int()/safe_add_int() in the next
commit, and their overflow paths evaluate these macros.
Fixes: b037e3637a49 "header: add integer overflow helper functions"
Assisted-by: Claude:claude-opus-4-8
Reviewed-by: Eugene Syromiatnikov <esyr@openssl.org>
Reviewed-by: Tom Cosgrove <tom.cosgrove@arm.com>
Merge-date: Thu Nov 19 09:28:51 2026
Merged-from: https://github.com/openssl/openssl/pull/30681
diff --git a/include/internal/safe_math.h b/include/internal/safe_math.h
index dda5cc48f0..d174e07d94 100644
--- a/include/internal/safe_math.h
+++ b/include/internal/safe_math.h
@@ -1,5 +1,5 @@
/*
- * Copyright 2021-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2021-2026 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
@@ -405,8 +405,8 @@
}
/* Calculate ranges of types */
-#define OSSL_SAFE_MATH_MINS(type) ((type)1 << (sizeof(type) * 8 - 1))
-#define OSSL_SAFE_MATH_MAXS(type) (~OSSL_SAFE_MATH_MINS(type))
+#define OSSL_SAFE_MATH_MAXS(type) ((type)((((type)1 << (sizeof(type) * 8 - 2)) - 1) * 2 + 1))
+#define OSSL_SAFE_MATH_MINS(type) (-OSSL_SAFE_MATH_MAXS(type) - 1)
#define OSSL_SAFE_MATH_MAXU(type) (~(type)0)
/*