Skip to contentSkip to conversation

IPVS fixes for net

PATCH Superseded Pablo Neira Ayuso 4 participants 32 messages Nov 13 – Nov 15

Subsystems (5)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Pablo Neira Ayuso

author maintainer
#0 lore raw

cover IPVS fixes for net

Hi,

The following patchset contains IPVS fixes for net:

1) Avoid out-of-bounds write in ip_vs_nat_icmp_v6() when an ICMPv6 error embeds a non-first ESP fragment, from Axel Mierczuk.

2) Update *offset for non-first fragments in ipv6_find_hdr(), so callers no longer use the initial offset as if it had been updated. Also from Axel.

3) Rework connection refcounting so the pending and running timer hold a reference. This fixes a use-after-free race between connection deletion and a concurrent timer callback, from Julian Anastasov.

4) Expire controlled connection chains iteratively instead of recursively to avoid kernel stack exhaustion, from Zihan Xi.

5) Reject zero and configured FTP control ports as data ports in the FTP helper, from Zihan Xi.

6) Skip conntrack templates in ip_vs_ftp_out() to fix a UAF in the expectation list after the CT rule is removed, from Theodor Arsenij Larionov Trichkine.

7) Add the seqadj extension before linking the FTP expectation, since krealloc() of ct->ext can otherwise leave the expectation pointing to freed memory. Also from Theodor.

8) Update conn flags, seqs and related fields in the backup server

    under cp->lock, from Julian Anastasov.

9) Read conn flags and seqs atomically in the master when building sync messages, from Julian Anastasov.

10) Fix a race that can leave a destination in the overload state forever. Also make the LBLC/LBLCR schedulers honor the overload state for cached destinations, from Julian Anastasov.

11) Validate cport and IP_VS_CONN_F_NO_CPORT in received sync records. This rejects templates and connections that incoming lookups cannot match, from Axel Mierczuk.

12) Skip cport 0 connections in ip_vs_conn_out_get(), using the same rule as __ip_vs_conn_in_get(). Also from Axel.

13) Do not create connections from packets with client or virtual port 0, which could create a duplicate connection for every packet, from Julian Anastasov.

14) Wait for an RCU grace period before reusing a destination from dest_trash, and before restarting its estimator, from Darong Lu.

15) Pass the netfilter hook's state->sk to the update_pmtu handler, and pass a NULL sk to ip_local_out() when forwarding through an IPVS tunnel, from Julian Anastasov.

Please, pull these changes from:

git://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git nf-26-11-13

Thanks.

----------------------------------------------------------------

The following changes since commit d1bb235aa409a4e5aeba6c748d953d948625b1e9:

netfilter: nat: zero newrange before filling it in (2026-11-05 13:31:11 +0100)

are available in the Git repository at:

git://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git nf-26-11-13

for you to fetch changes up to 937b060406a547e4d931525e600540726ea26532:

ipvs: pass correct sk to update_pmtu and on tunneling (2026-11-13 02:08:35 +0100)

----------------------------------------------------------------
netfilter pull request 26-11-13

----------------------------------------------------------------
Axel Mierczuk (4):
ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6
ipv6: update *offset for non-first fragments in ipv6_find_hdr()
ipvs: validate cport in received sync records
ipvs: skip cport 0 connections in ip_vs_conn_out_get()

Darong Lu (1):
ipvs: wait grace period before reusing destinations

Julian Anastasov (6):
ipvs: fix problems during connection deletion
ipvs: update flags and seqs in backup server under lock
ipvs: read flags and seqs in master atomically
ipvs: honor the overload state and do not enter it forever
ipvs: do not create conns from packets with port 0
ipvs: pass correct sk to update_pmtu and on tunneling

Theodor Arsenij Larionov Trichkine (2):
ipvs: ftp: skip conntrack templates in ip_vs_ftp_out
ipvs: ftp: add seqadj extension before linking the expectation

Zihan Xi (2):
ipvs: avoid stack overflow from recursive connection expiration
ipvs: reject FTP control ports as data ports

 include/net/ip_vs.h                     |  52 ++++++++----
 net/ipv6/exthdrs_core.c                 |   6 +-
 net/netfilter/ipvs/ip_vs_conn.c         | 133 ++++++++++++++++++------------
 net/netfilter/ipvs/ip_vs_core.c         |  58 +++++++++----
 net/netfilter/ipvs/ip_vs_ctl.c          | 140 ++++++++++++++++++++++++--------
 net/netfilter/ipvs/ip_vs_ftp.c          |  39 +++++++--
 net/netfilter/ipvs/ip_vs_lblc.c         |   8 +-
 net/netfilter/ipvs/ip_vs_lblcr.c        |  13 +--
 net/netfilter/ipvs/ip_vs_proto_ah_esp.c |   2 +-
 net/netfilter/ipvs/ip_vs_proto_sctp.c   |  12 ++-
 net/netfilter/ipvs/ip_vs_proto_tcp.c    |  12 ++-
 net/netfilter/ipvs/ip_vs_proto_udp.c    |  11 ++-
 net/netfilter/ipvs/ip_vs_sync.c         |  53 ++++++++++--
 net/netfilter/ipvs/ip_vs_xmit.c         | 114 +++++++++++++++++---------
 14 files changed, 462 insertions(+), 191 deletions(-)
author maintainer
#1 lore raw

PATCH 1/15 ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6

From: Axel Mierczuk <[email protected]>

ipv6_find_hdr() does not set the header offset for non-first fragments, so an ICMPv6 error embedding such an ESP fragment leaves ip_vs_fill_iph_skb_icmp() with len == off. The NAT paths size skb_ensure_writable() from len, and ip_vs_nat_icmp_v6() then writes the embedded addresses after the validated area.

Include the embedded IP header in ciph.len at both ICMPv6 call sites when parsing stops at a non-first fragment. ESP lookup does not require a transport header. Non-first TCP, UDP and SCTP fragments bypass IPVS ICMP handling before connection lookup.

This fix does not depend on patch 2. Stable kernels without commit 342e24a339b9 ("ipvs: do not mangle ICMP replies for non-first fragments") also need that commit to handle incoming ICMPv6 errors quoting non-first ESP fragments.

Fixes 63dca2c0b0e7 ("ipvs: Fix faulty IPv6 extension header handling in IPVS")
---
 net/netfilter/ipvs/ip_vs_core.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
net/netfilter/ipvs/ip_vs_core.c +14 -0
index 8a3c880fdb26..76213159404f 100644
@@ -1206,6 +1206,13 @@ static int ip_vs_out_icmp_v6(struct netns_ipvs *ipvs, struct sk_buff *skb,
 				     true, &ciph))
 		return NF_ACCEPT; /* The packet looks wrong, ignore */
 
+	/* ipv6_find_hdr() does not include the embedded header for
+	 * non-first fragments, add it so that ESP can pass and the
+	 * NAT writable checks cover the rewritten addresses
+	 */
+	if (ciph.len == ciph.off)
+		ciph.len += sizeof(struct ipv6hdr);
+
 	pp = ip_vs_proto_get(ciph.protocol);
 	if (!pp)
 		return NF_ACCEPT;
@@ -2036,6 +2043,13 @@ static int ip_vs_in_icmp_v6(struct netns_ipvs *ipvs, struct sk_buff *skb,
 	if (!ip_vs_fill_iph_skb_icmp(AF_INET6, skb, offset, true, &ciph))
 		return NF_ACCEPT;
 
+	/* ipv6_find_hdr() does not include the embedded header for
+	 * non-first fragments, add it so that ESP can pass and the
+	 * NAT writable checks cover the rewritten addresses
+	 */
+	if (ciph.len == ciph.off)
+		ciph.len += sizeof(struct ipv6hdr);
+
 	pd = ip_vs_proto_data_get(ipvs, ciph.protocol);
 	if (!pd)
 		return NF_ACCEPT;
Signature · 1 line
2.47.3
#2 lore raw

Re: [PATCH net 01/15] ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6

This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

Hi!

This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

- How the issue was discovered, e.g. hit in production, hit during development, syzbot report, manual code inspection, LLM or static analysis tool scan.

- Whether the issue was actually triggered, or is only theoretical (e.g. found by LLM and not proven at runtime). If it was triggered please include the symptoms, like the stack trace or kernel messages.

Please do not repost the series just to address the above. Instead, reply to this email with the missing information, so that reviewers can take it into account. If the series needs another revision for other reasons, please include the information in the commit messages then.

The evaluation is done by an LLM so it may be wrong, if you think that is the case please reply and explain.

author maintainer
#3 lore raw

Re: [PATCH net 01/15] ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6

Quoted 8 lines · On Fri, Nov 13, 2026 at 01:16:59AM +0000, [email protected] wrote:

Hi!

This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

- How the issue was discovered, e.g. hit in production, hit during development, syzbot report, manual code inspection, LLM or static analysis tool scan.

This is a PR, there is a mix of patches coming from different sources but...

Quoted 3 lines

- Whether the issue was actually triggered, or is only theoretical (e.g. found by LLM and not proven at runtime). If it was triggered please include the symptoms, like the stack trace or kernel messages.

... these are mostly LLM findings.

Quoted 8 lines

Please do not repost the series just to address the above. Instead, reply to this email with the missing information, so that reviewers can take it into account. If the series needs another revision for other reasons, please include the information in the commit messages then.

The evaluation is done by an LLM so it may be wrong, if you think that is the case please reply and explain.

#4 lore raw

Re: [PATCH net 01/15] ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6

In reply to Pablo Neira Ayuso
Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] Commit "ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6" has only Fixes: 63dca2c0b0e7.
- [Low] The commit message says "This fix does not depend on patch 2".

--

ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6

This patch changes both ICMPv6 handlers in IPVS. When ipv6_find_hdr() stops at a non-first fragment and leaves ciph.len == ciph.off, the embedded IPv6 header is now added to ciph.len. The skb_ensure_writable() range used by the NAT paths then covers the addresses that ip_vs_nat_icmp_v6() rewrites.

Quoted 6 lines

This fix does not depend on patch 2. Stable kernels without commit 342e24a339b9 ("ipvs: do not mangle ICMP replies for non-first fragments") also need that commit to handle incoming ICMPv6 errors quoting non-first ESP fragments.

Fixes 63dca2c0b0e7 ("ipvs: Fix faulty IPv6 extension header handling in IPVS")

[Severity: Low]
The incoming half of this bug only seems to have become reachable with 342e24a339b9. That path is ip_vs_in_icmp_v6()->ip_vs_icmp_xmit_v6()->ip_vs_nat_icmp_v6().

Before that commit, ip_vs_in_icmp_v6() had:

	if (ciph.fragoffs)
		return NF_ACCEPT;

342e24a339b9 changed it to:

	if (ciph.fragoffs && !pp->dont_defrag)
		return NF_ACCEPT;

ESP sets .dont_defrag = 1 in ip_vs_proto_ah_esp.c, so non-first ESP fragments now reach ip_vs_icmp_xmit_v6(). There, wlen = ciph->len sizes skb_ensure_writable(), and without this fix ciph->len equals ciph->off. ip_vs_nat_icmp_v6() then writes the embedded addresses past that range.

The paragraph above reads as if 342e24a339b9 is only a functional prerequisite. Should it say that 342e24a339b9 exposed the incoming-path write, and add a second Fixes: 342e24a339b9 tag? The existing

Fixes 63dca2c0b0e7 tag plus Cc: stable already covers backports, so

this is mostly about traceability.

Quoted 5 lines
net/netfilter/ipvs/ip_vs_core.c +0 -0
index 8a3c880fdb266..76213159404f0 100644

net/netfilter/ipvs/ip_vs_core.c static int ip_vs_out_icmp_v6(struct netns_ipvs *ipvs, struct sk_buff *skb, · line 1214

Quoted 9 lines
net/netfilter/ipvs/ip_vs_core.c +6 -0
@@ -1206,6 +1206,13 @@ static int ip_vs_out_icmp_v6(struct netns_ipvs *ipvs, struct sk_buff *skb,
 				     true, &ciph))
 		return NF_ACCEPT; /* The packet looks wrong, ignore */
 
+	/* ipv6_find_hdr() does not include the embedded header for
+	 * non-first fragments, add it so that ESP can pass and the
+	 * NAT writable checks cover the rewritten addresses
+	 */
+	if (ciph.len == ciph.off)
+		ciph.len += sizeof(struct ipv6hdr);

[Severity: Low]
This isn't a bug, but is "so that ESP can pass" accurate for the IPv6 paths? A len vs off comparison only exists on the IPv4 side, for example in ip_vs_nat_icmp():

	if (cih->ihl * 4 != ciph->len - ciph->off)
		return false;

None of these compare ciph.len with ciph.off:

- ip_vs_out_icmp_v6()
- ip_vs_in_icmp_v6()
- handle_response_icmp()
- ip_vs_icmp_xmit_v6()
- ip_vs_nat_icmp_v6()
- the AH/ESP conn_in_get/conn_out_get handlers

So the only effect seems to be the larger skb_ensure_writable() range.

Later in the series, "ipv6: update *offset for non-first fragments in ipv6_find_hdr()" makes ipv6_find_hdr() do this for non-first fragments:

	*offset = start + sizeof(struct frag_hdr);

After that change, the first clause of this comment is no longer true. The ciph.len == ciph.off check also can't fire any more, here or in the copy added to ip_vs_in_icmp_v6().

Separately, the commit message says "This fix does not depend on patch 2." Once merged, "patch 2" won't point to anything in git history. Could it name "ipv6: update *offset for non-first fragments in ipv6_find_hdr()" instead?

Quoted 4 lines
net/netfilter/ipvs/ip_vs_core.c +1 -0
+
 	pp = ip_vs_proto_get(ciph.protocol);
 	if (!pp)
 		return NF_ACCEPT;

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
maintainer
#5 lore raw

Re: [PATCH net 01/15] ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6

Hello,

Quoted 3 lines · On Sat, 14 Nov 2026, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

In summary: we can drop current patches 1, 2, 15 and
should address problems in 7.

We plan to update patch 2 to check for present data.
Both patches 1 and 2 go together, so they can be dropped for now and improved in next version.

Patches 4, 8, 10 and 14 are ok, even if wording can be improved.

Patch 5: we prefer to drop the traffic when port 0 is involved

Patch 7 should be checked by the Netfilter guys.

Patch 11: NO_CPORT is before connection is established and we do not sync conns in master before establishment. So, nothing bad can happen in practice.

Patch 12: races are possible but nothing fatal

Patch 15: The patch was meant for ip_vs_bind_xmit_v6. daddr can be further limited in next version, so this patch can be dropped.

Quoted 2 lines
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org

Regards

--
Julian Anastasov <[email protected]>

author maintainer
#6 lore raw

Re: [PATCH net 01/15] ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6

Hi Julian,

Quoted 11 lines · Julian Anastasov

Hello,

Quoted 3 lines · On Sat, 14 Nov 2026, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

In summary: we can drop current patches 1, 2, 15 and
should address problems in 7.

OK; then I'll drop 1, 2, 7 and 15. Regarding 7, see below.

Quoted 9 lines

We plan to update patch 2 to check for present data.
Both patches 1 and 2 go together, so they can be dropped for now and improved in next version.

Patches 4, 8, 10 and 14 are ok, even if wording can be improved.

Patch 5: we prefer to drop the traffic when port 0 is involved

