[PATCH] netfilter: nf_nat: fix unsigned range_size underflow for ICMP and GRE when max < min

Hui Peng posted 1 patch 4 days, 23 hours ago
[PATCH] netfilter: nf_nat: fix unsigned range_size underflow for ICMP and GRE when max < min
Posted by Hui Peng 4 days, 23 hours ago
In nf_nat_l4proto_unique_tuple(), when NF_NAT_RANGE_PROTO_SPECIFIED is set
for IPPROTO_ICMP, IPPROTO_ICMPV6, or IPPROTO_GRE with max < min,
computing max - min + 1 in a u16 range_size underflows (and wraps to 0 when
min == max + 1, causing a divide-by-zero in % range_size for GRE). Handle
max < min gracefully by swapping min and max for ICMP/ICMPv6 and clamping
range_size to 1 for GRE, matching the TCP/UDP/SCTP path.

Fixes: 203f2e78200c ("netfilter: nat: remove l4proto->unique_tuple")
Assisted-by: LLM
Signed-off-by: Hui Peng <benquike@gmail.com>
---
diff --git a/net/netfilter/nf_nat_core.c b/net/netfilter/nf_nat_core.c
index a4858c2b2d65..83f4eb63a584 100644
--- a/net/netfilter/nf_nat_core.c
+++ b/net/netfilter/nf_nat_core.c
@@ -575,8 +575,10 @@ static void nf_nat_l4proto_unique_tuple(struct nf_conntrack_tuple *tuple,
 			range_size = 65536;
 		} else {
 			min = ntohs(range->min_proto.icmp.id);
-			range_size = ntohs(range->max_proto.icmp.id) -
-				     ntohs(range->min_proto.icmp.id) + 1;
+			max = ntohs(range->max_proto.icmp.id);
+			if (unlikely(max < min))
+				swap(max, min);
+			range_size = max - min + 1;
 		}
 		goto find_free_id;
 #if IS_ENABLED(CONFIG_NF_CT_PROTO_GRE)
@@ -596,7 +598,11 @@ static void nf_nat_l4proto_unique_tuple(struct nf_conntrack_tuple *tuple,
 			range_size = 65535;
 		} else {
 			min = ntohs(range->min_proto.gre.key);
-			range_size = ntohs(range->max_proto.gre.key) - min + 1;
+			max = ntohs(range->max_proto.gre.key);
+			if (max < min)
+				range_size = 1;
+			else
+				range_size = max - min + 1;
 		}
 		goto find_free_id;
 #endif