Skip to contentSkip to conversation

net: avoid stack canaries in TCP/IPv4 fast paths

PATCH New Xuanqiang Luo 2 participants 9 messages Nov 24 – Nov 25

Subsystems (9)
lore
Share & tools
lore
#0 lore raw

cover net: avoid stack canaries in TCP/IPv4 fast paths

From: Xuanqiang Luo <[email protected]>

With CONFIG_STACKPROTECTOR_STRONG=y, a function that has a local array or passes the address of one of its locals to another function needs a stack canary. The canary is set up and checked on every call, also when the local is only used on a path that almost never runs.

This series removes the canary from functions of the TCP/IPv4 fast paths, by returning results by value, by using storage that is not on the stack, or by not calling a function that has nothing to do.

Patch 1 returns the two mptcp_space() values in a structure, so that __tcp_select_window() no longer needs a canary.

Patch 2 changes ip_neigh_gw4() to take a pointer to the address, like ip_neigh_gw6(), so that ip_finish_output2() no longer needs a canary.

Patch 3 uses pskb_may_pull() in icmp_filter(), so that raw_local_deliver() no longer needs a canary.

Patch 4 turns skb_try_coalesce() into an inline wrapper over a function returning its results by value, so that its callers no longer need a canary because of it.

Patch 5 returns the result of the TCP receive coalescing by value, so that tcp_rcv_established() and tcp_data_queue() no longer need a canary.

Patch 6 calls bpf_skops_write_hdr_opt(), which needs a canary, only if a BPF program reserved room for TCP options.

The bloat-o-meter numbers are from gcc 16.2 on x86_64. The functions named in patches 1 to 5 also lose their canary with clang 23.1.6 on x86_64, with and without ThinLTO, and on arm64.

Xuanqiang Luo (6):
tcp: avoid a stack canary in __tcp_select_window()
ipv4: avoid a stack canary in ip_finish_output2()
ipv4: raw: do not use skb_header_pointer() in icmp_filter()
net: avoid stack canaries in skb_try_coalesce() callers
tcp: avoid a stack canary in tcp_rcv_established()
tcp: do not call bpf_skops_write_hdr_opt() unless needed

 include/linux/filter.h           |  2 +-
 include/linux/skbuff.h           | 35 ++++++++++-
 include/net/mptcp.h              | 13 ++++-
 include/net/route.h              | 16 +++---
 net/core/filter.c                |  2 +-
 net/core/skbuff.c                | 50 ++++++++--------
 net/ipv4/raw.c                   | 25 ++++----
 net/ipv4/route.c                 | 15 +++--
 net/ipv4/tcp_input.c             | 99 +++++++++++++++++---------------
 net/ipv4/tcp_output.c            | 25 ++++----
 net/mptcp/subflow.c              |  9 ++-
 net/netfilter/nf_flow_table_ip.c |  4 +-
 12 files changed, 178 insertions(+), 117 deletions(-)

base-commit: a4c450594f5d1dc0fc4daacfb95d40554d99dead

Signature · 1 line
2.43.0
#1 lore raw

PATCH 1/6 tcp: avoid a stack canary in __tcp_select_window()

From: Xuanqiang Luo <[email protected]>

__tcp_select_window() passes the address of two locals to mptcp_space(), but only for MPTCP subflows.

With CONFIG_STACKPROTECTOR_STRONG=y, this forces a stack canary in __tcp_select_window() for all TCP sockets.

Return both values in a small structure instead.

While we are at it, do not compute tcp_space() and tcp_full_space() for MPTCP subflows, their values were overwritten.

$ scripts/bloat-o-meter -t vmlinux.old vmlinux.new
add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-51 (-51)
Function                                     old     new   delta
mptcp_space                                   87      86      -1
tcp_connect                                 5892    5876     -16
__tcp_select_window                          706     672     -34
Total: Before=24068967, After=24068916, chg -0.00%
---
 include/net/mptcp.h   | 13 +++++++++++--
 net/ipv4/tcp_output.c | 14 ++++++++++----
 net/mptcp/subflow.c   |  9 ++++++---
 3 files changed, 27 insertions(+), 9 deletions(-)
include/net/mptcp.h +11 -2
index ad7005b574bb..95ebcfd5950d 100644
@@ -126,6 +126,12 @@ struct mptcp_pm_ops {
 	void (*release)(struct mptcp_sock *msk);
 } ____cacheline_aligned_in_smp;
 
+/* Result of mptcp_space(). */
+struct mptcp_space_info {
+	int space;
+	int full_space;
+};
+
 #ifdef CONFIG_MPTCP
 void mptcp_init(void);
 
@@ -144,7 +150,7 @@ static inline bool rsk_drop_req(const struct request_sock *req)
 	return tcp_rsk(req)->is_mptcp && tcp_rsk(req)->drop_req;
 }
 