Patch 7 should be checked by the Netfilter guys.

It seems it is possible to create an expectation on unconfirmed conntrack entries from the IPVS ftp helper.

For a TCP connection, the conntrack entry should not be already in confirmed state when the FTP helper runs in most cases.

So I think easiest way is to make a patch to prevent unconfirmed conntracks from expectations in the IPVS FTP helper.

Quoted 16 lines

Patch 11: NO_CPORT is before connection is established and we do not sync conns in master before establishment. So, nothing bad can happen in practice.

Patch 12: races are possible but nothing fatal

Patch 15: The patch was meant for ip_vs_bind_xmit_v6. daddr can be further limited in next version, so this patch can be dropped.

Quoted 2 lines
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org

Regards

--
Julian Anastasov <[email protected]>

author maintainer
#7 lore raw

PATCH 2/15 ipv6: update *offset for non-first fragments in ipv6_find_hdr()

In reply to Pablo Neira Ayuso

From: Axel Mierczuk <[email protected]>

The non-first fragment early return is the only successful exit of ipv6_find_hdr() that leaves *offset untouched. IPVS used the initial offset as if it had been updated.

For non-first fragments with target < 0, set *offset immediately after the Fragment header, at the start of the fragment payload. Callers must still account for the nonzero fragment offset. A NEXTHDR_FRAGMENT search continues to return the Fragment header's offset. Other target < 0 callers check the returned fragment offset or ignore *offset here.

Fixes b777e0ce7437 ("[NETFILTER]: make ipv6_find_hdr() find transport protocol header")
---
 net/ipv6/exthdrs_core.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
net/ipv6/exthdrs_core.c +5 -1
index 4a9748338cf4..e27f5b8cc154 100644
@@ -179,7 +179,10 @@ EXPORT_SYMBOL_GPL(ipv6_find_tlv);
  *
  * Note that non-1st fragment is special case that "the protocol number
  * of last header" is "next header" field in Fragment header. In this case,
- * *offset is meaningless and fragment offset is stored in *fragoff if fragoff
+ * for target < 0, *offset points immediately after the Fragment header,
+ * at the start of the fragment payload. Callers must still account for
+ * the nonzero fragment offset before interpreting the payload. The
+ * fragment offset is stored in *fragoff if fragoff
  * isn't NULL.
  *
  * if flags is not NULL and it's a fragment, then the frag flag
@@ -261,6 +264,7 @@ int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset,
 				     hp->nexthdr == NEXTHDR_NONE)) {
 					if (fragoff)
 						*fragoff = _frag_off;
+					*offset = start + sizeof(struct frag_hdr);
 					return hp->nexthdr;
 				}
 				if (!found)
Signature · 1 line
2.47.3
#8 lore raw

Re: [PATCH net 02/15] ipv6: update *offset for non-first fragments in ipv6_find_hdr()

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 2 · Low: 1

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] This patch adds a new success exit to ipv6_find_hdr():
*offset = start + sizeof(struct frag_hdr), taken for a non-first…
- [Medium] The commit message says "Other target < 0 callers check the returned fragment offset or ignore *offset here." That is not true for…
- [Low] The earlier patch in this series, "ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6", added a compensation block to…

--

ipv6: update *offset for non-first fragments in ipv6_find_hdr()

This commit makes ipv6_find_hdr() set *offset to the byte right after the Fragment header when it takes the early return for a non-first fragment with target < 0. Before this, that exit left *offset unchanged, and IPVS used the initial offset as if it had been updated.

Quoted 2 lines

Other target < 0 callers check the returned fragment offset or ignore *offset here.

[Severity: Medium]
Does this hold for every consumer of the offset?

ip6_packet_match() passes &acpar.thoff to ipv6_find_hdr(), and the result reaches xt targets as par->thoff. nft_set_pktinfo_ipv6() sets pkt->thoff the same way, and nft_compat forwards it to xt targets.

synproxy_tg6() in ip6t_SYNPROXY.c and nft_synproxy_do_eval() in nft_synproxy.c do not check par->fragoff or pkt->fragoff:

net/ipv6/netfilter/ip6t_SYNPROXY.c:synproxy_tg6() {
    ...
	if (nf_ip6_checksum(skb, xt_hooknum(par), par->thoff, IPPROTO_TCP))
		return NF_DROP;

	th = skb_header_pointer(skb, par->thoff, sizeof(_th), &_th);
	...
	if (th->syn && !(th->ack || th->fin || th->rst)) {
		/* Initial SYN from client */
    ...
}

Before this patch, thoff stayed at 0 for non-first fragments, so these targets parsed the IPv6 header as a TCP header. That was also wrong, but a sender had little control over it.

With this change, thoff points at the fragment payload, and the sender controls all of it. Could SYNPROXY now treat a non-first fragment that carries a forged TCP SYN or ACK with a valid checksum as a real segment? It would then answer with a SYN-cookie SYN-ACK, or send a SYN to the server.

Earlier port-filtering matches (tcp, multiport, payload) skip these fragments because they check fragoff. To reach SYNPROXY, the fragment has to get past nf_defrag_ipv6 without being reassembled. One way is notrack before defrag, which makes ipv6_defrag() return NF_ACCEPT for IP_CT_UNTRACKED.

xt_ecn match_tcp() and xt_tcpmss tcpmss_mt() do check par->fragoff and are not affected. The missing fragoff check in SYNPROXY is older than this patch.

Quoted 4 lines
net/ipv6/exthdrs_core.c +0 -0
index 764c694fb417a..12908d8ca370f 100644

[ ... ]

net/ipv6/exthdrs_core.c int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset, · line 268

Quoted 5 lines
net/ipv6/exthdrs_core.c +1 -0
@@ -262,6 +265,7 @@ int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset,
 				     hp->nexthdr == NEXTHDR_NONE)) {
 					if (fragoff)
 						*fragoff = _frag_off;
+					*offset = start + sizeof(struct frag_hdr);

[Severity: Medium]
Can this set *offset past the end of the skb?

At this point only the first 4 bytes of the 8-byte Fragment header have been bounds checked. hp reads 2 bytes at start, and fp reads the 2-byte frag_off at start + 2. Nothing checks that the Identification field is inside the packet.

Every other success exit runs this check before start advances:

		if (!found) {
			if (skb->len - start < hdrlen)
				return -EBADMSG;

Take a packet that ends 4 to 7 bytes into the Fragment header, for example with payload_len = 4. This path now returns success with *offset up to 4 bytes past skb->len. Before the patch, *offset kept its input value here.

Remote input can reach this. ip6_rcv_core() only parses hop-by-hop options. PRE_ROUTING hooks see such packets when nf_defrag_ipv6 is not loaded, when a chain runs before defrag (priority < -400), or when the packet is marked notrack before defrag.

nft_set_pktinfo_ipv6() only rejects thoff > U16_MAX. It therefore stores a pkt->thoff larger than skb->len and sets NFT_PKTINFO_L4PROTO. The subtraction in nf_trace_fill_pkt_info() then underflows:

		len = min_t(unsigned int, skb->len - nft_thoff(pkt),
			    NFT_TRACETYPE_TRANSPORT_HSIZE);

skb_copy_bits() then fails and nft_trace_notify() jumps to nla_put_failure. That path hits DEBUG_NET_WARN_ON_ONCE(1) and drops the trace event.

synproxy_tg6() and nft_synproxy_do_eval() also pass this thoff to nf_ip6_checksum() and nf_checksum(). For CHECKSUM_NONE and CHECKSUM_COMPLETE, these call skb_checksum(skb, 0, dataoff, 0) with a length past skb->len, which hits the DEBUG_NET_WARN_ON_ONCE(1) in skb_checksum(). They also pass skb->len - dataoff to csum_ipv6_magic(), and that value underflows.

Would it be better to require the whole Fragment header before setting *offset? For example:

	if (skb->len - start < sizeof(struct frag_hdr))
		return -EBADMSG;

[Severity: Low]
The earlier patch in this series, "ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6", added a compensation block to ip_vs_out_icmp_v6() and ip_vs_in_icmp_v6(). Does this change make that block dead code?

net/netfilter/ipvs/ip_vs_core.c:ip_vs_out_icmp_v6() {
    ...
	/* ipv6_find_hdr() does not include the embedded header for
	 * non-first fragments, add it so that ESP can pass and the
	 * NAT writable checks cover the rewritten addresses
	 */
	if (ciph.len == ciph.off)
		ciph.len += sizeof(struct ipv6hdr);
    ...
}

ip_vs_fill_iph_skb_off() sets iphdr->len = offset, which is nonzero. ipv6_find_hdr() therefore starts at *offset + sizeof(struct ipv6hdr). Flags start at 0 and target is -1, so every success exit now sets *offset to at least ciph.off + 40. As a result, ciph.len == ciph.off can no longer be true.

The comment at both sites also describes behaviour that ipv6_find_hdr() no longer has, and it contradicts the kernel-doc added by this patch. Both copies are still there, unchanged, at the end of the series.

For ESP non-first fragments, ciph.len now also covers the extension headers and the full 8-byte Fragment header, not just off + 40.

Should the block and its comment be removed or updated in both functions?

Quoted 3 lines
net/ipv6/exthdrs_core.c +0 -0
 					return hp->nexthdr;
 				}
 				if (!found)
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#9 lore raw

PATCH 3/15 ipvs: fix problems during connection deletion

In reply to Pablo Neira Ayuso

From: Julian Anastasov <[email protected]>

Sashiko reports for problem when deleting connections.

If connection timer expires, its callback can not be concurrently running but if connection is deleted the callback can be running on another CPU even after all references are released. Before now we continued with the connection freeing, risking the callback to access the deleted connection after it is freed. As ip_vs_conn_del() runs under RCU lock there is no risk for accessing a connection freed by concurrent timer callback. As Sashiko warns, the risk is present if normal connection expires and tries to delete its cp->control chain with ip_vs_conn_del_put() without holding a RCU read lock.

It is evident that as the pending timer and the running timer callback do not hold reference for the connection, there are races which is difficult to avoid.

Change the connection refcounting as follows:

* the connection hashing does not take reference anymore

* new connection handoffs its reference to the timer if started in __ip_vs_conn_put_timer(), to hold it while it is pending.

* if user finds connection in hash table it gets reference and can handoff this reference to the pending timer if this timer is started in __ip_vs_conn_put_timer(), otherwise puts its reference if the timer was already pending which is the common case.

* the pending timer handoffs its reference to the running timer callback implicitly. By this way, the timer callback in the common case has the last reference. In rare cases, while the timer callback is running and before it changes refcnt from 1 to 0, other users can get reference and to handoff it again to the pending timer they arm. In this case, the expiration is deferred for later time.

As result, cp->refcnt accounts all current connection users and the pending and running timer.

Two paths can try to delete the connection: the normal expiration path and ip_vs_conn_del() if it successfully steals the connection reference from the pending timer. refcount_dec_if_one() will tell us if we were the last active user with no packets accessing the connection and no pending/running timers.

Change ip_vs_conn_unlink() to directly unhash the connection because when we are the last user the connection's forwarding method can not change.
Use smp_acquire__after_ctrl_dep() after refcount_dec_if_one() and before reading the connection fields.

ip_vs_conn_expire() does not need to call timer_delete() anymore because the pending timer is already accounted in refcnt.

Add explicit rcu_read_lock() while deleting the cp->control chain to protect from concurrent timer callback for ct to expire it before us and to cause use-after-free.

During such races, try to keep 0 in cp->timeout as it is a request for deleting our cp->control chain immediately. Make sure we do not send timeout 0 (seconds) in the v1 sync message because the backup server will select some large default value which is not desired for small timeouts.

Remove the smp_mb__before_atomic() call from __ip_vs_conn_put(), it is from the atomic_dec() era, now refcount_dec() has RELEASE semantics.

---
 include/net/ip_vs.h             |  1 -
 net/netfilter/ipvs/ip_vs_conn.c | 99 ++++++++++++++++++---------------
 net/netfilter/ipvs/ip_vs_sync.c |  2 +-
 3 files changed, 55 insertions(+), 47 deletions(-)
include/net/ip_vs.h +0 -1
index 9a83bff32569..97097d60d1c4 100644
@@ -1685,7 +1685,6 @@ static inline bool __ip_vs_conn_get(struct ip_vs_conn *cp)
 /* put back the conn without restarting its timer */
 static inline void __ip_vs_conn_put(struct ip_vs_conn *cp)
 {
-	smp_mb__before_atomic();
 	refcount_dec(&cp->refcnt);
 }
 void ip_vs_conn_put(struct ip_vs_conn *cp);
net/netfilter/ipvs/ip_vs_conn.c +54 -45

179 lines not on this page · raw message

net/netfilter/ipvs/ip_vs_sync.c +1 -1
index 157f5c8361ab..1caacf419af9 100644
@@ -732,7 +732,7 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts)
 	s->v4.vport = cp->vport;
 	s->v4.dport = cp->dport;
 	s->v4.fwmark = htonl(cp->fwmark);
-	s->v4.timeout = htonl(cp->timeout / HZ);
+	s->v4.timeout = htonl(max(1UL, cp->timeout / HZ));
 	m->nr_conns++;
 
 #ifdef CONFIG_IP_VS_IPV6
Signature · 1 line
2.47.3
author maintainer
#10 lore raw

PATCH 4/15 ipvs: avoid stack overflow from recursive connection expiration

In reply to Pablo Neira Ayuso

From: Zihan Xi <[email protected]>

When a controlled IPVS connection expires, its controller may be expired synchronously if it has no remaining controlled connections. A chain of controlled connections can then recurse through ip_vs_conn_expire() and exhaust the kernel stack during namespace cleanup.

Continue expiration with the controller after the current connection has been fully cleaned up instead of calling ip_vs_conn_del() recursively. Keep the expiration walk under RCU, preserve the immediate-drop timeout for a controller with its own controller, and switch to deletion mode before the next iteration.

This keeps controlled-connection cleanup synchronous while using one stack frame for the whole chain. The timer callback race during connection deletion is handled by the preceding connection-deletion fix.

This patch depends on "ipvs: fix problems during connection deletion" to protect the iterative controller cleanup from the timer callback race.

Fixes f9200a52eedf ("ipvs: avoid expiring many connections from timer")
---
 net/netfilter/ipvs/ip_vs_conn.c | 40 ++++++++++++++++++++++++---------
 1 file changed, 29 insertions(+), 11 deletions(-)
net/netfilter/ipvs/ip_vs_conn.c +29 -11
index 86c5e6c7b5af..27db8d558a03 100644
@@ -1336,9 +1336,23 @@ static void ip_vs_conn_rcu_free(struct rcu_head *head)
 	kmem_cache_free(ip_vs_conn_cachep, cp);
 }
 
