[PATCH 12/82] ipv4: Silence intentional wrapping addition

From: Kees Cook
Date: Mon Jan 22 2024 - 20:15:27 EST


The overflow sanitizer quickly noticed what appears to have been an old
sore spot involving intended wrap around:

[ 22.192362] ------------[ cut here ]------------
[ 22.193329] UBSAN: signed-integer-overflow in ../arch/x86/include/asm/atomic.h:85:11
[ 22.194844] 1469769800 + 1671667352 cannot be represented in type 'int'
[ 22.195975] CPU: 2 PID: 2260 Comm: nmbd Not tainted 6.7.0 #1
[ 22.196927] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 0.0.0 02/06/2015
[ 22.198231] Call Trace:
[ 22.198641] <TASK>
[ 22.198641] dump_stack_lvl+0x64/0x80
[ 22.199533] handle_overflow+0x152/0x1a0
[ 22.200382] __ip_select_ident+0xe3/0x100

Explicitly perform a wrapping addition to solve for the needed
-fno-strict-overflow behavior but still allow the sanitizers to operate
correctly.

To see the (unchanged) assembly results more clearly, see:
https://godbolt.org/z/EhYhz6zTT

Cc: Jakub Kicinski <kuba@xxxxxxxxxx>
Cc: "David S. Miller" <davem@xxxxxxxxxxxxx>
Cc: David Ahern <dsahern@xxxxxxxxxx>
Cc: Eric Dumazet <edumazet@xxxxxxxxxx>
Cc: Paolo Abeni <pabeni@xxxxxxxxxx>
Cc: netdev@xxxxxxxxxxxxxxx
Signed-off-by: Kees Cook <keescook@xxxxxxxxxxxx>
---
net/ipv4/route.c | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/net/ipv4/route.c b/net/ipv4/route.c
index 16615d107cf0..c52e85b06fe7 100644
--- a/net/ipv4/route.c
+++ b/net/ipv4/route.c
@@ -473,11 +473,11 @@ static u32 ip_idents_reserve(u32 hash, int segs)
if (old != now && cmpxchg(p_tstamp, old, now) == old)
delta = get_random_u32_below(now - old);

- /* If UBSAN reports an error there, please make sure your compiler
- * supports -fno-strict-overflow before reporting it that was a bug
- * in UBSAN, and it has been fixed in GCC-8.
+ /* If UBSAN reports an error there, please make sure your arch's
+ * atomic_add_return() implementation has been annotated with
+ * __signed_wrap.
*/
- return atomic_add_return(segs + delta, p_id) - segs;
+ return atomic_add_return(add_wrap(segs, delta), p_id) - segs;
}

void __ip_select_ident(struct net *net, struct iphdr *iph, int segs)
--
2.34.1