-void mptcp_space(const struct sock *ssk, int *space, int *full_space);
+struct mptcp_space_info mptcp_space(const struct sock *ssk);
 bool mptcp_syn_options(struct sock *sk, const struct sk_buff *skb,
 		       unsigned int *size, struct mptcp_out_options *opts);
 bool mptcp_synack_options(const struct request_sock *req, unsigned int *size,
@@ -291,7 +297,10 @@ static inline bool mptcp_skb_can_collapse(const struct sk_buff *to,
 	return true;
 }
 
-static inline void mptcp_space(const struct sock *ssk, int *s, int *fs) { }
+static inline struct mptcp_space_info mptcp_space(const struct sock *ssk)
+{
+	return (struct mptcp_space_info){ };
+}
 static inline void mptcp_seq_show(struct seq_file *seq) { }
 
 static inline int mptcp_subflow_init_cookie_req(struct request_sock *req,
net/ipv4/tcp_output.c +10 -4
index 08d0d4a639fe..c2022fc9ad52 100644
@@ -3391,12 +3391,18 @@ u32 __tcp_select_window(struct sock *sk)
 	 * fluctuations.  --SAW  1998/11/1
 	 */
 	int mss = icsk->icsk_ack.rcv_mss;
-	int free_space = tcp_space(sk);
-	int allowed_space = tcp_full_space(sk);
+	int free_space, allowed_space;
 	int full_space, window;
 
-	if (sk_is_mptcp(sk))
-		mptcp_space(sk, &free_space, &allowed_space);
+	if (sk_is_mptcp(sk)) {
+		struct mptcp_space_info info = mptcp_space(sk);
+
+		free_space = info.space;
+		allowed_space = info.full_space;
+	} else {
+		free_space = tcp_space(sk);
+		allowed_space = tcp_full_space(sk);
+	}
 
 	full_space = min_t(int, tp->window_clamp, allowed_space);
 
net/mptcp/subflow.c +6 -3
index 00677fb3efcd..d22ee068f599 100644
@@ -1532,13 +1532,16 @@ bool mptcp_subflow_data_available(struct sock *sk)
  * as far as mptcp peer is concerned that data is still inflight.
  * DSS ACK is updated when skb is moved to the mptcp rx queue.
  */
-void mptcp_space(const struct sock *ssk, int *space, int *full_space)
+struct mptcp_space_info mptcp_space(const struct sock *ssk)
 {
 	const struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
 	const struct sock *sk = subflow->conn;
+	struct mptcp_space_info info;
 
-	*space = __mptcp_space(sk);
-	*full_space = mptcp_win_from_space(sk, READ_ONCE(sk->sk_rcvbuf));
+	info.space = __mptcp_space(sk);
+	info.full_space = mptcp_win_from_space(sk, READ_ONCE(sk->sk_rcvbuf));
+
+	return info;
 }
 
 static void subflow_error_report(struct sock *ssk)
Signature · 1 line
2.43.0
#2 lore raw

PATCH 2/6 ipv4: avoid a stack canary in ip_finish_output2()

In reply to Xuanqiang Luo

From: Xuanqiang Luo <[email protected]>

ip_neigh_gw4() passes the address of its by-value @daddr argument to __neigh_create() when the lockless lookup finds no neighbour.

Once inlined, this forces a stack canary (CONFIG_STACKPROTECTOR_STRONG=y) into its callers, ip_finish_output2() being the one in the transmit path of every IPv4 packet, although creating a neighbour is rare compared to finding one.

Change ip_neigh_gw4() to take a pointer to the address, like ip_neigh_gw6(). All callers have the address in the route, in the packet or in another object that is not on their stack.

Call it only once in ip_neigh_for_gw() and ipv4_dst_neigh_lookup(), so that the lookup and the creation are no longer inlined twice there.

Change the type of ipv4_nh in struct bpf_nh_params to __be32, since its address is now given to ip_neigh_gw4().

Note that skb_do_redirect() and nf_flow_offload_ip_hook() still need a canary for other reasons.

$ scripts/bloat-o-meter -t vmlinux.old vmlinux.new
add/remove: 0/0 grow/shrink: 1/5 up/down: 3/-846 (-843)
Function                                     old     new   delta
nf_flow_offload_ip_hook                     2065    2068      +3
ip_do_fragment                              1441    1425     -16
ipv4_dst_neigh_lookup                        684     587     -97
skb_do_redirect                             4382    4222    -160
vrf_finish_output                           1614    1345    -269
ip_finish_output2                           1775    1471    -304
Total: Before=24068916, After=24068073, chg -0.00%
---
 include/linux/filter.h           |  2 +-
 include/net/route.h              | 16 ++++++++--------
 net/core/filter.c                |  2 +-
 net/ipv4/route.c                 | 15 +++++++--------
 net/netfilter/nf_flow_table_ip.c |  4 +++-
 5 files changed, 20 insertions(+), 19 deletions(-)
include/linux/filter.h +1 -1
index 4f0cd67caccb..e258ba4741af 100644
@@ -871,7 +871,7 @@ struct bpf_skb_data_end {
 struct bpf_nh_params {
 	u32 nh_family;
 	union {
-		u32 ipv4_nh;
+		__be32 ipv4_nh;
 		struct in6_addr ipv6_nh;
 	};
 };
include/net/route.h +8 -8
index 3fccd31eb74d..1571e1c6082c 100644
@@ -406,15 +406,15 @@ static inline int ip4_dst_hoplimit(const struct dst_entry *dst)
 }
 
 static inline struct neighbour *ip_neigh_gw4(struct net_device *dev,
-					     __be32 daddr)
+					     const __be32 *daddr)
 {
 	struct neighbour *neigh;
 
-	neigh = __ipv4_neigh_lookup_noref(dev, (__force u32)daddr);
+	neigh = __ipv4_neigh_lookup_noref(dev, (__force u32)*daddr);
 	if (unlikely(!neigh)) {
 		struct neigh_table *tbl = arp_table(dev_net(dev));
 
-		neigh = __neigh_create(tbl, &daddr, dev, false);
+		neigh = __neigh_create(tbl, daddr, dev, false);
 	}
 
 	return neigh;
@@ -425,17 +425,17 @@ static inline struct neighbour *ip_neigh_for_gw(struct rtable *rt,
 						bool *is_v6gw)
 {
 	struct net_device *dev = rt->dst.dev;
-	struct neighbour *neigh;
+	const __be32 *daddr;
 
 	if (likely(rt->rt_gw_family == AF_INET)) {
-		neigh = ip_neigh_gw4(dev, rt->rt_gw4);
+		daddr = &rt->rt_gw4;
 	} else if (rt->rt_gw_family == AF_INET6) {
-		neigh = ip_neigh_gw6(dev, &rt->rt_gw6);
 		*is_v6gw = true;
+		return ip_neigh_gw6(dev, &rt->rt_gw6);
 	} else {
-		neigh = ip_neigh_gw4(dev, ip_hdr(skb)->daddr);
+		daddr = &ip_hdr(skb)->daddr;
 	}
-	return neigh;
+	return ip_neigh_gw4(dev, daddr);
 }
 
 #endif	/* _ROUTE_H */
net/core/filter.c +1 -1
index f42ecfb5841f..8ee023c87c24 100644
@@ -2376,7 +2376,7 @@ static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb,
 		neigh = ip_neigh_gw6(dev, &nh->ipv6_nh);
 		is_v6gw = true;
 	} else if (nh->nh_family == AF_INET) {
-		neigh = ip_neigh_gw4(dev, nh->ipv4_nh);
+		neigh = ip_neigh_gw4(dev, &nh->ipv4_nh);
 	} else {
 		rcu_read_unlock();
 		goto out_drop;
net/ipv4/route.c +7 -8
index d0930ae4c5ae..585c10743e1b 100644
@@ -419,15 +419,14 @@ static struct neighbour *ipv4_dst_neigh_lookup(const struct dst_entry *dst,
 
 	rcu_read_lock();
 	dev = dst_dev_rcu(dst);
-	if (likely(rt->rt_gw_family == AF_INET)) {
-		n = ip_neigh_gw4(dev, rt->rt_gw4);
-	} else if (rt->rt_gw_family == AF_INET6) {
+	if (unlikely(rt->rt_gw_family == AF_INET6)) {
 		n = ip_neigh_gw6(dev, &rt->rt_gw6);
-        } else {
-		__be32 pkey;
-
-		pkey = skb ? ip_hdr(skb)->daddr : *((__be32 *) daddr);
-		n = ip_neigh_gw4(dev, pkey);
+	} else {
+		if (likely(rt->rt_gw_family == AF_INET))
+			daddr = &rt->rt_gw4;
+		else if (skb)
+			daddr = &ip_hdr(skb)->daddr;
+		n = ip_neigh_gw4(dev, daddr);
 	}
 
 	if (!IS_ERR(n) && !refcount_inc_not_zero(&n->refcnt))
net/netfilter/nf_flow_table_ip.c +3 -1
index 78bba416dd5b..19f62005b517 100644
@@ -872,7 +872,9 @@ static int nf_flow_queue_xmit4(struct sk_buff *skb,
 			flow_offload_teardown(flow);
 			return NF_DROP;
 		}
-		neigh = ip_neigh_gw4(rt->dst.dev, rt_nexthop(rt, ip_addr->ip));
+		neigh = ip_neigh_gw4(rt->dst.dev,
+				     rt->rt_gw_family == AF_INET ?
+				     &rt->rt_gw4 : &ip_addr->ip);
 		if (IS_ERR(neigh)) {
 			flow_offload_teardown(flow);
 			return NF_DROP;
Signature · 1 line
2.43.0
#3 lore raw

Re: [PATCH net-next v1 2/6] ipv4: avoid a stack canary in ip_finish_output2()

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] bpf: device mismatch in…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] bpf: device mismatch in bpf_out_neigh_v4() on RTN_LOCAL routes
[1]
--

commit ca3d30f8ff839a5ead3ac3b6137813b8e1486837
Author: Xuanqiang Luo <[email protected]>

ipv4: avoid a stack canary in ip_finish_output2()

This commit changes ip_neigh_gw4() to take a pointer to the IPv4 address instead of passing it by value, avoiding a stack canary in callers such as ip_finish_output2() and deduplicating inlined calls in ip_neigh_for_gw() and ipv4_dst_neigh_lookup().

[ ... ]

Quoted 4 lines
include/net/route.h +0 -0
index 3fccd31eb74df..1571e1c6082cc 100644

[ ... ]

Quoted 28 lines
include/net/route.h +5 -5
@@ -425,17 +425,17 @@ static inline struct neighbour *ip_neigh_for_gw(struct rtable *rt,
 						bool *is_v6gw)
 {
 	struct net_device *dev = rt->dst.dev;
-	struct neighbour *neigh;
+	const __be32 *daddr;
 
 	if (likely(rt->rt_gw_family == AF_INET)) {
-		neigh = ip_neigh_gw4(dev, rt->rt_gw4);
+		daddr = &rt->rt_gw4;
 	} else if (rt->rt_gw_family == AF_INET6) {
-		neigh = ip_neigh_gw6(dev, &rt->rt_gw6);
 		*is_v6gw = true;
+		return ip_neigh_gw6(dev, &rt->rt_gw6);
 	} else {
-		neigh = ip_neigh_gw4(dev, ip_hdr(skb)->daddr);
+		daddr = &ip_hdr(skb)->daddr;
 	}
-	return neigh;
+	return ip_neigh_gw4(dev, daddr);
 }
 
 #endif	/* _ROUTE_H */
net/core/filter.c +0 -0
index f42ecfb5841f9..8ee023c87c243 100644

net/core/filter.c static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb, · line 2382

Quoted 8 lines
net/core/filter.c +1 -1
@@ -2376,7 +2376,7 @@ static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb,
 		neigh = ip_neigh_gw6(dev, &nh->ipv6_nh);
 		is_v6gw = true;
 	} else if (nh->nh_family == AF_INET) {
-		neigh = ip_neigh_gw4(dev, nh->ipv4_nh);
+		neigh = ip_neigh_gw4(dev, &nh->ipv4_nh);
 	} else {
 		rcu_read_unlock();
 		goto out_drop;

[Severity: High]
This problem wasn't introduced by this patch, but can bpf_out_neigh_v4() resolve the neighbour on the wrong device when nh is NULL [1]?

When __bpf_redirect_neigh_v4() resolves an RTN_LOCAL route via ip_route_output_flow(), rt->dst.dev is set to net->loopback_dev (or the VRF device) rather than the target redirect device dev:

net/core/filter.c:bpf_out_neigh_v4() {
	...
	skb->dev = dev;
	skb_clear_tstamp(skb);

	if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
		skb = skb_expand_head(skb, hh_len);
		if (!skb)
			return -ENOMEM;
	}

	rcu_read_lock();
	if (!nh) {
		struct rtable *rt = skb_rtable(skb);

		neigh = ip_neigh_for_gw(rt, skb, &is_v6gw);
	...
}

Because ip_neigh_for_gw() uses rt->dst.dev instead of dev, neigh_output() is invoked with a loopback_dev neighbour (which uses eth_header_ops) while skb->dev points to dev. If dev is an L3 device where dev->header_ops is NULL (such as a tun interface), bpf_out_neigh_v4() skips skb_expand_head(), and neigh_output() pushes an Ethernet header without sufficient headroom, triggering skb_under_panic().

[1] https://sashiko.dev/#/bug/linux-26626829-3abf-4baa-b906-b783eeb1b107

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#4 lore raw

PATCH 3/6 ipv4: raw: do not use skb_header_pointer() in icmp_filter()

In reply to Xuanqiang Luo

From: Xuanqiang Luo <[email protected]>

raw_local_deliver() is called for every IPv4 packet delivered locally.

icmp_filter() passes the address of a local struct icmphdr to skb_header_pointer(). Once inlined, this forces a stack canary (CONFIG_STACKPROTECTOR_STRONG=y) into raw_local_deliver(), although only ICMP packets matching a raw socket need the filter.

Prefer pskb_may_pull(), as commit a14d93179045 ("ipv6: do not use skb_header_pointer() in icmpv6_filter()") did for IPv6.

skb->data already points to the transport header here.

skb->head can change, reload iph pointer in raw_v4_input().

$ scripts/bloat-o-meter -t vmlinux.old vmlinux.new
add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-95 (-95)
Function                                     old     new   delta
raw_local_deliver                            648     553     -95
Total: Before=24068073, After=24067978, chg -0.00%
---
 net/ipv4/raw.c | 25 ++++++++++++++-----------
 1 file changed, 14 insertions(+), 11 deletions(-)
net/ipv4/raw.c +14 -11
index f33a9dfc5309..f72163699040 100644
@@ -140,16 +140,14 @@ EXPORT_SYMBOL_GPL(raw_v4_match);
  *	0 - deliver
  *	1 - block
  */
-static int icmp_filter(const struct sock *sk, const struct sk_buff *skb)
+static int icmp_filter(const struct sock *sk, struct sk_buff *skb)
 {
-	struct icmphdr _hdr;
 	const struct icmphdr *hdr;
 
-	hdr = skb_header_pointer(skb, skb_transport_offset(skb),
-				 sizeof(_hdr), &_hdr);
-	if (!hdr)
+	if (!pskb_may_pull(skb, sizeof(*hdr)))
 		return 1;
 
+	hdr = (const struct icmphdr *)skb->data;
 	if (hdr->type < 32) {
 		__u32 data = raw_sk(sk)->filter.data;
 
@@ -166,10 +164,10 @@ static int icmp_filter(const struct sock *sk, const struct sk_buff *skb)
  * RFC 1122: SHOULD pass TOS value up to the transport layer.
  * -> It does. And not only TOS, but all IP header.
  */
-static int raw_v4_input(struct net *net, struct sk_buff *skb,
-			const struct iphdr *iph, int hash)
+static int raw_v4_input(struct net *net, struct sk_buff *skb, int hash)
 {
 	int sdif = inet_sdif(skb);
+	const struct iphdr *iph;
 	struct hlist_head *hlist;
 	int dif = inet_iif(skb);
 	int delivered = 0;
@@ -178,13 +176,19 @@ static int raw_v4_input(struct net *net, struct sk_buff *skb,
 	hlist = &raw_v4_hashinfo.ht[hash];
 	rcu_read_lock();
 	sk_for_each_rcu(sk, hlist) {
+		iph = ip_hdr(skb);
 		if (!raw_v4_match(net, sk, iph->protocol,
 				  iph->saddr, iph->daddr, dif, sdif))
 			continue;
 
 		delivered = 1;
-		if ((iph->protocol != IPPROTO_ICMP || !icmp_filter(sk, skb)) &&
-		    ip_mc_sf_allow(sk, iph->daddr, iph->saddr,
+		if (iph->protocol == IPPROTO_ICMP) {
+			if (icmp_filter(sk, skb))
+				continue;
+			/* icmp_filter() might have changed skb->head. */
+			iph = ip_hdr(skb);
+		}
+		if (ip_mc_sf_allow(sk, iph->daddr, iph->saddr,
 				   skb->dev->ifindex, sdif)) {
 			struct sk_buff *clone;
 
@@ -208,8 +212,7 @@ int raw_local_deliver(struct sk_buff *skb, int protocol)
 {
 	struct net *net = dev_net(skb->dev);
 
-	return raw_v4_input(net, skb, ip_hdr(skb),
-			    raw_hashfunc(net, protocol));
+	return raw_v4_input(net, skb, raw_hashfunc(net, protocol));
 }
 
 static void raw_err(struct sock *sk, struct sk_buff *skb, u32 info)
Signature · 1 line
2.43.0
#5 lore raw

PATCH 4/6 net: avoid stack canaries in skb_try_coalesce() callers

In reply to Xuanqiang Luo

From: Xuanqiang Luo <[email protected]>

skb_try_coalesce() returns the stolen head indication and the truesize delta through pointers to locals of its callers.

With CONFIG_STACKPROTECTOR_STRONG=y, this forces a stack canary in all of them, some are in TCP receive fast paths.

Rename it to __skb_try_coalesce(), and return its results by value in a small structure.

skb_try_coalesce() is now an inline wrapper, callers do not change.

A successful merge never has a negative delta, so that a negative value can be used to report a failure.

$ scripts/bloat-o-meter -t vmlinux.old vmlinux.new
add/remove: 2/2 grow/shrink: 1/8 up/down: 1303/-1677 (-374)
Function                                     old     new   delta
__skb_try_coalesce                             -    1255   +1255
tcp_data_queue                              4393    4425     +32
__pfx___skb_try_coalesce                       -      16     +16
mptcp_recvmsg                               2108    2092     -16
alloc_skb_with_frags                         534     518     -16
__pfx_skb_try_coalesce                        16       -     -16
tcp_try_coalesce                             386     359     -27
skb_copy_ubufs                              1645    1613     -32
__mptcp_move_skbs_from_subflow              1215    1167     -48
tcp_add_backlog                             1576    1527     -49
mptcp_try_coalesce                           235     168     -67
inet_frag_reasm_finish                       672     598     -74
skb_try_coalesce                            1332       -   -1332
Total: Before=24067978, After=24067604, chg -0.00%
---
 include/linux/skbuff.h | 35 +++++++++++++++++++++++++++--
 net/core/skbuff.c      | 50 +++++++++++++++++++++++-------------------
 2 files changed, 60 insertions(+), 25 deletions(-)
include/linux/skbuff.h +33 -2
index 55ab6392301a..bbdf64811aed 100644
@@ -1370,8 +1370,39 @@ void __consume_stateless_skb(struct sk_buff *skb);
 void  __kfree_skb(struct sk_buff *skb);
 
 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen);
-bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
-		      bool *fragstolen, int *delta_truesize);
+
+/* Result of __skb_try_coalesce(). */
+struct skb_coalesce_res {
+	int	delta_truesize;	/* negative if not coalesced */
+	bool	fragstolen;
+};
+
+struct skb_coalesce_res __skb_try_coalesce(struct sk_buff *to,
+					   struct sk_buff *from);
+
+/**
+ * skb_try_coalesce - try to merge skb to prior one
+ * @to: prior buffer
+ * @from: buffer to add
+ * @fragstolen: pointer to boolean
+ * @delta_truesize: how much more was allocated than was requested
+ *
+ * Return: true if @from was merged into @to, false otherwise.
+ */
+static __always_inline bool skb_try_coalesce(struct sk_buff *to,
+					     struct sk_buff *from,
+					     bool *fragstolen,
+					     int *delta_truesize)
+{
+	struct skb_coalesce_res res = __skb_try_coalesce(to, from);
+
+	*fragstolen = res.fragstolen;
+	if (res.delta_truesize < 0)
+		return false;
+
+	*delta_truesize = res.delta_truesize;
+	return true;
+}
 
 struct sk_buff *__alloc_skb(unsigned int size, gfp_t priority, int flags,
 			    int node);
net/core/skbuff.c +27 -23

122 lines not on this page · raw message

Signature · 1 line
2.43.0
#6 lore raw

PATCH 5/6 tcp: avoid a stack canary in tcp_rcv_established()

In reply to Xuanqiang Luo

From: Xuanqiang Luo <[email protected]>

tcp_rcv_established() passes the address of a local boolean to tcp_queue_rcv(), to know if skb->head was stolen while coalescing.

With CONFIG_STACKPROTECTOR_STRONG=y, this forces a stack canary in tcp_rcv_established(), which is paid for every received packet, including pure ACKs. tcp_data_queue() has the same issue.

Change tcp_try_coalesce(), tcp_ooo_try_coalesce() and tcp_queue_rcv() to return this information by value, in a new enum tcp_eaten.

$ scripts/bloat-o-meter -t vmlinux.old vmlinux.new
add/remove: 0/0 grow/shrink: 1/5 up/down: 16/-215 (-199)
Function                                     old     new   delta
tcp_validate_incoming                       2487    2503     +16
tcp_send_rcvq                                502     490     -12
tcp_try_coalesce                             359     336     -23
tcp_queue_rcv                                752     723     -29
tcp_data_queue                              4425    4350     -75
tcp_rcv_established                         3287    3211     -76
Total: Before=24067604, After=24067405, chg -0.00%
---
 net/ipv4/tcp_input.c | 99 +++++++++++++++++++++++---------------------
 1 file changed, 52 insertions(+), 47 deletions(-)
net/ipv4/tcp_input.c +52 -47
index 801c76744ed8..3d0a8b7e883e 100644
@@ -5276,41 +5276,47 @@ static void tcp_sack_remove(struct tcp_sock *tp)
 	tp->rx_opt.num_sacks = num_sacks;
 }
 
+/* Result of an attempt to merge an skb to a prior one. */
+enum tcp_eaten {
+	TCP_NOT_EATEN,
+	TCP_EATEN,
+	TCP_EATEN_STOLEN,	/* skb->head was stolen */
+};
+
 /**
  * tcp_try_coalesce - try to merge skb to prior one
  * @sk: socket
  * @to: prior buffer
  * @from: buffer to add in queue
- * @fragstolen: pointer to boolean
  *
  * Before queueing skb @from after @to, try to merge them
  * to reduce overall memory use and queue lengths, if cost is small.
  * Packets in ofo or receive queues can stay a long time.
  * Better try to coalesce them right now to avoid future collapses.
- * Returns true if caller should free @from instead of queueing it
+ *
+ * Return: TCP_NOT_EATEN if @from has to be queued. Otherwise the caller
+ * should free @from with kfree_skb_partial().
  */
-static bool tcp_try_coalesce(struct sock *sk,
-			     struct sk_buff *to,
-			     struct sk_buff *from,
-			     bool *fragstolen)
+static enum tcp_eaten tcp_try_coalesce(struct sock *sk,
+				       struct sk_buff *to,
+				       struct sk_buff *from)
 {
+	bool fragstolen;
 	int delta;
 
-	*fragstolen = false;
-
 	/* Its possible this segment overlaps with prior segment in queue */
 	if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq)
-		return false;
+		return TCP_NOT_EATEN;
 
 	if (!tcp_skb_can_collapse_rx(to, from))
-		return false;
+		return TCP_NOT_EATEN;
 
 	/* Nothing follows a FIN. */
 	if (unlikely(TCP_SKB_CB(to)->tcp_flags & TCPHDR_FIN))
-		return false;
+		return TCP_NOT_EATEN;
 
-	if (!skb_try_coalesce(to, from, fragstolen, &delta))
-		return false;
+	if (!skb_try_coalesce(to, from, &fragstolen, &delta))
+		return TCP_NOT_EATEN;
 
 	atomic_add(delta, &sk->sk_rmem_alloc);
 	sk_mem_charge(sk, delta);
@@ -5325,15 +5331,14 @@ static bool tcp_try_coalesce(struct sock *sk,
 		skb_hwtstamps(to)->hwtstamp = skb_hwtstamps(from)->hwtstamp;
 	}
 
-	return true;
+	return fragstolen ? TCP_EATEN_STOLEN : TCP_EATEN;
 }
 
-static bool tcp_ooo_try_coalesce(struct sock *sk,
-			     struct sk_buff *to,
-			     struct sk_buff *from,
-			     bool *fragstolen)
+static enum tcp_eaten tcp_ooo_try_coalesce(struct sock *sk,
+					   struct sk_buff *to,
+					   struct sk_buff *from)
 {
-	bool res = tcp_try_coalesce(sk, to, from, fragstolen);
+	enum tcp_eaten res = tcp_try_coalesce(sk, to, from);
 
 	/* In case tcp_drop_reason() is called later, update to->gso_segs */
 	if (res) {
@@ -5359,9 +5364,10 @@ static void tcp_ofo_queue(struct sock *sk)
 {
 	struct tcp_sock *tp = tcp_sk(sk);
 	__u32 dsack_high = tp->rcv_nxt;
-	bool fin, fragstolen, eaten;
 	struct sk_buff *skb, *tail;
+	enum tcp_eaten eaten;
 	struct rb_node *p;
+	bool fin;
 
 	p = rb_first(&tp->out_of_order_queue);
 	while (p) {
@@ -5387,13 +5393,13 @@ static void tcp_ofo_queue(struct sock *sk)
 		bpf_tcp_ops_call_flag(enqueue_rcvq, RCVQ, sk, skb);
 
 		tail = skb_peek_tail(&sk->sk_receive_queue);
-		eaten = tail && tcp_try_coalesce(sk, tail, skb, &fragstolen);
+		eaten = tail ? tcp_try_coalesce(sk, tail, skb) : TCP_NOT_EATEN;
 		tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
 		fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
 		if (!eaten)
 			tcp_add_receive_queue(sk, skb);
 		else
-			kfree_skb_partial(skb, fragstolen);
+			kfree_skb_partial(skb, eaten == TCP_EATEN_STOLEN);
 
 		if (unlikely(fin)) {
 			tcp_fin(sk);
@@ -5460,8 +5466,8 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
 	enum skb_drop_reason reason;
 	struct rb_node **p, *parent;
 	struct sk_buff *skb1;
+	enum tcp_eaten eaten;
 	u32 seq, end_seq;
-	bool fragstolen;
 	int rmem;
 
 	tcp_save_lrcv_flowlabel(sk, skb);
@@ -5504,15 +5510,15 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
 	/* In the typical case, we are adding an skb to the end of the list.
 	 * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
 	 */
-	if (tcp_ooo_try_coalesce(sk, tp->ooo_last_skb,
-				 skb, &fragstolen)) {
+	eaten = tcp_ooo_try_coalesce(sk, tp->ooo_last_skb, skb);
+	if (eaten) {
 coalesce_done:
 		/* For non sack flows, do not grow window to force DUPACK
 		 * and trigger fast retransmit.
 		 */
 		if (tcp_is_sack(tp))
 			tcp_grow_window(sk, skb, true);
-		kfree_skb_partial(skb, fragstolen);
+		kfree_skb_partial(skb, eaten == TCP_EATEN_STOLEN);
 		skb = NULL;
 		goto add_sack;
 	}
@@ -5561,9 +5567,10 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
 						SKB_DROP_REASON_TCP_OFOMERGE);
 				goto merge_right;
 			}
-		} else if (tcp_ooo_try_coalesce(sk, skb1,
-						skb, &fragstolen)) {
-			goto coalesce_done;
+		} else {
+			eaten = tcp_ooo_try_coalesce(sk, skb1, skb);
+			if (eaten)
+				goto coalesce_done;
 		}
 		p = &parent->rb_right;
 	}
@@ -5614,18 +5621,16 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
 		tcp_rcvbuf_grow(sk, tp->rcvq_space.space);
 }
 
-static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb,
-				      bool *fragstolen)
+static enum tcp_eaten __must_check tcp_queue_rcv(struct sock *sk,
+						 struct sk_buff *skb)
 {
 	int rmem = atomic_read(&sk->sk_rmem_alloc);
 	struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
-	int eaten;
+	enum tcp_eaten eaten;
 
 	bpf_tcp_ops_call_flag(enqueue_rcvq, RCVQ, sk, skb);
 
-	eaten = (tail &&
-		 tcp_try_coalesce(sk, tail,
-				  skb, fragstolen)) ? 1 : 0;
+	eaten = tail ? tcp_try_coalesce(sk, tail, skb) : TCP_NOT_EATEN;
 	tcp_rcv_nxt_update(tcp_sk(sk), TCP_SKB_CB(skb)->end_seq);
 	if (!eaten) {
 		tcp_add_receive_queue(sk, skb);
@@ -5637,10 +5642,10 @@ static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb,
 
 int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
 {
+	enum tcp_eaten eaten;
 	struct sk_buff *skb;
 	int err = -ENOMEM;
 	int data_len = 0;
-	bool fragstolen;
 
 	if (size == 0)
 		return 0;
@@ -5674,8 +5679,9 @@ int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
 	TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size;
 	TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1;
 
-	if (tcp_queue_rcv(sk, skb, &fragstolen)) {
-		WARN_ON_ONCE(fragstolen); /* should not happen */
+	eaten = tcp_queue_rcv(sk, skb);
+	if (eaten) {
+		WARN_ON_ONCE(eaten == TCP_EATEN_STOLEN); /* should not happen */
 		__kfree_skb(skb);
 	}
 	return size;
@@ -5697,8 +5703,7 @@ static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
 {
 	struct tcp_sock *tp = tcp_sk(sk);
 	enum skb_drop_reason reason;
-	bool fragstolen;
-	int eaten;
+	enum tcp_eaten eaten;
 
 	/* If a subflow has been reset, the packet should not continue
 	 * to be processed, drop the packet.
@@ -5756,7 +5761,7 @@ static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
 			sk_forced_mem_schedule(sk, skb->truesize);
 		}
 
-		eaten = tcp_queue_rcv(sk, skb, &fragstolen);
+		eaten = tcp_queue_rcv(sk, skb);
 		if (skb->len)
 			tcp_event_data_recv(sk, skb);
 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
@@ -5777,8 +5782,8 @@ static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
 
 		tcp_fast_path_check(sk);
 
-		if (eaten > 0)
-			kfree_skb_partial(skb, fragstolen);
+		if (eaten)
+			kfree_skb_partial(skb, eaten == TCP_EATEN_STOLEN);
 		if (!sock_flag(sk, SOCK_DEAD))
 			tcp_data_ready(sk);
 		return;
@@ -6815,8 +6820,7 @@ void tcp_rcv_established(struct sock *sk, struct sk_buff *skb)
 				goto discard;
 			}
 		} else {
-			int eaten = 0;
-			bool fragstolen = false;
+			enum tcp_eaten eaten;
 
 			if (tcp_checksum_complete(skb))
 				goto csum_error;
@@ -6847,7 +6851,7 @@ void tcp_rcv_established(struct sock *sk, struct sk_buff *skb)
 			__skb_pull(skb, tcp_header_len);
 			tcp_ecn_received_counters(sk, skb,
 						  len - tcp_header_len);
-			eaten = tcp_queue_rcv(sk, skb, &fragstolen);
+			eaten = tcp_queue_rcv(sk, skb);
 
 			tcp_event_data_recv(sk, skb);
 
@@ -6864,7 +6868,8 @@ void tcp_rcv_established(struct sock *sk, struct sk_buff *skb)
 			__tcp_ack_snd_check(sk, 0);
 no_ack:
 			if (eaten)
-				kfree_skb_partial(skb, fragstolen);
+				kfree_skb_partial(skb,
+						  eaten == TCP_EATEN_STOLEN);
 			tcp_data_ready(sk);
 			return;
 		}
Signature · 1 line
2.43.0
#7 lore raw

Re: [PATCH net-next v1 5/6] tcp: avoid a stack canary in tcp_rcv_established()

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] tcp: post-FIN segments queued in…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] tcp: post-FIN segments queued in tcp_rcv_state_process() and tcp_data_queue() [1]
--

commit a4b62910075d79274253c31ee8181da76c593e87
Author: Xuanqiang Luo <[email protected]>

tcp: avoid a stack canary in tcp_rcv_established()

This commit changes tcp_try_coalesce(), tcp_ooo_try_coalesce() and tcp_queue_rcv() to return an enum tcp_eaten by value instead of taking a boolean pointer for fragstolen, avoiding a stack canary in tcp_rcv_established() and tcp_data_queue().

Quoted 4 lines
net/ipv4/tcp_input.c +0 -0
index 801c76744ed8a..3d0a8b7e883e4 100644

[ ... ]

net/ipv4/tcp_input.c static void tcp_data_queue(struct sock *sk, struct sk_buff *skb) · line 5767

Quoted 9 lines
net/ipv4/tcp_input.c +1 -1
@@ -5756,7 +5761,7 @@ static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
 			sk_forced_mem_schedule(sk, skb->truesize);
 		}
 
-		eaten = tcp_queue_rcv(sk, skb, &fragstolen);
+		eaten = tcp_queue_rcv(sk, skb);
 		if (skb->len)
 			tcp_event_data_recv(sk, skb);
 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)

[Severity: High]
This problem wasn't introduced by this patch, but can a peer queue post-FIN payload onto sk->sk_receive_queue and advance tp->rcv_nxt after EOF [1]?

After an in-order FIN has been processed, RCV_SHUTDOWN is set and tp->rcv_nxt has advanced past the FIN sequence number. If a socket in TCP_CLOSE_WAIT, TCP_CLOSING, or TCP_LAST_ACK with a non-zero receive window receives a segment with seq == tp->rcv_nxt - 1, 1 byte of payload, and TCPHDR_FIN set (end_seq == tp->rcv_nxt + 1), both checks in tcp_rcv_state_process() are bypassed:

net/ipv4/tcp_input.c:tcp_rcv_state_process() {
    ...
	case TCP_CLOSE_WAIT:
	case TCP_CLOSING:
	case TCP_LAST_ACK:
		if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
			...
			break;
		}
		fallthrough;
	case TCP_FIN_WAIT1:
	case TCP_FIN_WAIT2:
		if (sk->sk_shutdown & RCV_SHUTDOWN) {
			if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
			    after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
				NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
				tcp_reset(sk, skb);
				return SKB_DROP_REASON_TCP_ABORT_ON_DATA;
			}
		}
		fallthrough;
	case TCP_ESTABLISHED:
		tcp_data_queue(sk, skb);
    ...
}

Subtracting th->fin from end_seq yields tp->rcv_nxt, so the RCV_SHUTDOWN check does not reset the connection and calls tcp_data_queue(). Because seq < tp->rcv_nxt < end_seq, tcp_data_queue() treats the packet as a partial overlap and jumps to queue_and_out, where tcp_queue_rcv() queues the post-FIN data and advances tp->rcv_nxt.

This corrupts tcp_inq() unread byte accounting after EOF and desynchronizes tp->copied_seq from kTLS record consumption in tcp_read_done(), which stops at the first skb carrying TCPHDR_FIN while tls_strp_check_queue_ok() accepts multi-skb records across FIN boundaries.

[1] https://sashiko.dev/#/bug/linux-ddef83cf-eb5a-48d6-b4ef-687a557a5260

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#8 lore raw

PATCH 6/6 tcp: do not call bpf_skops_write_hdr_opt() unless needed

In reply to Xuanqiang Luo

From: Xuanqiang Luo <[email protected]>

__tcp_transmit_skb() calls bpf_skops_write_hdr_opt() for every skb. The function returns at once if no BPF program reserved room for TCP options (opts->bpf_opt_len == 0), which is the common case.

It has a struct bpf_sock_ops_kern on its stack. With CONFIG_STACKPROTECTOR_STRONG=y, its stack canary is set up and checked even when it has nothing to do.

Test opts.bpf_opt_len in its callers instead.

$ scripts/bloat-o-meter -t vmlinux.old vmlinux.new
add/remove: 0/0 grow/shrink: 2/2 up/down: 28/-196 (-168)
Function                                     old     new   delta
tcp_make_synack                             2006    2020     +14
__tcp_transmit_skb                          4114    4128     +14
tcp_options_write.isra                      1699    1651     -48
bpf_skops_write_hdr_opt.isra                1206    1058    -148
Total: Before=24067405, After=24067237, chg -0.00%
---
 net/ipv4/tcp_output.c | 11 +++++------
 1 file changed, 5 insertions(+), 6 deletions(-)
net/ipv4/tcp_output.c +5 -6
index c2022fc9ad52..3c0be5a675ea 100644
@@ -538,9 +538,6 @@ static void bpf_skops_write_hdr_opt(struct sock *sk, struct sk_buff *skb,
 {
 	u8 first_opt_off, nr_written = 0, max_opt_len = opts->bpf_opt_len;
 
-	if (likely(!max_opt_len))
-		return;
-
 	first_opt_off = tcp_hdrlen(skb) - max_opt_len;
 
 	if (cgroup_bpf_enabled(CGROUP_SOCK_OPS) &&
@@ -1731,7 +1728,8 @@ static int __tcp_transmit_skb(struct sock *sk, struct sk_buff *skb,
 	}
 
 	/* BPF prog is the last one writing header option */
-	bpf_skops_write_hdr_opt(sk, skb, NULL, NULL, 0, &opts);
+	if (unlikely(opts.bpf_opt_len))
+		bpf_skops_write_hdr_opt(sk, skb, NULL, NULL, 0, &opts);
 
 #if IS_ENABLED(CONFIG_IPV6)
 	if (likely(icsk->icsk_af_ops->net_header_len == sizeof(struct ipv6hdr)))
@@ -4146,8 +4144,9 @@ struct sk_buff *tcp_make_synack(const struct sock *sk, struct dst_entry *dst,
 	rcu_read_unlock();
 #endif
 
-	bpf_skops_write_hdr_opt((struct sock *)sk, skb, req, syn_skb,
-				synack_type, &opts);
+	if (unlikely(opts.bpf_opt_len))
+		bpf_skops_write_hdr_opt((struct sock *)sk, skb, req, syn_skb,
+					synack_type, &opts);
 
 	skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC);
 	tcp_add_tx_delay(skb, tp);
Signature · 1 line
2.43.0