-/* Try to delete connection while not holding reference.
+/* Try to steal the reference from the pending timer.
  * It can be called concurrently and always under RCU lock
  * to protect from connection deletion from others.
+ */
+static bool ip_vs_conn_del_reference(struct ip_vs_conn *cp)
+{
+	/* Steal reference from the pending timer */
+	if (!timer_delete(&cp->timer))
+		return false;
+
+	/* Drop cp->control chain too */
+	if (cp->control)
+		cp->timeout = 0;
+	return true;
+}
+
+/* Try to delete connection while not holding reference.
  * Used when we need to remove the connection immediately
  * and without overloading the timer processing.
  * OTOH, we use ip_vs_conn_expire_now() when we prefer to
@@ -1347,13 +1361,8 @@ static void ip_vs_conn_rcu_free(struct rcu_head *head)
  */
 static void ip_vs_conn_del(struct ip_vs_conn *cp)
 {
-	/* Steal reference from the pending timer */
-	if (timer_delete(&cp->timer)) {
-		/* Drop cp->control chain too */
-		if (cp->control)
-			cp->timeout = 0;
+	if (ip_vs_conn_del_reference(cp))
 		ip_vs_conn_expire(&cp->timer);
-	}
 }
 
 /* Connection is removed in the following steps:
@@ -1366,6 +1375,9 @@ static void ip_vs_conn_expire(struct timer_list *t)
 	struct ip_vs_conn *cp = timer_container_of(cp, t, timer);
 	struct netns_ipvs *ipvs = cp->ipvs;
 
+	rcu_read_lock();
+
+repeat:
 	/*
 	 *	do I control anybody?
 	 */
@@ -1375,19 +1387,18 @@ static void ip_vs_conn_expire(struct timer_list *t)
 	/* Unlink conn if not referenced anymore */
 	if (likely(ip_vs_conn_unlink(cp))) {
 		struct ip_vs_conn *ct = cp->control;
+		bool next = false;
 
 		/* does anybody control me? */
 		if (ct) {
-			rcu_read_lock();
 			ip_vs_control_del(cp);
 			/* Drop CTL or non-assured TPL if not used anymore */
 			if (!cp->timeout && !atomic_read(&ct->n_control) &&
 			    (!(ct->flags & IP_VS_CONN_F_TEMPLATE) ||
 			     !(ct->state & IP_VS_CTPL_S_ASSURED))) {
 				IP_VS_DBG(4, "drop controlling connection\n");
-				ip_vs_conn_del(ct);
+				next = ip_vs_conn_del_reference(ct);
 			}
-			rcu_read_unlock();
 		}
 
 		if ((cp->flags & IP_VS_CONN_F_NFCT) &&
@@ -1414,7 +1425,11 @@ static void ip_vs_conn_expire(struct timer_list *t)
 		else
 			call_rcu(&cp->rcu_head, ip_vs_conn_rcu_free);
 		atomic_dec(&ipvs->conn_count);
-		return;
+		if (next) {
+			cp = ct;
+			goto repeat;
+		}
+		goto out;
 	}
 
   expire_later:
@@ -1429,6 +1444,9 @@ static void ip_vs_conn_expire(struct timer_list *t)
 		ip_vs_sync_conn(ipvs, cp, sysctl_sync_threshold(ipvs));
 
 	__ip_vs_conn_put_timer(cp);
+
+out:
+	rcu_read_unlock();
 }
 
 /* Modify timer, so that it expires as soon as possible.
Signature · 1 line
2.47.3
#11 lore raw

Re: [PATCH net 04/15] ipvs: avoid stack overflow from recursive connection expiration

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] The commit message says the recursive chain walk exhausts the kernel stack "during namespace cleanup".

--

ipvs: avoid stack overflow from recursive connection expiration

This commit replaces the recursive controller expiration in ip_vs_conn_expire() with an iterative walk. It no longer calls ip_vs_conn_del() on the controller. Instead, the new ip_vs_conn_del_reference() helper steals the controller's timer reference, and the function loops back with cp = ct inside a single rcu_read_lock() section.

Quoted 4 lines

When a controlled IPVS connection expires, its controller may be expired synchronously if it has no remaining controlled connections. A chain of controlled connections can then recurse through ip_vs_conn_expire() and exhaust the kernel stack during namespace cleanup.

[Severity: Low]
This isn't a bug, but is "during namespace cleanup" the only place the recursion can happen?

ip_vs_conn_del_reference() is the only code that sets cp->timeout = 0, which arms the drop-controller chain. It is reached from runtime callers as well as from the netns flush.

ip_vs_random_dropentry() runs from defense_work when drop_entry defense is active:

net/netfilter/ipvs/ip_vs_conn.c:ip_vs_random_dropentry() {
    ...
drop:
			IP_VS_DBG(4, "drop connection\n");
			ip_vs_conn_del(cp);
    ...
}

ip_vs_expire_nodest_conn_flush() runs when a real server becomes unavailable and expire_nodest_conn is set:

net/netfilter/ipvs/ip_vs_conn.c:ip_vs_expire_nodest_conn_flush() {
    ...
			ip_vs_conn_del(cp);
			if (cp_c && !atomic_read(&cp_c->n_control)) {
				IP_VS_DBG(4, "del controlling connection\n");
				ip_vs_conn_del(cp_c);
			}
    ...
}

The chain can also run from the timer softirq. If ip_vs_conn_unlink() fails because refcnt > 1, the expire_later path keeps timeout == 0 when n_control == 0:

net/netfilter/ipvs/ip_vs_conn.c:ip_vs_conn_expire() {
    ...
  expire_later:
    ...
	if (cp->timeout || atomic_read(&cp->n_control))
		cp->timeout = 60 * HZ;
    ...
	__ip_vs_conn_put_timer(cp);
}

The timer is then re-armed at jiffies + 0. The next callback walks the controller chain, and before this patch that walk recursed on the softirq stack.

The loop in ip_vs_conn_expire() covers all of these entry points, so the code change itself looks fine. Could the commit message also mention the runtime paths, since stable and CVE triage will rely on the stated impact?

The commit message also doesn't explain how a deep chain is built. The ip_vs_conn_expire_now() comment still says chains are at most DATA->CTL->TPL. Both points are handled by the follow-up patch in the series, "ipvs: reject FTP control ports as data ports". It rejects control ports as FTP data ports in ip_vs_ftp_out() and ip_vs_ftp_in(), which bounds the chain again.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#12 lore raw

PATCH 5/15 ipvs: reject FTP control ports as data ports

In reply to Pablo Neira Ayuso

From: Zihan Xi <[email protected]>

The FTP helper must not treat a configured control port as a data port. Accepting such a port can leave IPVS connections in a state that leads to recursive expiration and kernel stack exhaustion.

Reject zero and configured control ports before creating passive data connections. For active mode, reject a zero client port and a derived data port that is itself a configured control port.

---
 net/netfilter/ipvs/ip_vs_ftp.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
net/netfilter/ipvs/ip_vs_ftp.c +18 -0
index 9e3e005a8263..4822a1a75212 100644
@@ -62,6 +62,17 @@ static unsigned short ports[IP_VS_APP_MAX_PORTS] = {21, 0};
 module_param_array(ports, ushort, &ports_count, 0444);
 MODULE_PARM_DESC(ports, "Ports to monitor for FTP control commands");
 
+static bool is_control_port(u16 port)
+{
+	unsigned int i;
+
+	for (i = 0; i < ports_count; i++) {
+		if (ports[i] == port)
+			return true;
+	}
+	return false;
+}
+
 
 static char *ip_vs_ftp_data_ptr(struct sk_buff *skb, struct ip_vs_iphdr *ipvsh)
 {
@@ -319,6 +330,10 @@ static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp,
 		return 1;
 	}
 
+	/* Do not redirect data to control ports */
+	if (!port || is_control_port(ntohs(port)))
+		return 0;
+
 	/* Now update or create a connection entry for it */
 	{
 		struct ip_vs_conn_param p;
@@ -529,6 +544,9 @@ static int ip_vs_ftp_in(struct ip_vs_app *app, struct ip_vs_conn *cp,
 		return 1;
 	}
 
+	if (!port || is_control_port(ntohs(cp->vport) - 1))
+		return 0;
+
 	/* Passive mode off */
 	cp->app_data = (void *) IP_VS_FTP_ACTIVE;
 
Signature · 1 line
2.47.3
#13 lore raw

Re: [PATCH net 05/15] ipvs: reject FTP control ports as data ports

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 0

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] The two new rejection checks in ip_vs_ftp_in() and ip_vs_ftp_out() return 0.

--

ipvs: reject FTP control ports as data ports

This patch adds is_control_port() to the IPVS FTP helper and uses it to refuse a zero port, or a configured FTP control port, as a data port. ip_vs_ftp_out() refuses such ports in PASV/EPSV replies. ip_vs_ftp_in() refuses PORT/EPRT commands that carry a zero port, or where vport - 1 is a control port.

Quoted 4 lines
net/netfilter/ipvs/ip_vs_ftp.c +0 -0
index 9e3e005a82635..4822a1a75212d 100644

[ ... ]

Quoted 12 lines
net/netfilter/ipvs/ip_vs_ftp.c +4 -0
@@ -319,6 +330,10 @@ static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp,
 		return 1;
 	}
 
+	/* Do not redirect data to control ports */
+	if (!port || is_control_port(ntohs(port)))
+		return 0;
+
 	/* Now update or create a connection entry for it */
 	{
 		struct ip_vs_conn_param p;

net/netfilter/ipvs/ip_vs_ftp.c static int ip_vs_ftp_in(struct ip_vs_app *app, struct ip_vs_conn *cp, · line 549

Quoted 6 lines
net/netfilter/ipvs/ip_vs_ftp.c +3 -0
@@ -529,6 +544,9 @@ static int ip_vs_ftp_in(struct ip_vs_app *app, struct ip_vs_conn *cp,
 		return 1;
 	}
 
+	if (!port || is_control_port(ntohs(cp->vport) - 1))
+		return 0;
+

[Severity: Medium]
Does returning 0 here stall the whole FTP control connection, rather than only refusing the data connection?

The pkt_in/pkt_out contract in include/net/ip_vs.h treats 0 as an error:

Return: 0=Error, 1=Payload Not Mangled/Mangled but checksum is ok,

On the inbound side, tcp_dnat_handler() passes that result up:

    if (!(ret = ip_vs_app_pkt_in(cp, skb, iph)))
        return 0;

ip_vs_nat_xmit() then takes the tx_error path and frees the skb. The segment that carries the PORT/EPRT command is dropped.

cp->vport is fixed for the life of the connection, and ip_vs_ftp_in() keeps no state for this case. Every retransmission of that segment is parsed the same way and dropped again. Nothing after it in the TCP stream gets through until the client's TCP gives up (tcp_retries2).

If vport - 1 is also in the ports module parameter (for example ports=2120,2121), would active mode hang for every client of that service? A client that sends PORT/EPRT with port 0 would hang its own session the same way.

The check added to ip_vs_ftp_out() above behaves similarly. It returns 0 while cp->app_data is still IP_VS_FTP_PASV or IP_VS_FTP_EPSV, and tcp_snat_handler() passes that up:

    if (!(ret = ip_vs_app_pkt_out(cp, skb, iph)))
        return 0;

handle_response() then drops the 227/229 reply. The server retransmits it, the same port is parsed again, and the reply is dropped again.

The existing ret = 0 path at the end of ip_vs_ftp_out() sets cp->app_data = IP_VS_FTP_ACTIVE before it returns, so it never re-parses the reply. The ip_vs_conn_new() failure return is transient, which fits the existing "hopefully it will succeed on the retransmitted packet" comment. The new checks reject the same input every time.

Could ip_vs_ftp_in() return 1 here without creating the data connection, since nothing is mangled on that path anyway? And could ip_vs_ftp_out() set cp->app_data to IP_VS_FTP_ACTIVE before rejecting, so that only the data connection fails?

Quoted 3 lines
net/netfilter/ipvs/ip_vs_ftp.c +0 -0
 	/* Passive mode off */
 	cp->app_data = (void *) IP_VS_FTP_ACTIVE;
 
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#14 lore raw

PATCH 6/15 ipvs: ftp: skip conntrack templates in ip_vs_ftp_out

In reply to Pablo Neira Ayuso

From: Theodor Arsenij Larionov Trichkine <[email protected]>

A CT target hooked after conntrack attaches its template to a packet that conntrack left without an entry. On an IPVS FTP PASV/EPSV reply, ip_vs_ftp_out() then mangles with the template and creates an expectation with the template as master. Deleting the CT rule frees the template and leaves the expectation, so a later expectation flush reads freed memory:

  BUG: KASAN: slab-use-after-free in nf_ct_unlink_expect_report

Reachable with CAP_NET_ADMIN in a user namespace.

Skip templates, as nft_ct and nfnetlink_queue do.

Fixes f4bc17cdd205 ("ipvs: netfilter connection tracking changes")
---
 net/netfilter/ipvs/ip_vs_ftp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/netfilter/ipvs/ip_vs_ftp.c +1 -1
index 4822a1a75212..44de99f4d187 100644
@@ -383,7 +383,7 @@ static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp,
 	buf_len = strlen(buf);
 
 	ct = nf_ct_get(skb, &ctinfo);
-	if (ct) {
+	if (ct && !nf_ct_is_template(ct)) {
 		bool mangled;
 
 		/* If mangling fails this function will return 0
Signature · 1 line
2.47.3
author maintainer
#15 lore raw

PATCH 7/15 ipvs: ftp: add seqadj extension before linking the expectation

In reply to Pablo Neira Ayuso

From: Theodor Arsenij Larionov Trichkine <[email protected]>

ip_vs_ftp_out() links an expectation into the helper extension of the conntrack, then ip_vs_update_conntrack() adds the seqadj extension. If the conntrack is still unconfirmed, which happens when the real server's reply does not match an existing conntrack and creates a new one, krealloc() can move ct->ext and the expectation list keeps pointing into the freed area. Deleting the conntrack then writes to it:

  BUG: KASAN: slab-use-after-free in nf_ct_unlink_expect_report+0x490/0x4c0
  Write of size 8 at addr ffff888004dd4e48 by task syz.2.17/649

Reachable with CAP_NET_ADMIN in a user namespace.

Add the seqadj extension before mangling, so it is in place before the expectation is linked.

Fixes b25adce16064 ("ipvs: correct usage/allocation of seqadj ext in ipvs")
---
 net/netfilter/ipvs/ip_vs_ftp.c | 19 +++++++++++++------
 1 file changed, 13 insertions(+), 6 deletions(-)
net/netfilter/ipvs/ip_vs_ftp.c +13 -6
index 44de99f4d187..81c3a2fd27b3 100644
@@ -29,6 +29,7 @@
 #include <linux/netfilter.h>
 #include <net/netfilter/nf_conntrack.h>
 #include <net/netfilter/nf_conntrack_expect.h>
+#include <net/netfilter/nf_conntrack_seqadj.h>
 #include <net/netfilter/nf_nat.h>
 #include <net/netfilter/nf_nat_helper.h>
 #include <linux/gfp.h>
@@ -384,19 +385,25 @@ static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp,
 
 	ct = nf_ct_get(skb, &ctinfo);
 	if (ct && !nf_ct_is_template(ct)) {
-		bool mangled;
+		bool mangled = false;
 
 		/* If mangling fails this function will return 0
 		 * which will cause the packet to be dropped.
 		 * Mangling can only fail under memory pressure,
 		 * hopefully it will succeed on the retransmitted
 		 * packet.
+		 *
+		 * Add the seqadj extension before the expectation is
+		 * linked into the helper extension: adding it later
+		 * reallocates ct->ext under the expectation list.
 		 */
-		mangled = nf_nat_mangle_tcp_packet(skb, ct, ctinfo,
-						   ipvsh->len,
-						   start - data,
-						   end - start,
-						   buf, buf_len);
+		if (nf_ct_is_confirmed(ct) || nfct_seqadj(ct) ||
+		    nfct_seqadj_ext_add(ct))
+			mangled = nf_nat_mangle_tcp_packet(skb, ct, ctinfo,
+							   ipvsh->len,
+							   start - data,
+							   end - start,
+							   buf, buf_len);
 		if (mangled) {
 			ip_vs_nfct_expect_related(skb, ct, n_cp,
 						  ipvsh->protocol, 0, 0);
Signature · 1 line
2.47.3
#16 lore raw

Re: [PATCH net 07/15] ipvs: ftp: add seqadj extension before linking the expectation

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.

Critical: 0 · High: 1 · Medium: 0 · Low: 0

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [High] The fix is incomplete.

--

ipvs: ftp: add seqadj extension before linking the expectation

This patch adds the seqadj extension to an unconfirmed conntrack in ip_vs_ftp_out() before the payload is mangled and before the expectation is linked. The goal is to keep ip_vs_update_conntrack() from reallocating ct->ext while the helper's expectation list still points into it.

Quoted 4 lines
net/netfilter/ipvs/ip_vs_ftp.c +0 -0
index 44de99f4d187f..81c3a2fd27b39 100644

[ ... ]

Quoted 22 lines
net/netfilter/ipvs/ip_vs_ftp.c +5 -6
@@ -384,19 +385,25 @@ static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp,
 
 	ct = nf_ct_get(skb, &ctinfo);
 	if (ct && !nf_ct_is_template(ct)) {
-		bool mangled;
+		bool mangled = false;
 
 		/* If mangling fails this function will return 0
 		 * which will cause the packet to be dropped.
 		 * Mangling can only fail under memory pressure,
 		 * hopefully it will succeed on the retransmitted
 		 * packet.
+		 *
+		 * Add the seqadj extension before the expectation is
+		 * linked into the helper extension: adding it later
+		 * reallocates ct->ext under the expectation list.
 		 */
-		mangled = nf_nat_mangle_tcp_packet(skb, ct, ctinfo,
-						   ipvsh->len,
-						   start - data,
-						   end - start,
-						   buf, buf_len);

net/netfilter/ipvs/ip_vs_ftp.c static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp, · line 409

Quoted 10 lines
net/netfilter/ipvs/ip_vs_ftp.c +7 -0
+		if (nf_ct_is_confirmed(ct) || nfct_seqadj(ct) ||
+		    nfct_seqadj_ext_add(ct))
+			mangled = nf_nat_mangle_tcp_packet(skb, ct, ctinfo,
+							   ipvsh->len,
+							   start - data,
+							   end - start,
+							   buf, buf_len);
 		if (mangled) {
 			ip_vs_nfct_expect_related(skb, ct, n_cp,
 						  ipvsh->protocol, 0, 0);

[Severity: High]
Does this fully close the use-after-free? The expectation is still linked into nfct_help(ct)->expectations while ct is unconfirmed, and that list head lives inside ct->ext. Pre-adding seqadj only stops one later extension add from moving ct->ext.

nf_ct_expect_insert() does:

    hlist_add_head_rcu(&exp->lnode, &master_help->expectations);

so exp->lnode.pprev now points into the current ct->ext block.

Later hooks on the same packet can still grow ct->ext. One example is a MASQUERADE rule in POSTROUTING, which runs for this IP_CT_NEW conntrack after the IPVS out hook:

nf_nat_inet_fn()

    nf_nat_masquerade_ipv4()
      nf_ct_nat_ext_add()
        nf_ct_ext_add(ct, NF_CT_EXT_NAT, GFP_ATOMIC)
          krealloc(ct->ext, alloc, gfp)

Here is one layout where this moves the block. With CONFIG_NF_CONNTRACK_TIMESTAMP=y and an ecache extension present (nf_conntrack_events=1), the extensions are header 16, ecache 32, help 56 and seqadj 24. That adds up to exactly 128 bytes, which is the NF_CT_EXT_PREALLOC object size. Adding NAT gives a newlen of 132-136. __do_krealloc() then goes to alloc_new and the old block is freed. nf_conntrack_acct=1 gives the same arithmetic.

After that, ext->help.expectations.first in the new block points to exp->lnode. But exp->lnode.pprev still points into the freed block. When the expectation or conntrack is removed, nf_ct_unlink_expect_report() calls:

    hlist_del_rcu(&exp->lnode);

This writes through the stale pprev, which looks like the same KASAN report quoted in the commit message. In this layout the seqadj add would not have moved the block even before the patch, so the patch does not help in this case.

Other extension adds on an unconfirmed ct are also reachable later in the same traversal:

nft_ct_set_eval() with NFT_CT_EVENTMASK -> nf_ct_ecache_ext_add() nft_ct_timeout_obj_eval() -> nf_ct_timeout_ext_add()

The commit message says this is reachable with CAP_NET_ADMIN in a user namespace. That context can configure MASQUERADE, nft ct rules, the acct sysctl and ctnetlink listeners.

Would it be better to not link the expectation while the conntrack's ext can still grow? Two options are deferring the link until confirmation, or making ct->ext stable first. Pre-adding one more extension does not seem to cover these other paths.

None of the later patches in the series appear to touch ip_vs_ftp.c, ip_vs_nfct.c, nf_conntrack_extend.c, nf_nat_core.c, nf_nat_masquerade.c or nf_conntrack_expect.c.

Quoted 2 lines
net/netfilter/ipvs/ip_vs_ftp.c +0 -0
 			if (skb->ip_summed == CHECKSUM_COMPLETE)
 				skb->ip_summed = CHECKSUM_UNNECESSARY;

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#17 lore raw

PATCH 8/15 ipvs: update flags and seqs in backup server under lock

In reply to Pablo Neira Ayuso

From: Julian Anastasov <[email protected]>

Sashiko reports that we modify the conn flags and seq values in the backup server without holding cp->lock. The same is true for other fields such as state, old_state and timeout which are modified by protocols under lock.

Extend the locked region in ip_vs_proc_conn() to update the fields atomically.

---
 net/netfilter/ipvs/ip_vs_sync.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
net/netfilter/ipvs/ip_vs_sync.c +6 -3
index 1caacf419af9..ba2fa1f9d08e 100644
@@ -850,6 +850,7 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa
 			    unsigned long timeout, __u32 fwmark,
 			    struct ip_vs_sync_conn_options *opt)
 {
+	struct ip_vs_conn *cp_new = NULL;
 	struct ip_vs_dest *dest;
 	struct ip_vs_conn *cp;
 
@@ -891,9 +892,6 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa
 		flags &= IP_VS_CONN_F_BACKUP_UPD_MASK;
 		flags |= cp->flags & ~IP_VS_CONN_F_BACKUP_UPD_MASK;
 		cp->flags = flags;
-		spin_unlock_bh(&cp->lock);
-		if (!dest)
-			ip_vs_try_bind_dest(cp);
 	} else {
 		/*
 		 * Find the appropriate destination for the connection.
@@ -920,6 +918,8 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa
 		}
 		if (!(flags & IP_VS_CONN_F_TEMPLATE))
 			kfree(param->pe_data);
+		cp_new = cp;
+		spin_lock_bh(&cp->lock);
 	}
 
 	if (opt) {
@@ -951,6 +951,9 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa
 		else
 			cp->timeout = (3*60*HZ);
 	}
+	spin_unlock_bh(&cp->lock);
+	if (!dest && !cp_new)
+		ip_vs_try_bind_dest(cp);
 	ip_vs_conn_put(cp);
 }
 
Signature · 1 line
2.47.3
#18 lore raw

Re: [PATCH net 08/15] ipvs: update flags and seqs in backup server under lock

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] The commit message overstates the old bug.

--

ipvs: update flags and seqs in backup server under lock

This patch extends the cp->lock critical section in ip_vs_proc_conn(). On the backup server, cp->flags, in_seq/out_seq, state, old_state and timeout are now updated together. New connections also take cp->lock, and ip_vs_try_bind_dest() is called after the lock is dropped.

Quoted 4 lines

Sashiko reports that we modify the conn flags and seq values in the backup server without holding cp->lock. The same is true for other fields such as state, old_state and timeout which are modified by protocols under lock.

[Severity: Low]
Is the first sentence accurate for cp->flags?

Before this patch, the existing-connection path in ip_vs_proc_conn() already updated cp->flags under cp->lock:

net/netfilter/ipvs/ip_vs_sync.c:ip_vs_proc_conn() {
    ...
		spin_lock_bh(&cp->lock);
		...
		flags &= IP_VS_CONN_F_BACKUP_UPD_MASK;
		flags |= cp->flags & ~IP_VS_CONN_F_BACKUP_UPD_MASK;
		cp->flags = flags;
		spin_unlock_bh(&cp->lock);
		if (!dest)
			ip_vs_try_bind_dest(cp);
    ...
}

ip_vs_try_bind_dest() also takes cp->lock before ip_vs_bind_dest() changes cp->flags.

The fields written without the lock were the seqs, state, old_state and timeout, after spin_unlock_bh():

	if (opt) {
		cp->in_seq = opt->in_seq;
		cp->out_seq = opt->out_seq;
	}
	atomic_set(&cp->in_pkts, sysctl_sync_threshold(ipvs));
	cp->state = state;
	cp->old_state = cp->state;

So the IP_VS_CONN_F_SEQ_MASK bits were set under the lock, but the in_seq/out_seq values they describe were written outside it. The subject line and "update the fields atomically" describe this correctly.

Could the first sentence say that flags and seqs were not updated together under the lock, instead of saying the flags were modified without it? The code change itself looks correct.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#19 lore raw

PATCH 9/15 ipvs: read flags and seqs in master atomically

In reply to Pablo Neira Ayuso

From: Julian Anastasov <[email protected]>

After we fixed the double read of cp->flags in the master with commit 3e3fe49e8678 ("ipvs: fix buffer overflow when sending sync messages") Sashiko reports that we should also read the cp->flags and the seqs atomically. So if the SEQ_MASK is set, re-read the flags and the seqs under cp->lock to provide a snapshot when sending the sync message.

Fixes 3e3fe49e8678 ("ipvs: fix buffer overflow when sending sync messages")
Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 net/netfilter/ipvs/ip_vs_sync.c | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)
net/netfilter/ipvs/ip_vs_sync.c +20 -3
index ba2fa1f9d08e..f11c59eca553 100644
@@ -539,6 +539,7 @@ static int ip_vs_sync_conn_needed(struct netns_ipvs *ipvs,
 static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp,
 			       int pkts)
 {
+	struct ip_vs_sync_conn_options opts;
 	struct ip_vs_sync_mesg_v0 *m;
 	struct ip_vs_sync_conn_v0 *s;
 	struct ip_vs_sync_buff *buff;
@@ -557,6 +558,14 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp,
 	if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
 		return;
 
+	if (flags & IP_VS_CONN_F_SEQ_MASK) {
+		/* Take atomic snapshot of flags and seqs */
+		spin_lock_bh(&cp->lock);
+		flags = cp->flags;
+		memcpy(&opts, &cp->sync_conn_opt, sizeof(opts));
+		spin_unlock_bh(&cp->lock);
+	}
+
 	spin_lock_bh(&ipvs->sync_buff_lock);
 	if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
 		spin_unlock_bh(&ipvs->sync_buff_lock);
@@ -604,7 +613,7 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp,
 	if (seq_mask) {
 		struct ip_vs_sync_conn_options *opt =
 			(struct ip_vs_sync_conn_options *)&s[1];
-		memcpy(opt, &cp->sync_conn_opt, sizeof(*opt));
+		memcpy(opt, &opts, sizeof(*opt));
 	}
 
 	m->nr_conns++;
@@ -630,6 +639,7 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp,
  */
 void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts)
 {
+	struct ip_vs_sync_conn_options opts;
 	struct ip_vs_sync_mesg *m;
 	union ip_vs_sync_conn *s;
 	struct ip_vs_sync_buff *buff;
@@ -651,6 +661,13 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts)
 	if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
 		goto control;
 	flags = READ_ONCE(cp->flags);
+	if (flags & IP_VS_CONN_F_SEQ_MASK) {
+		/* Take atomic snapshot of flags and seqs */
+		spin_lock_bh(&cp->lock);
+		flags = cp->flags;
+		memcpy(&opts, &cp->sync_conn_opt, sizeof(opts));
+		spin_unlock_bh(&cp->lock);
+	}
 
 	/* Sanity checks */
 	pe_name_len = 0;
@@ -752,9 +769,9 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts)
 	if (seq_mask) {
 		*(p++) = IPVS_OPT_SEQ_DATA;
 		*(p++) = sizeof(struct ip_vs_sync_conn_options);
-		hton_seq(&cp->in_seq, (struct ip_vs_seq *)p);
+		hton_seq(&opts.in_seq, (struct ip_vs_seq *)p);
 		p += sizeof(struct ip_vs_seq);
-		hton_seq(&cp->out_seq, (struct ip_vs_seq *)p);
+		hton_seq(&opts.out_seq, (struct ip_vs_seq *)p);
 		p += sizeof(struct ip_vs_seq);
 	}
 	/* Handle pe data */
Signature · 1 line
2.47.3
author maintainer
#20 lore raw

PATCH 10/15 ipvs: honor the overload state and do not enter it forever

In reply to Pablo Neira Ayuso

From: Julian Anastasov <[email protected]>

Sashiko warns that we may enter the dest overload state forever if setting the u_threshold to 1 races with the ip_vs_unbind_dest() call for the last connection for dest. The problem is that we prefer ip_vs_unbind_dest() to avoid using locks while reading the threshold.

To avoid the race, add a smp_mb() in __ip_vs_dest_update_overload() that is paired with the atomic_fetch_dec() in ip_vs_unbind_dest() which allows to re-read the totalconns and to leave the overload state if we are below l_threshold_val.

Also, remove the overload parameter from ip_vs_dest_update_overload() because we just need to know the current state while deciding which threshold ranges to use. This ip_vs_dest_is_overloaded() check can be in __ip_vs_dest_update_overload() instead.

To avoid ip_vs_bind_dest() to enter lock just to initialize u_threshold_val to INT_MAX, do it in ip_vs_new_dest().

The LBLC and LBLCR schedulers do not honor the global overload state for cached dests, so add a ip_vs_dest_is_overloaded() check for the situations where we may fallback from overloaded dest (LBLC and LBLCR) or when we hit a cached dest (LBLC).

Also, move the ip_vs_dest_set_min() call in LBLCR after the ip_vs_dest_set_erase() call that removes the most-loaded server because due to races we may work with dest that is in process of removing, i.e. ip_vs_dest_set_min() and ip_vs_dest_set_max() may return same dest.

Fixes 3ba20137287f ("ipvs: fix more races around the overload flag")
Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 include/net/ip_vs.h              |  2 +-
 net/netfilter/ipvs/ip_vs_conn.c  |  4 ++--
 net/netfilter/ipvs/ip_vs_ctl.c   | 30 ++++++++++++++++++------------
 net/netfilter/ipvs/ip_vs_lblc.c  |  8 +++++---
 net/netfilter/ipvs/ip_vs_lblcr.c | 13 +++++++------
 5 files changed, 33 insertions(+), 24 deletions(-)
include/net/ip_vs.h +1 -1
index 97097d60d1c4..c1f7a3f144f1 100644
@@ -1922,7 +1922,7 @@ static inline void ip_vs_dest_put_and_free(struct ip_vs_dest *dest)
 		kfree(dest);
 }
 
-void ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload);
+void ip_vs_dest_update_overload(struct ip_vs_dest *dest);
 
 /* Check if dest is in overloaded state */
 static inline bool ip_vs_dest_is_overloaded(const struct ip_vs_dest *dest)
net/netfilter/ipvs/ip_vs_conn.c +2 -2
index 27db8d558a03..66fcdc00ef37 100644
@@ -1168,7 +1168,7 @@ ip_vs_bind_dest(struct ip_vs_conn *cp, struct ip_vs_dest *dest)
 			atomic_inc(&dest->activeconns);
 		tc = atomic_inc_return(&dest->totalconns);
 		if (tc >= READ_ONCE(dest->u_threshold_val))
-			ip_vs_dest_update_overload(dest, true);
+			ip_vs_dest_update_overload(dest);
 	} else {
 		/* It is a persistent connection/template, so increase
 		   the persistent connection counter */
@@ -1261,7 +1261,7 @@ static inline void ip_vs_unbind_dest(struct ip_vs_conn *cp)
 			atomic_dec(&dest->activeconns);
 		tc = atomic_fetch_dec(&dest->totalconns);
 		if (tc <= READ_ONCE(dest->l_threshold_val))
-			ip_vs_dest_update_overload(dest, false);
+			ip_vs_dest_update_overload(dest);
 	} else {
 		/* It is a persistent connection/template, so decrease
 		   the persistent connection counter */
net/netfilter/ipvs/ip_vs_ctl.c +18 -12
index ce9fe20d6106..5868adda6ed6 100644
@@ -1304,12 +1304,12 @@ void ip_vs_stats_free(struct ip_vs_stats *stats)
 	}
 }
 
-/* Update overload flag based on number of dest conns and lower/upper
+/* Update overload state based on number of dest conns and lower/upper
  * connection thresholds:
- * - conns reach u_threshold and exceed it: set the flag
- * - conns go below l_threshold (or 75% of u_threshold): clear the flag
+ * - conns reach u_threshold and exceed it: set the overload state
+ * - conns go below l_threshold (or 75% of u_threshold): clear the state
  */
-static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload)
+static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest)
 {
 	int conns;
 	u32 l, u;
@@ -1320,10 +1320,18 @@ static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload)
 		/* Low threshold defaults to 75% of upper threshold */
 		l = READ_ONCE(dest->l_threshold) ? : (u - (u >> 2));
 		conns = atomic_read(&dest->totalconns);
-		if (conns >= (overload ? l : u)) {
+		if (conns >= (ip_vs_dest_is_overloaded(dest) ? l : u)) {
 			WRITE_ONCE(dest->u_threshold_val, INT_MAX);
 			WRITE_ONCE(dest->l_threshold_val, l);
-			return;
+			/* Commit thresholds before repeating the check,
+			 * it is paired with atomic_fetch_dec() in
+			 * ip_vs_unbind_dest() to avoid entering the
+			 * overload state forever.
+			 */
+			smp_mb();
+			conns = atomic_read(&dest->totalconns);
+			if (conns >= l)
+				return;
 		}
 	}
 
@@ -1331,10 +1339,10 @@ static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload)
 	WRITE_ONCE(dest->l_threshold_val, 0);
 }
 
-void ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload)
+void ip_vs_dest_update_overload(struct ip_vs_dest *dest)
 {
 	spin_lock_bh(&dest->dst_lock);
-	__ip_vs_dest_update_overload(dest, overload);
+	__ip_vs_dest_update_overload(dest);
 	spin_unlock_bh(&dest->dst_lock);
 }
 
@@ -1406,13 +1414,10 @@ __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest,
 
 	if (READ_ONCE(dest->u_threshold) != udest->u_threshold ||
 	    READ_ONCE(dest->l_threshold) != udest->l_threshold) {
-		bool overload;
-
 		spin_lock_bh(&dest->dst_lock);
 		WRITE_ONCE(dest->u_threshold, udest->u_threshold);
 		WRITE_ONCE(dest->l_threshold, udest->l_threshold);
-		overload = ip_vs_dest_is_overloaded(dest);
-		__ip_vs_dest_update_overload(dest, overload);
+		__ip_vs_dest_update_overload(dest);
 		spin_unlock_bh(&dest->dst_lock);
 	}
 
@@ -1477,6 +1482,7 @@ ip_vs_new_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
 	if (ret < 0)
 		goto err_stats;
 
+	dest->u_threshold_val = INT_MAX;
 	dest->af = udest->af;
 	dest->protocol = svc->protocol;
 	dest->vaddr = svc->addr;
net/netfilter/ipvs/ip_vs_lblc.c +5 -3
index e1111c3b2721..f5ce1f2afb86 100644
@@ -467,10 +467,11 @@ is_overloaded(struct ip_vs_dest *dest, struct ip_vs_service *svc)
 		struct ip_vs_dest *d;
 
 		list_for_each_entry_rcu(d, &svc->destinations, n_list) {
-			if (atomic_read(&d->activeconns)*2
-			    < atomic_read(&d->weight)) {
+			if (ip_vs_dest_is_overloaded(d))
+				continue;
+			if (atomic_read(&d->activeconns) * 2 <
+			    atomic_read(&d->weight))
 				return 1;
-			}
 		}
 	}
 	return 0;
@@ -507,6 +508,7 @@ ip_vs_lblc_schedule(struct ip_vs_service *svc, const struct sk_buff *skb,
 
 		dest = en->dest;
 		if ((dest->cflags & IP_VS_DEST_CF_AVAILABLE) &&
+		    !ip_vs_dest_is_overloaded(dest) &&
 		    atomic_read(&dest->weight) > 0 && !is_overloaded(dest, svc))
 			goto out;
 	}
net/netfilter/ipvs/ip_vs_lblcr.c +7 -6
index dfb5bf83750d..4046608922e7 100644
@@ -630,10 +630,11 @@ is_overloaded(struct ip_vs_dest *dest, struct ip_vs_service *svc)
 		struct ip_vs_dest *d;
 
 		list_for_each_entry_rcu(d, &svc->destinations, n_list) {
-			if (atomic_read(&d->activeconns)*2
-			    < atomic_read(&d->weight)) {
+			if (ip_vs_dest_is_overloaded(d))
+				continue;
+			if (atomic_read(&d->activeconns) * 2 <
+			    atomic_read(&d->weight))
 				return 1;
-			}
 		}
 	}
 	return 0;
@@ -658,9 +659,6 @@ ip_vs_lblcr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb,
 	if (en) {
 		en->lastuse = jiffies;
 
-		/* Get the least loaded destination */
-		dest = ip_vs_dest_set_min(&en->set);
-
 		/* More than one destination + enough time passed by, cleanup */
 		if (atomic_read(&en->set.size) > 1 &&
 		    time_after(jiffies, en->set.lastmod +
@@ -676,6 +674,9 @@ ip_vs_lblcr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb,
 			spin_unlock_bh(&svc->sched_lock);
 		}
 
+		/* Get the least loaded destination */
+		dest = ip_vs_dest_set_min(&en->set);
+
 		/* If the destination is not overloaded, use it */
 		if (dest && !is_overloaded(dest, svc))
 			goto out;
Signature · 1 line
2.47.3
#21 lore raw

Re: [PATCH net 10/15] ipvs: honor the overload state and do not enter it forever

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] The commit message's reason for moving ip_vs_dest_set_min() after the set_max/erase cleanup in ip_vs_lblcr_schedule()…

--

ipvs: honor the overload state and do not enter it forever

This commit adds an smp_mb() and a re-read of totalconns in __ip_vs_dest_update_overload(), so a dest cannot stay in the overload state forever when it races with ip_vs_unbind_dest(). It also drops the overload parameter from ip_vs_dest_update_overload() and makes LBLC and LBLCR honor the overload state for cached dests. In LBLCR it moves the ip_vs_dest_set_min() call to after the set_max/erase cleanup.

Quoted 4 lines
net/netfilter/ipvs/ip_vs_lblcr.c +0 -0
index dfb5bf83750db..4046608922e7c 100644

[ ... ]

Quoted 11 lines
net/netfilter/ipvs/ip_vs_lblcr.c +0 -3
@@ -658,9 +659,6 @@ ip_vs_lblcr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb,
 	if (en) {
 		en->lastuse = jiffies;
 
-		/* Get the least loaded destination */
-		dest = ip_vs_dest_set_min(&en->set);
-
 		/* More than one destination + enough time passed by, cleanup */
 		if (atomic_read(&en->set.size) > 1 &&
 		    time_after(jiffies, en->set.lastmod +

net/netfilter/ipvs/ip_vs_lblcr.c ip_vs_lblcr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, · line 682

Quoted 9 lines
net/netfilter/ipvs/ip_vs_lblcr.c +3 -0
@@ -676,6 +674,9 @@ ip_vs_lblcr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb,
 			spin_unlock_bh(&svc->sched_lock);
 		}
 
+		/* Get the least loaded destination */
+		dest = ip_vs_dest_set_min(&en->set);
+
 		/* If the destination is not overloaded, use it */
 		if (dest && !is_overloaded(dest, svc))
 			goto out;

[Severity: Low]
This isn't a bug, and the code change looks right. The commit message explains the move this way:

"Also, move the ip_vs_dest_set_min() call in LBLCR after the ip_vs_dest_set_erase() call that removes the most-loaded server because due to races we may work with dest that is in process of removing, i.e. ip_vs_dest_set_min() and ip_vs_dest_set_max() may return same dest."

Can the two helpers also return the same dest without any race?

ip_vs_dest_set_min() only replaces its candidate when another member is strictly less loaded:

    if (((__s64)loh * atomic_read(&dest->weight) >
         (__s64)doh * atomic_read(&least->weight)) &&
        (dest->cflags & IP_VS_DEST_CF_AVAILABLE)) {

ip_vs_dest_set_max() only replaces its candidate when another member is strictly more loaded:

    if (((__s64)moh * atomic_read(&dest->weight) <
         (__s64)doh * atomic_read(&most->weight))
        && (atomic_read(&dest->weight) > 0)) {

Take two weight-1 members with the same ip_vs_dest_conn_overhead(), for example both idle. Both helpers then return the first list element.

Before this patch, once the set had more than one member and was older than sysctl_lblcr_expiration, the sequence was:

ip_vs_lblcr_schedule()

    ip_vs_dest_set_min()     -> first member (tie)
    ip_vs_dest_set_max()     -> same first member (tie)
    ip_vs_dest_set_erase()   -> removes it from en->set
    goto out                 -> returns the erased dest

So on load ties the old code returned the dest it had just removed from the cache set, with no race involved.

Could the commit message say that this also happens on ties, not only because of races?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#22 lore raw

PATCH 11/15 ipvs: validate cport in received sync records

In reply to Pablo Neira Ayuso

From: Axel Mierczuk <[email protected]>

Local templates have cport 0 and IP_VS_CONN_F_NO_CPORT clear, so ip_vs_conn_in_get() cannot match them. A template received over the unauthenticated sync protocol with a nonzero cport can reach the protocol state machine. Before template state validation, this could cause out-of-bounds reads, crashes and kernel data leaks.

Ordinary records with cport 0 and IP_VS_CONN_F_NO_CPORT clear, or with a nonzero cport and IP_VS_CONN_F_NO_CPORT set, create connections that incoming lookups cannot match. The latter also keeps the cport-zero fallback in ip_vs_conn_in_get() enabled.

Reject all three cases. Continue accepting ordinary connections with cport 0 and IP_VS_CONN_F_NO_CPORT. The companion commit f96e91748f63 ("ipvs: filter some flags received in the backup server") rejects template records carrying IP_VS_CONN_F_NO_CPORT.

Fixes 87375ab47cd0 ("[IPVS]: ip_vs_ftp breaks connections using persistence")
---
 net/netfilter/ipvs/ip_vs_sync.c | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
net/netfilter/ipvs/ip_vs_sync.c +19 -0
index f11c59eca553..7e562e745ab5 100644
@@ -871,6 +871,25 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa
 	struct ip_vs_dest *dest;
 	struct ip_vs_conn *cp;
 
+	/* Templates require cport 0. Ordinary connections require
+	 * NO_CPORT exactly when cport is 0.
+	 */
+	if (flags & IP_VS_CONN_F_TEMPLATE) {
+		if (param->cport) {
+			IP_VS_DBG(2, "BACKUP, template with cport dropped\n");
+			kfree(param->pe_data);
+			return;
+		}
+	} else if (!param->cport && !(flags & IP_VS_CONN_F_NO_CPORT)) {
+		IP_VS_DBG(2, "BACKUP, conn without cport dropped\n");
+		kfree(param->pe_data);
+		return;
+	} else if (param->cport && (flags & IP_VS_CONN_F_NO_CPORT)) {
+		IP_VS_DBG(2, "BACKUP, conn with cport and NO_CPORT dropped\n");
+		kfree(param->pe_data);
+		return;
+	}
+
 	if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
 		cp = ip_vs_conn_in_get(param);
 		if (cp && ((cp->dport != dport) ||
Signature · 1 line
2.47.3
#23 lore raw

Re: [PATCH net 11/15] ipvs: validate cport in received sync records

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] This patch has Cc: [email protected], but on its own it does not stop synced templates from being matched by ip_vs_conn_in_get().
- [Low] The new backup check in ip_vs_proc_conn() drops every non- template record with a nonzero cport and IP_VS_CONN_F_NO_CPORT set.

--

ipvs: validate cport in received sync records

This commit adds checks to ip_vs_proc_conn() that drop received sync records whose cport and IP_VS_CONN_F_NO_CPORT combination is inconsistent. Three cases are rejected: templates with a nonzero cport, ordinary connections with cport 0 and NO_CPORT clear, and ordinary connections with a nonzero cport and NO_CPORT set.

Quoted 7 lines
net/netfilter/ipvs/ip_vs_sync.c +0 -0
index f11c59eca5536..7e562e745ab5d 100644
@@ -871,6 +871,25 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa
 	struct ip_vs_dest *dest;
 	struct ip_vs_conn *cp;

net/netfilter/ipvs/ip_vs_sync.c static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa · line 882

Quoted 10 lines
net/netfilter/ipvs/ip_vs_sync.c +9 -0
 
+	/* Templates require cport 0. Ordinary connections require
+	 * NO_CPORT exactly when cport is 0.
+	 */
+	if (flags & IP_VS_CONN_F_TEMPLATE) {
+		if (param->cport) {
+			IP_VS_DBG(2, "BACKUP, template with cport dropped\n");
+			kfree(param->pe_data);
+			return;
+		}

[Severity: Low]

This patch carries Cc: stable, but for templates it only rejects a nonzero cport. A template with cport 0 and IP_VS_CONN_F_NO_CPORT set still passes this check.

That combination is rejected only by ip_vs_sync_validate_flags(), which is added by f96e91748f63 ("ipvs: filter some flags received in the backup server"):

    if (flags & IP_VS_CONN_F_NO_CPORT) {
        if (flags & IP_VS_CONN_F_TEMPLATE)
            return false;
    }

That commit has a Fixes: tag but no Cc: stable.

Suppose a stable tree picks up only this patch. Can an unauthenticated sync message then still install a template with TEMPLATE | NO_CPORT and cport 0? ip_vs_conn_new() would raise no_cport_conns. The cport-zero fallback in ip_vs_conn_in_get() would then match that template for any client source port:

    if (atomic_read(&ipvs->no_cport_conns[af_id])) {
        struct ip_vs_conn_param cport_zero_p = *p;

        cport_zero_p.cport = 0;
        cp = __ip_vs_conn_in_get(&cport_zero_p);
    }

This happens because !p->cport ^ !(cp->flags & IP_VS_CONN_F_NO_CPORT) evaluates to true in __ip_vs_conn_in_get().

Mainline is not affected, because f96e91748f63 is already an ancestor. In stable, the out-of-bounds part is covered by 74cb39735b6c ("ipvs:
reject invalid states in connection template sync records"). The two commits share the same Fixes: target, so stable tooling may pick up f96e91748f63 anyway.

The commit message calls f96e91748f63 a "companion commit". Would it help to state the backport dependency explicitly, for example:

    Cc: [email protected] # depends on f96e91748f63

net/netfilter/ipvs/ip_vs_sync.c static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa · line 891

Quoted 9 lines
net/netfilter/ipvs/ip_vs_sync.c +9 -0
+	} else if (!param->cport && !(flags & IP_VS_CONN_F_NO_CPORT)) {
+		IP_VS_DBG(2, "BACKUP, conn without cport dropped\n");
+		kfree(param->pe_data);
+		return;
+	} else if (param->cport && (flags & IP_VS_CONN_F_NO_CPORT)) {
+		IP_VS_DBG(2, "BACKUP, conn with cport and NO_CPORT dropped\n");
+		kfree(param->pe_data);
+		return;
+	}

[Severity: Low]

Can a legitimate in-tree master send a nonzero cport with NO_CPORT still set for an ordinary connection? The new comment says ordinary connections require NO_CPORT exactly when cport is 0. However, ip_vs_conn_fill_cport() updates the two fields in separate passes:

net/netfilter/ipvs/ip_vs_conn.c:ip_vs_conn_fill_cport() {
    ...
	if (cp->flags & IP_VS_CONN_F_NO_CPORT && (!cp->cport || by_me)) {
		...
		if (!cp->cport) {
			cp->cport = cport;
			by_me = true;
		}
		if (!dir) {
			atomic_dec(&ipvs->no_cport_conns[af_id]);
			cp->flags &= ~IP_VS_CONN_F_NO_CPORT;
		}
    ...
	spin_unlock_bh(&cp->lock);
	if (dir-- && by_me)
		goto next_dir;
}

The dir=1 pass sets cp->cport and releases cp->lock. Only the dir=0 pass clears NO_CPORT.

On the sending side, ip_vs_sync_conn() reads the flags with READ_ONCE(cp->flags). It takes cp->lock only when IP_VS_CONN_F_SEQ_MASK is set. Later it copies s->v4.cport = cp->cport without the lock. ip_vs_sync_conn_v0() copies s->cport = cp->cport the same way.

Consider a NO_CPORT FTP data connection under MASQ. One CPU can be in ip_vs_nat_xmit()->ip_vs_conn_fill_cport() between the two passes while another CPU syncs the connection. The record would then carry a nonzero cport with NO_CPORT still set, and this new branch would drop it.

The impact looks small. Before this patch, the backup would have created a connection that incoming lookups could not match anyway, and later syncs carry consistent flags.

Should the comment and the debug message be adjusted? This state can come from an in-tree master, so it does not necessarily mean the peer misbehaved.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#24 lore raw

PATCH 12/15 ipvs: skip cport 0 connections in ip_vs_conn_out_get()

In reply to Pablo Neira Ayuso

From: Axel Mierczuk <[email protected]>

ip_vs_conn_out_get() does not filter templates. A template with cport 0 is matched by a packet sent to client port 0 that traverses the out hook, and handle_response() then runs ip_vs_set_state() and the timeout update on a connection that must never see packets. A backup server receives such templates over the unauthenticated sync protocol. An ordinary connection scheduled for a client that uses source port 0 has cport 0 as well and is matched the same way.

Apply the rule used by __ip_vs_conn_in_get(): a lookup for client port 0 matches only connections flagged IP_VS_CONN_F_NO_CPORT, which still wait for their cport, and a lookup for a nonzero client port matches only connections without this flag. Test p->vport, which was already compared with cp->cport, instead of reading cp->cport again.

ip_vs_ftp_out() relies on the first case: it looks up the data connection with client port 0 to find the IP_VS_CONN_F_NO_CPORT entry created for an earlier PASV or EPSV reply. That lookup keeps working.

---
 net/netfilter/ipvs/ip_vs_conn.c | 2 ++
 1 file changed, 2 insertions(+)
net/netfilter/ipvs/ip_vs_conn.c +2 -0
index 66fcdc00ef37..83d8a9153a34 100644
@@ -590,6 +590,8 @@ struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p)
 				    ip_vs_addr_equal(p->af, p->vaddr,
 						     &cp->caddr) &&
 				    ip_vs_addr_equal(p->af, p->caddr, saddr) &&
+				    (!p->vport ^
+				     (!(cp->flags & IP_VS_CONN_F_NO_CPORT))) &&
 				    p->protocol == cp->protocol) {
 					if (__ip_vs_conn_get(cp))
 						goto out;
Signature · 1 line
2.47.3
#25 lore raw

Re: [PATCH net 12/15] ipvs: skip cport 0 connections in ip_vs_conn_out_get()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 0

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] ip_vs_conn_out_get() (net/netfilter/ipvs/ip_vs_conn.c:593-594) now copies the symmetric rule from __ip_vs_conn_in_get(): `(!p->vport…

--

ipvs: skip cport 0 connections in ip_vs_conn_out_get()

This patch adds the rule from __ip_vs_conn_in_get() to ip_vs_conn_out_get(). A lookup for client port 0 matches only connections flagged IP_VS_CONN_F_NO_CPORT, and a lookup for a nonzero client port matches only connections without that flag. The goal is to stop templates and ordinary cport 0 connections from being matched on the out path.

net/netfilter/ipvs/ip_vs_conn.c struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p) · line 594

Quoted 10 lines
net/netfilter/ipvs/ip_vs_conn.c +2 -0
index 66fcdc00ef375..83d8a9153a342 100644
@@ -590,6 +590,8 @@ struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p)
 				    ip_vs_addr_equal(p->af, p->vaddr,
 						     &cp->caddr) &&
 				    ip_vs_addr_equal(p->af, p->caddr, saddr) &&
+				    (!p->vport ^
+				     (!(cp->flags & IP_VS_CONN_F_NO_CPORT))) &&

[Severity: Medium]

Can the nonzero p->vport half of this check make the out lookup miss a MASQ connection while ip_vs_conn_fill_cport() is still filling it?

For double-hashed connections (ip_vs_conn_use_hash2(): MASQ and not a template), ip_vs_conn_fill_cport() works in two separately locked passes. The first pass is dir 1:

net/netfilter/ipvs/ip_vs_conn.c:ip_vs_conn_fill_cport() {
    ...
	/* No packets from inside, so we can do it in 2 steps. */
	dir = use2 ? 1 : 0;
    ...
		if (!cp->cport) {
			cp->cport = cport;
			by_me = true;
		}
		if (!dir) {
			atomic_dec(&ipvs->no_cport_conns[af_id]);
			cp->flags &= ~IP_VS_CONN_F_NO_CPORT;
		}
    ...
			hlist_bl_del_rcu(&hn->node);
			hlist_bl_add_head_rcu(&hn->node, head_new);
    ...
	spin_unlock_bh(&cp->lock);
	if (dir-- && by_me)
		goto next_dir;
}

After the dir 1 pass, cp->cport is set and hn1 (the node walked by ip_vs_conn_out_get()) sits in the bucket for the new cport. But IP_VS_CONN_F_NO_CPORT stays set until the dir 0 pass, and all locks are dropped between the two passes.

Before this patch, an out lookup in that window matched on cport alone. With the new check, p->vport is nonzero and the flag is still set, so the expression is 0 ^ 0 and the entry is skipped. Nothing else in ip_vs_conn_out_get() would find the connection.

One sequence that seems possible with an FTP PASV/EPSV data connection, which is created with IP_VS_CONN_F_NO_CPORT:

CPU A and CPU B each handle a client packet for the data connection. Both find it through the cport 0 fallback in ip_vs_conn_in_get().

CPU A
ip_vs_nat_xmit()
ip_vs_conn_fill_cport()
dir 1 pass done: cport set, hn1 rehashed, NO_CPORT still set cp->lock released

CPU B
ip_vs_nat_xmit()
ip_vs_conn_fill_cport()

    sees cp->cport set and by_me false, so it does nothing

packet forwarded to the real server

The real server's reply then reaches ip_vs_out() before CPU A runs its dir 0 pass. ip_vs_conn_out_get() misses, so handle_response() and SNAT are skipped. The reply is NF_ACCEPTed with the real server's address as its source.

The window is short. It only fits a full round trip if CPU A stalls between the passes, for example through vCPU preemption or softirq preemption on PREEMPT_RT. TCP retransmission should recover after dir 0 completes.

The commit message's goal seems to need only the p->vport == 0 half. For nonzero lookups, the other half only matters in this in-between fill state. Would a one-sided check avoid opening this window? For example:

	if (!p->vport && !(cp->flags & IP_VS_CONN_F_NO_CPORT))
		continue;

On the in side, __ip_vs_conn_in_get() uses the same symmetric rule without this problem. There, hn0 is rehashed and the flag is cleared in the same locked step, but hn1 has no such guarantee.

Quoted 3 lines
net/netfilter/ipvs/ip_vs_conn.c +0 -0
 				    p->protocol == cp->protocol) {
 					if (__ip_vs_conn_get(cp))
 						goto out;
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#26 lore raw

PATCH 13/15 ipvs: do not create conns from packets with port 0

In reply to Pablo Neira Ayuso

From: Julian Anastasov <[email protected]>

We should disallow normal connections with cport 0 to be created from packets by the scheduler (from clients) or by ip_vs_new_conn_out (from real servers) because later such traffic can not hit the connection due to the NO_CPORT requirement. As result, it can lead to duplicate connection for every packet. Do the same for vport 0.

---
 net/netfilter/ipvs/ip_vs_core.c       | 3 ++-
 net/netfilter/ipvs/ip_vs_proto_sctp.c | 7 +++++++
 net/netfilter/ipvs/ip_vs_proto_tcp.c  | 7 +++++++
 net/netfilter/ipvs/ip_vs_proto_udp.c  | 6 ++++++
 4 files changed, 22 insertions(+), 1 deletion(-)
net/netfilter/ipvs/ip_vs_core.c +2 -1
index 76213159404f..15617bd19e96 100644
@@ -1312,6 +1312,7 @@ static inline bool is_new_conn_expected(const struct ip_vs_conn *cp,
  *    In fwmark-VS actual vaddr and vport are unknown to IPVS
  * 2) Real Server and Virtual Service were NOT configured without port:
  *    This is to allow match of different VS to the same RS ip-addr
+ * 3) Client port is not 0
  */
 struct ip_vs_conn *ip_vs_new_conn_out(struct ip_vs_service *svc,
 				      struct ip_vs_dest *dest,
@@ -1335,7 +1336,7 @@ struct ip_vs_conn *ip_vs_new_conn_out(struct ip_vs_service *svc,
 	/* check pre-requisites are satisfied */
 	if (svc->fwmark)
 		return NULL;
-	if (!vport || !dport)
+	if (!vport || !dport || !cport)
 		return NULL;
 
 	/* for persistent service first create connection template */
net/netfilter/ipvs/ip_vs_proto_sctp.c +7 -0
index fb8af6b15a39..cb34bcceb4f6 100644
@@ -30,6 +30,7 @@ sctp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 			sch = skb_header_pointer(skb, iph->len + sizeof(_sctph),
 						 sizeof(_schunkh), &_schunkh);
 			if (sch) {
+				/* Accept packet without scheduling? */
 				if (sch->type == SCTP_CID_ABORT ||
 				    !(sysctl_sloppy_sctp(ipvs) ||
 				      sch->type == SCTP_CID_INIT))
@@ -56,6 +57,12 @@ sctp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 	if (svc) {
 		int ignored;
 
+		/* Do not create connection for port 0 */
+		if (!ports[0] || !ports[1]) {
+			*verdict = NF_DROP;
+			return 0;
+		}
+
 		if (ip_vs_todrop(ipvs)) {
 			/*
 			 * It seems that we are very loaded.
net/netfilter/ipvs/ip_vs_proto_tcp.c +7 -0
index fec0e8b47b71..25d4576d0e12 100644
@@ -48,6 +48,7 @@ tcp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 	if (likely(!ip_vs_iph_icmp(iph))) {
 		th = skb_header_pointer(skb, iph->len, sizeof(_tcph), &_tcph);
 		if (th) {
+			/* Accept packet without scheduling? */
 			if (th->rst || !(sysctl_sloppy_tcp(ipvs) || th->syn))
 				return 1;
 			ports = &th->source;
@@ -74,6 +75,12 @@ tcp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 	if (svc) {
 		int ignored;
 
+		/* Do not create connection for port 0 */
+		if (!ports[0] || !ports[1]) {
+			*verdict = NF_DROP;
+			return 0;
+		}
+
 		if (ip_vs_todrop(ipvs)) {
 			/*
 			 * It seems that we are very loaded.
net/netfilter/ipvs/ip_vs_proto_udp.c +6 -0
index f32785682402..ab3ab9524168 100644
@@ -62,6 +62,12 @@ udp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 	if (svc) {
 		int ignored;
 
+		/* Do not create connection for port 0 */
+		if (!ports[0] || !ports[1]) {
+			*verdict = NF_DROP;
+			return 0;
+		}
+
 		if (ip_vs_todrop(ipvs)) {
 			/*
 			 * It seems that we are very loaded.
Signature · 1 line
2.47.3
author maintainer
#27 lore raw

PATCH 14/15 ipvs: wait grace period before reusing destinations

In reply to Pablo Neira Ayuso

From: Darong Lu <[email protected]>

An IPVS destination can be removed from a service and immediately reused from dest_trash before an RCU grace period has elapsed. Reusing its n_list or d_list can make existing readers follow links into another service or real-server hash chain.

The grace-period cookie is also saved when a live destination is unhashed for an edit and consumed when it is rehashed. Describe rcu_state as the cookie for an unlink, covering both trash and rehash cases.

When a destination is retrieved from dest_trash, ip_vs_add_dest() currently restarts its estimator before waiting for the grace period.
If the estimator was on a tick chain, ip_vs_stop_estimator() removed est->list with hlist_del_rcu(), so an estimator kthread can still be traversing that node.
ip_vs_start_estimator() rewrites the node on its temporary list on success, or initializes it on failure, before the current wait. A reader can then follow the changed link or stop traversing the chain early.

Wait immediately after retrieving the destination, before starting its estimator. The conditional grace-period wait then covers the destination list, real-server hash and estimator list on both estimator success and failure paths.

Fixes bcbde4c0a755 ("ipvs: make the service replacement more robust")
---
 include/net/ip_vs.h            |   4 +-
 net/netfilter/ipvs/ip_vs_ctl.c | 110 ++++++++++++++++++++++++++-------
 2 files changed, 91 insertions(+), 23 deletions(-)
include/net/ip_vs.h +3 -1
index c1f7a3f144f1..8dc80d5d42dc 100644
@@ -1021,7 +1021,9 @@ struct ip_vs_dest {
 
 	struct rcu_head		rcu_head;
 	struct list_head	t_list;		/* in dest_trash */
-	unsigned int		in_rs_table:1;	/* we are in rs_table */
+	unsigned long		rcu_state;	/* GP cookie on unlink (trash or rehash) */
+	unsigned int		in_rs_table:1,	/* we are in rs_table */
+				need_gp:1;	/* Need GP on rehash */
 };
 
 /* The scheduler object */
net/netfilter/ipvs/ip_vs_ctl.c +88 -22

237 lines not on this page · raw message

Signature · 1 line
2.47.3
#28 lore raw

Re: [PATCH net 14/15] ipvs: wait grace period before reusing destinations

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] The commit message for "ipvs: wait grace period before reusing destinations" describes the change against an earlier revision of the…

--

ipvs: wait grace period before reusing destinations

This patch adds a conditional RCU grace-period wait in ip_vs_add_dest() right after a destination is taken from dest_trash, before its estimator is restarted. Trash insertions are batched so that one rcu_state cookie covers each removal. A need_gp flag makes ip_vs_rs_hash() wait before it rehashes a destination that was unhashed during an edit.

Quoted 2 lines

When a destination is retrieved from dest_trash, ip_vs_add_dest() currently restarts its estimator before waiting for the grace period.

[ ... ]

Quoted 3 lines

ip_vs_start_estimator() rewrites the node on its temporary list on success, or initializes it on failure, before the current wait. A reader can then follow the changed link or stop traversing the chain early.

[Severity: Low]
Does this wording describe the change against an earlier revision of the patch rather than the tree it applies to?

In the parent tree, the trash-reuse path in ip_vs_add_dest() has no grace-period wait. ip_vs_trash_get_dest() is followed directly by ip_vs_start_estimator() and __ip_vs_update_dest(). There is also no rcu_state, need_gp or cond_synchronize_rcu() anywhere under net/netfilter/ipvs/ in the parent tree.

So "currently restarts its estimator before waiting" and "before the current wait" point to a wait that does not exist in the baseline. The patch adds the wait rather than moving it.

Quoted 3 lines

The grace-period cookie is also saved when a live destination is unhashed for an edit and consumed when it is rehashed. Describe rcu_state as the cookie for an unlink, covering both trash and rehash cases.

The sentence "Describe rcu_state as the cookie for an unlink" reads like a note between patch versions about rewording the comment on the new struct ip_vs_dest::rcu_state field. It does not describe a change against the baseline.

The patch is tagged for stable. Could the message say plainly that before this patch n_list, d_list and est->list were reused with no grace period? It could then say that the patch adds cond_synchronize_rcu() right after the dest is taken from the trash, and a need_gp wait in ip_vs_rs_hash() for the edit/rehash case.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#29 lore raw

PATCH 15/15 ipvs: pass correct sk to update_pmtu and on tunneling

In reply to Pablo Neira Ayuso

From: Julian Anastasov <[email protected]>

This commit fixes two cases of providing sk on tunneling, one to the update_pmtu handler and the second case is to the ip_local_out() call.

For local clients, we can see at LOCAL_OUT a netfilter hook's state->sk that is different from the protocol's skb->sk. This can be the case for UDP_TUNNEL where different sk is provided to ip_local_out. If such packet is then forwarded via IPVS tunnel we may need to provide state->sk to the update_pmtu handler, not skb->sk.

Fix that by passing the netfilter's hook state via the packet_xmit and conn_schedule handlers to call the update_pmtu handler with state->sk.

While here, change maybe_update_pmtu() to be family independent by using dst and do not request neigh confirm via the last update_pmtu arg because we do not generate the event based on remote signal.

Sashiko has some warnings for the update_pmtu handlers because we provide only sk, not skb:

- we do not provide skb because the handlers assume they are called from tunnel transmitters where skb->dev is present but for IPVS skb->dev is not set yet

- without skb, the zero destination address for unconnected sockets can be blindly used for FIB nexthop or route exceptions. So, we now restrict the sk to be for TCP_ESTABLISHED state where the sk is connected to destination address.

- as we provide the original sk (from state->sk) for the original IP header, make sure we do not provide sk from one family to the update_pmtu handler for different family.

The second problem is that on tunnel forwarding we call ip_local_out() with skb->sk. As we push our own outer IP header in ip_vs_tunnel_xmit*(), the right thing is to provide NULL instead.

For consistency, even if we do not walk the netfilter hooks and just pass the packet with NF_ACCEPT, provide ip_vs_null_xmit_v6 handler to properly indicate that we are sending IPv6 packet. Before now we used ip_vs_null_xmit for both families.

Fixes 79b16aadea32 ("udp_tunnel: Pass UDP socket down through udp_tunnel{, 6}_xmit_skb().")
Fixes 7026b1ddb6b8 ("netfilter: Pass socket pointer down through okfn().")
---
 include/net/ip_vs.h                     |  45 +++++++---
 net/netfilter/ipvs/ip_vs_conn.c         |   2 +-
 net/netfilter/ipvs/ip_vs_core.c         |  41 +++++----
 net/netfilter/ipvs/ip_vs_proto_ah_esp.c |   2 +-
 net/netfilter/ipvs/ip_vs_proto_sctp.c   |   5 +-
 net/netfilter/ipvs/ip_vs_proto_tcp.c    |   5 +-
 net/netfilter/ipvs/ip_vs_proto_udp.c    |   5 +-
 net/netfilter/ipvs/ip_vs_xmit.c         | 114 ++++++++++++++++--------
 8 files changed, 141 insertions(+), 78 deletions(-)
include/net/ip_vs.h +31 -14
index 8dc80d5d42dc..fdb3a9063e60 100644
@@ -731,7 +731,8 @@ struct ip_vs_protocol {
 			     int af, struct sk_buff *skb,
 			     struct ip_vs_proto_data *pd,
 			     int *verdict, struct ip_vs_conn **cpp,
-			     struct ip_vs_iphdr *iph);
+			     struct ip_vs_iphdr *iph,
+			     const struct nf_hook_state *state);
 
 	struct ip_vs_conn *
 	(*conn_in_get)(struct netns_ipvs *ipvs,
@@ -872,7 +873,8 @@ struct ip_vs_conn {
 	 * NF_ACCEPT can be returned when destination is local.
 	 */
 	int (*packet_xmit)(struct sk_buff *skb, struct ip_vs_conn *cp,
-			   struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+			   struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+			   const struct nf_hook_state *state);
 
 	struct rcu_head		rcu_head;
 };
@@ -1872,7 +1874,8 @@ ip_vs_schedule(struct ip_vs_service *svc, struct sk_buff *skb,
 	       struct ip_vs_proto_data *pd, int *ignored,
 	       struct ip_vs_iphdr *iph);
 int ip_vs_leave(struct ip_vs_service *svc, struct sk_buff *skb,
-		struct ip_vs_proto_data *pd, struct ip_vs_iphdr *iph);
+		struct ip_vs_proto_data *pd, struct ip_vs_iphdr *iph,
+		const struct nf_hook_state *state);
 
 void ip_vs_scheduler_err(struct ip_vs_service *svc, const char *msg);
 
@@ -1987,32 +1990,46 @@ static inline int ip_vs_est_max_threads(struct netns_ipvs *ipvs)
 
 /* Various IPVS packet transmitters (from ip_vs_xmit.c) */
 int ip_vs_null_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
-		    struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+		    struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+		    const struct nf_hook_state *state);
 int ip_vs_bypass_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
-		      struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+		      struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+		      const struct nf_hook_state *state);
 int ip_vs_nat_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
-		   struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+		   struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+		   const struct nf_hook_state *state);
 int ip_vs_tunnel_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
-		      struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+		      struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+		      const struct nf_hook_state *state);
 int ip_vs_dr_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
-		  struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+		  struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+		  const struct nf_hook_state *state);
 int ip_vs_icmp_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
 		    struct ip_vs_protocol *pp, unsigned int toff,
-		    unsigned int hooknum, struct ip_vs_iphdr *ciph);
+		    const struct nf_hook_state *state,
+		    struct ip_vs_iphdr *ciph);
 void ip_vs_dest_dst_rcu_free(struct rcu_head *head);
 
 #ifdef CONFIG_IP_VS_IPV6
+int ip_vs_null_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
+		       struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+		       const struct nf_hook_state *state);
 int ip_vs_bypass_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
-			 struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+			 struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+			 const struct nf_hook_state *state);
 int ip_vs_nat_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
-		      struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+		      struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+		      const struct nf_hook_state *state);
 int ip_vs_tunnel_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
-			 struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+			 struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+			 const struct nf_hook_state *state);
 int ip_vs_dr_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
-		     struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
+		     struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph,
+		     const struct nf_hook_state *state);
 int ip_vs_icmp_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
 		       struct ip_vs_protocol *pp, unsigned int toff,
-		       unsigned int hooknum, struct ip_vs_iphdr *ciph);
+		       const struct nf_hook_state *state,
+		       struct ip_vs_iphdr *ciph);
 #endif
 
 #ifdef CONFIG_SYSCTL
net/netfilter/ipvs/ip_vs_conn.c +1 -1
index 83d8a9153a34..7cb8de634f5f 100644
@@ -1057,7 +1057,7 @@ static inline void ip_vs_bind_xmit(struct ip_vs_conn *cp)
 		break;
 
 	case IP_VS_CONN_F_LOCALNODE:
-		cp->packet_xmit = ip_vs_null_xmit;
+		cp->packet_xmit = ip_vs_null_xmit_v6;
 		break;
 
 	case IP_VS_CONN_F_BYPASS:
net/netfilter/ipvs/ip_vs_core.c +24 -17

140 lines not on this page · raw message

net/netfilter/ipvs/ip_vs_proto_ah_esp.c +1 -1
index 44e14acc187e..c7f90b29be51 100644
@@ -102,7 +102,7 @@ static int
 ah_esp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 		     struct ip_vs_proto_data *pd,
 		     int *verdict, struct ip_vs_conn **cpp,
-		     struct ip_vs_iphdr *iph)
+		     struct ip_vs_iphdr *iph, const struct nf_hook_state *state)
 {
 	/*
 	 * AH/ESP is only related traffic. Pass the packet to IP stack.
net/netfilter/ipvs/ip_vs_proto_sctp.c +3 -2
index cb34bcceb4f6..3d773c881f75 100644
@@ -17,7 +17,7 @@ static int
 sctp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 		   struct ip_vs_proto_data *pd,
 		   int *verdict, struct ip_vs_conn **cpp,
-		   struct ip_vs_iphdr *iph)
+		   struct ip_vs_iphdr *iph, const struct nf_hook_state *state)
 {
 	struct ip_vs_service *svc;
 	struct sctp_chunkhdr _schunkh, *sch;
@@ -78,7 +78,8 @@ sctp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 		*cpp = ip_vs_schedule(svc, skb, pd, &ignored, iph);
 		if (!*cpp && ignored <= 0) {
 			if (!ignored)
-				*verdict = ip_vs_leave(svc, skb, pd, iph);
+				*verdict = ip_vs_leave(svc, skb, pd, iph,
+						       state);
 			else
 				*verdict = NF_DROP;
 			return 0;
net/netfilter/ipvs/ip_vs_proto_tcp.c +3 -2
index 25d4576d0e12..13ac917a0ac8 100644
@@ -35,7 +35,7 @@ static int
 tcp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 		  struct ip_vs_proto_data *pd,
 		  int *verdict, struct ip_vs_conn **cpp,
-		  struct ip_vs_iphdr *iph)
+		  struct ip_vs_iphdr *iph, const struct nf_hook_state *state)
 {
 	struct ip_vs_service *svc;
 	struct tcphdr _tcph, *th;
@@ -97,7 +97,8 @@ tcp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 		*cpp = ip_vs_schedule(svc, skb, pd, &ignored, iph);
 		if (!*cpp && ignored <= 0) {
 			if (!ignored)
-				*verdict = ip_vs_leave(svc, skb, pd, iph);
+				*verdict = ip_vs_leave(svc, skb, pd, iph,
+						       state);
 			else
 				*verdict = NF_DROP;
 			return 0;
net/netfilter/ipvs/ip_vs_proto_udp.c +3 -2
index ab3ab9524168..760b019e6a06 100644
@@ -31,7 +31,7 @@ static int
 udp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 		  struct ip_vs_proto_data *pd,
 		  int *verdict, struct ip_vs_conn **cpp,
-		  struct ip_vs_iphdr *iph)
+		  struct ip_vs_iphdr *iph, const struct nf_hook_state *state)
 {
 	struct ip_vs_service *svc;
 	struct udphdr _udph, *uh;
@@ -84,7 +84,8 @@ udp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb,
 		*cpp = ip_vs_schedule(svc, skb, pd, &ignored, iph);
 		if (!*cpp && ignored <= 0) {
 			if (!ignored)
-				*verdict = ip_vs_leave(svc, skb, pd, iph);
+				*verdict = ip_vs_leave(svc, skb, pd, iph,
+						       state);
 			else
 				*verdict = NF_DROP;
 			return 0;
net/netfilter/ipvs/ip_vs_xmit.c +75 -39

300 lines not on this page · raw message

Signature · 1 line
2.47.3
#30 lore raw

Re: [PATCH net 15/15] ipvs: pass correct sk to update_pmtu and on tunneling

Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 3 · Low: 3

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] The new IPv6 null transmitter was added to the IPv4 binder instead of the IPv6 one.
- [Medium] maybe_update_pmtu() treats sk->sk_state == TCP_ESTABLISHED as proof that the socket's daddr is the packet's destination; the…
- [Medium] ip_vs_tunnel_xmit() and ip_vs_tunnel_xmit_v6() now call ip_local_out(net, NULL, skb) and ip6_local_out(net, NULL, skb) instead…
- [Low] The new family check in maybe_update_pmtu() (sk->sk_family == dst->ops->family, net/netfilter/ipvs/ip_vs_xmit.c:224) also turns off…
- [Low] The commit message's main example is UDP_TUNNEL (state->sk differs from skb->sk) and it says 'we may need to provide state->sk to…
- [Low] maybe_update_pmtu() relies on a lockless, plain read of sk->sk_state == TCP_ESTABLISHED to make sure the socket has a valid…

--

ipvs: pass correct sk to update_pmtu and on tunneling

The patch passes the netfilter hook state down through the IPVS conn_schedule and packet_xmit handlers. maybe_update_pmtu() then uses state->sk, limited to TCP_ESTABLISHED sockets at LOCAL_OUT whose family matches the dst. The tunnel transmitters now call ip_local_out() and ip6_local_out() with a NULL sk, and a new ip_vs_null_xmit_v6() handler is added.

net/netfilter/ipvs/ip_vs_conn.c static inline void ip_vs_bind_xmit(struct ip_vs_conn *cp) · line 1063

Quoted 13 lines
net/netfilter/ipvs/ip_vs_conn.c +1 -1
index 83d8a9153a342..7cb8de634f5f9 100644
@@ -1057,7 +1057,7 @@ static inline void ip_vs_bind_xmit(struct ip_vs_conn *cp)
 		break;
 
 	case IP_VS_CONN_F_LOCALNODE:
-		cp->packet_xmit = ip_vs_null_xmit;
+		cp->packet_xmit = ip_vs_null_xmit_v6;
 		break;
 
 	case IP_VS_CONN_F_BYPASS:

[Severity: Medium]
Was this change meant for ip_vs_bind_xmit_v6() instead?

This hunk is in ip_vs_bind_xmit(), which is not under CONFIG_IP_VS_IPV6. Both the prototype in include/net/ip_vs.h and the definition in ip_vs_xmit.c sit inside #ifdef CONFIG_IP_VS_IPV6.

With CONFIG_IP_VS enabled and CONFIG_IP_VS_IPV6 disabled (for example CONFIG_IPV6=n), won't this fail to build? ip_vs_null_xmit_v6 would be both an implicit declaration and an undefined symbol.

With CONFIG_IP_VS_IPV6=y it builds, but the two bindings look swapped. IPv4 LOCALNODE connections now get the v6 handler, while the IPv6 binder is unchanged:

net/netfilter/ipvs/ip_vs_conn.c:ip_vs_bind_xmit_v6() {
    ...
	case IP_VS_CONN_F_LOCALNODE:
		cp->packet_xmit = ip_vs_null_xmit;
		break;
    ...
}

So IPv6 connections never use ip_vs_null_xmit_v6, which is the opposite of what the commit message describes. This has no runtime effect, because ip_vs_send_or_cont() only reads pf when local == 0.

Quoted 23 lines
net/netfilter/ipvs/ip_vs_xmit.c +8 -6
index ebc6b697ae516..c777493eee749 100644
@@ -205,13 +205,24 @@ static inline bool crosses_local_route_boundary(int skb_af, struct sk_buff *skb,
 	return false;
 }
 
-static inline void maybe_update_pmtu(int skb_af, struct sk_buff *skb, int mtu)
+static inline void maybe_update_pmtu(int skb_af, struct sk_buff *skb, int mtu,
+				     const struct nf_hook_state *state)
 {
-	struct sock *sk = skb->sk;
-	struct rtable *ort = skb_rtable(skb);
-
-	if (!skb->dev && sk && sk_fullsock(sk))
-		ort->dst.ops->update_pmtu(&ort->dst, sk, NULL, mtu, true);
+	struct dst_entry *dst = skb_dst(skb);
+	struct sock *sk = state->sk;
+
+	/* The update_pmtu handlers are missing some checks for:
+	 * - skb->dev: present for tunnels, not for IPVS, so we do not
+	 * provide skb, only sk

net/netfilter/ipvs/ip_vs_xmit.c static inline bool crosses_local_route_boundary(int skb_af, struct sk_buff *skb, · line 226

Quoted 10 lines
net/netfilter/ipvs/ip_vs_xmit.c +9 -0
+	 * - present daddr: so, we require TCP_ESTABLISHED (connected socket)
+	 *
+	 * In some states the senders ignore the PMTU events:
+	 * - sk_fullsock(): so use the TCP_ESTABLISHED check
+	 */
+	if (sk && sk->sk_state == TCP_ESTABLISHED &&
+	    state->hook == NF_INET_LOCAL_OUT &&
+	    sk->sk_family == dst->ops->family)
+		dst->ops->update_pmtu(dst, sk, NULL, mtu, false);
 }

[Severity: Medium]
For datagram sockets, does TCP_ESTABLISHED guarantee that the socket's daddr is the packet's destination? The commit message says "where the sk is connected to destination address".

udp_sendmsg() still uses msg_name on a connected socket:

net/ipv4/udp.c:udp_sendmsg() {
    ...
		daddr = usin->sin_addr.s_addr;
		dport = usin->sin_port;
    ...
}

An unprivileged local user could connect() a UDP socket to any address X and then sendto() an IPVS tunnel VIP. Every new check passes (sk set, TCP_ESTABLISHED, LOCAL_OUT, AF_INET):

udp_sendmsg()
ip_local_out()

    ip_vs_in_hook()
      ip_vs_tunnel_xmit()
        __ip_vs_get_out_rt()
          maybe_update_pmtu()
            ip_rt_update_pmtu(dst, sk, NULL, mtu, false)
              ip_rt_build_flow_key()->build_sk_flow_key()
                  /* daddr = inet->inet_daddr, i.e. X */
              __ip_rt_update_pmtu()
                update_or_create_fnhe(nhc, X, 0, mtu, ...)

Would that create a netns-wide PMTU exception for X, using the tunnel MTU from the VIP route?

IPv6 looks similar. With iph == NULL, __ip6_rt_update_pmtu() uses sk->sk_v6_daddr and adds an RTF_CACHE exception under the VIP route.

The old code behaved the same way with skb->sk. Since the patch now relies on TCP_ESTABLISHED for this guarantee, could it also compare inet_sk(sk)->inet_daddr with ip_hdr(skb)->daddr (or sk->sk_v6_daddr with ipv6_hdr(skb)->daddr)? Limiting the update to stream sockets would be another option.

[Severity: Low]
Can the sk_state check go stale before the handler reads the address?

Connected UDP sockets send without lock_sock(). A concurrent connect(AF_UNSPEC) runs __udp_disconnect() under lock_sock only:

net/ipv4/udp.c:__udp_disconnect() {
    ...
	sk->sk_state = TCP_CLOSE;
	WRITE_ONCE(inet->inet_daddr, 0);
    ...
}

Suppose that runs between the sk_state check here and build_sk_flow_key() reading inet->inet_daddr. Wouldn't ip_rt_update_pmtu() then build the flow with daddr 0? That ends up in fib_lookup() and update_or_create_fnhe() for 0.0.0.0, the case the TCP_ESTABLISHED check is meant to exclude.

On IPv6, a concurrent connect() could leave __ip6_rt_update_pmtu() reading a torn sk_v6_daddr. The plain sk_state read also races with the plain store above, which KCSAN may report.

[Severity: Low]
Does the sk->sk_family == dst->ops->family check also rule out AF_INET6 sockets connected to v4-mapped addresses?

Such a socket transmits through the IPv4 path, so at LOCAL_OUT state->sk->sk_family is AF_INET6 while the dst family is AF_INET.

Before this patch, ip_rt_update_pmtu() was called for these sockets. build_sk_flow_key() reads only inet_sk() fields (inet_daddr, inet_saddr, inet_opt, sk_bound_dev_if, sk_mark), and those are valid for v4-mapped sockets.

When pmtu_disc is enabled, ensure_mtu_is_adequate() still sends ICMP FRAG_NEEDED to these senders. The lost update matters mostly with pmtu_disc=0 in tunnel mode.

Was dropping this case intended? If so, could the commit message mention it?

[Severity: Low]
The commit message gives UDP_TUNNEL as the motivating case:

"This can be the case for UDP_TUNNEL where different sk is provided to ip_local_out. If such packet is then forwarded via IPVS tunnel we may need to provide state->sk to the update_pmtu handler, not skb->sk."

vxlan, geneve and wireguard create their sockets with udp_sock_create() and no peer_udp_port. Those sockets are bound but never connected, so sk_state stays TCP_CLOSE.

With the TCP_ESTABLISHED check, won't these tunnel sockets never get the direct update? For most of the motivating cases, the update seems to be dropped completely rather than redirected to the tunnel socket.

Only connected tunnel sockets still qualify, such as kernel L2TP sockets or FOU with FOU_ATTR_PEER_PORT. The other tunnel drivers still learn the PMTU from the ICMP FRAG_NEEDED sent by ensure_mtu_is_adequate().

Could the commit message say this explicitly, to help backporters?

[ ... ]

net/netfilter/ipvs/ip_vs_xmit.c ip_vs_tunnel_xmit(struct sk_buff *skb, struct ip_vs_conn *cp, · line 1314

Quoted 9 lines
net/netfilter/ipvs/ip_vs_xmit.c +1 -1
@@ -1276,7 +1308,7 @@ ip_vs_tunnel_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
 
 	ret = ip_vs_tunnel_xmit_prepare(skb, cp);
 	if (ret == NF_ACCEPT)
-		ip_local_out(net, skb->sk, skb);
+		ip_local_out(net, NULL, skb);
 	else if (ret == NF_DROP)
 		kfree_skb(skb);
 

[Severity: Medium]
Does passing NULL here skip cgroup egress BPF for the encapsulated packet?

For local clients, IPVS steals the original packet at LOCAL_OUT. That makes this tunneled packet the only one that reaches ip_finish_output().

ip_vs_prepare_tunneled_skb() keeps the owning socket:

		if (skb->sk)
			skb_set_owner_w(new_skb, skb->sk);

So before this patch, BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb) ran with sk == skb_to_full_sk(skb). With sk == NULL the macro returns early:

	if (cgroup_bpf_enabled(CGROUP_INET_EGRESS) && sk) {

As a result, cgroup_skb/egress programs (for example systemd IPAddressDeny= or IPAccounting=) would no longer filter or count locally generated traffic that IPVS forwards in tunnel mode. The same applies to the ip6_local_out(net, NULL, skb) change in ip_vs_tunnel_xmit_v6().

The NAT and DR paths already pass NULL to NF_HOOK() in ip_vs_send_or_cont(), so this matches them. On the other hand, xfrm_output_resume() keeps the original sk for locally encapsulated packets.

Was this side effect intended? If so, could the commit message mention it?

Quoted 9 lines
net/netfilter/ipvs/ip_vs_xmit.c +1 -1
@@ -1418,7 +1451,7 @@ ip_vs_tunnel_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
 
 	ret = ip_vs_tunnel_xmit_prepare(skb, cp);
 	if (ret == NF_ACCEPT)
-		ip6_local_out(net, skb->sk, skb);
+		ip6_local_out(net, NULL, skb);
 	else if (ret == NF_DROP)
 		kfree_skb(skb);
 
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261113011447.2357709-2-pablo%40netfilter.org
author maintainer
#31 lore raw
In reply to Pablo Neira Ayuso

Hi,

I'm preparing a v2 of this batch with IPVS fixes, we have identified a few issues in this batch. I plan to submit it by tomorrow.

Apologies and thanks.

Quoted 123 lines · Pablo Neira Ayuso

Hi,

The following patchset contains IPVS fixes for net:

1) Avoid out-of-bounds write in ip_vs_nat_icmp_v6() when an ICMPv6 error embeds a non-first ESP fragment, from Axel Mierczuk.

2) Update *offset for non-first fragments in ipv6_find_hdr(), so callers no longer use the initial offset as if it had been updated. Also from Axel.

3) Rework connection refcounting so the pending and running timer hold a reference. This fixes a use-after-free race between connection deletion and a concurrent timer callback, from Julian Anastasov.

4) Expire controlled connection chains iteratively instead of recursively to avoid kernel stack exhaustion, from Zihan Xi.

5) Reject zero and configured FTP control ports as data ports in the FTP helper, from Zihan Xi.

6) Skip conntrack templates in ip_vs_ftp_out() to fix a UAF in the expectation list after the CT rule is removed, from Theodor Arsenij Larionov Trichkine.

7) Add the seqadj extension before linking the FTP expectation, since krealloc() of ct->ext can otherwise leave the expectation pointing to freed memory. Also from Theodor.

8) Update conn flags, seqs and related fields in the backup server

    under cp->lock, from Julian Anastasov.

9) Read conn flags and seqs atomically in the master when building sync messages, from Julian Anastasov.

10) Fix a race that can leave a destination in the overload state forever. Also make the LBLC/LBLCR schedulers honor the overload state for cached destinations, from Julian Anastasov.

11) Validate cport and IP_VS_CONN_F_NO_CPORT in received sync records. This rejects templates and connections that incoming lookups cannot match, from Axel Mierczuk.

12) Skip cport 0 connections in ip_vs_conn_out_get(), using the same rule as __ip_vs_conn_in_get(). Also from Axel.

13) Do not create connections from packets with client or virtual port 0, which could create a duplicate connection for every packet, from Julian Anastasov.

14) Wait for an RCU grace period before reusing a destination from dest_trash, and before restarting its estimator, from Darong Lu.

15) Pass the netfilter hook's state->sk to the update_pmtu handler, and pass a NULL sk to ip_local_out() when forwarding through an IPVS tunnel, from Julian Anastasov.

Please, pull these changes from:

git://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git nf-26-11-13

Thanks.

----------------------------------------------------------------

The following changes since commit d1bb235aa409a4e5aeba6c748d953d948625b1e9:

netfilter: nat: zero newrange before filling it in (2026-11-05 13:31:11 +0100)

are available in the Git repository at:

git://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git nf-26-11-13

for you to fetch changes up to 937b060406a547e4d931525e600540726ea26532:

ipvs: pass correct sk to update_pmtu and on tunneling (2026-11-13 02:08:35 +0100)

----------------------------------------------------------------
netfilter pull request 26-11-13

----------------------------------------------------------------
Axel Mierczuk (4):
ipvs: avoid out-of-bounds write in ip_vs_nat_icmp_v6
ipv6: update *offset for non-first fragments in ipv6_find_hdr()
ipvs: validate cport in received sync records
ipvs: skip cport 0 connections in ip_vs_conn_out_get()

Darong Lu (1):
ipvs: wait grace period before reusing destinations

Julian Anastasov (6):
ipvs: fix problems during connection deletion
ipvs: update flags and seqs in backup server under lock
ipvs: read flags and seqs in master atomically
ipvs: honor the overload state and do not enter it forever
ipvs: do not create conns from packets with port 0
ipvs: pass correct sk to update_pmtu and on tunneling

Theodor Arsenij Larionov Trichkine (2):
ipvs: ftp: skip conntrack templates in ip_vs_ftp_out
ipvs: ftp: add seqadj extension before linking the expectation

Zihan Xi (2):
ipvs: avoid stack overflow from recursive connection expiration
ipvs: reject FTP control ports as data ports

 include/net/ip_vs.h                     |  52 ++++++++----
 net/ipv6/exthdrs_core.c                 |   6 +-
 net/netfilter/ipvs/ip_vs_conn.c         | 133 ++++++++++++++++++------------
 net/netfilter/ipvs/ip_vs_core.c         |  58 +++++++++----
 net/netfilter/ipvs/ip_vs_ctl.c          | 140 ++++++++++++++++++++++++--------
 net/netfilter/ipvs/ip_vs_ftp.c          |  39 +++++++--
 net/netfilter/ipvs/ip_vs_lblc.c         |   8 +-
 net/netfilter/ipvs/ip_vs_lblcr.c        |  13 +--
 net/netfilter/ipvs/ip_vs_proto_ah_esp.c |   2 +-
 net/netfilter/ipvs/ip_vs_proto_sctp.c   |  12 ++-
 net/netfilter/ipvs/ip_vs_proto_tcp.c    |  12 ++-
 net/netfilter/ipvs/ip_vs_proto_udp.c    |  11 ++-
 net/netfilter/ipvs/ip_vs_sync.c         |  53 ++++++++++--
 net/netfilter/ipvs/ip_vs_xmit.c         | 114 +++++++++++++++++---------
 14 files changed, 462 insertions(+), 191 deletions(-)