Netdev List
 help / color / mirror / Atom feed
* [BUG] ipvs: replies of a connection leave with the address of another virtual service after a conn_tab resize
@ 2026-11-30  6:42 Zhenrong (Daniel) Gu
  2026-12-01  7:35 ` Julian Anastasov
  0 siblings, 1 reply; 2+ messages in thread
From: Zhenrong (Daniel) Gu @ 2026-11-30  6:42 UTC (permalink / raw)
  To: Julian Anastasov
  Cc: Simon Horman, Pablo Neira Ayuso, Florian Westphal, lvs-devel,
	netfilter-devel, netdev, regressions, Xing Feng, Peng Zhang

Hello Julian,

This is a second ordering problem with the resizable connection table,
next to the conn_reuse one in "[PATCH nf v2] ipvs: fix connection
reuse with the resizable hash tables" [1]. This one is in the out
direction, and that patch does not cover it.

Two NAT virtual services, VIP1:80 and VIP2:80, share a real server
RS:8080. A client connects to VIP1, the real server closes, and the
client connects from the same source port to VIP2. If conn_tab is
resized while the VIP1 entry is still in TIME_WAIT, the SYN-ACK of the
VIP2 connection leaves the director with VIP1 as its source. The client
has no such connection and answers with a RST, so the connection fails.

Seen on 7.3.4 (Fedora 7.3.4-300.fc45.x86_64) and on net at
e9e45fcb6d39 (7.4.0-rc4), with and without the RFC version of [1] (v2
is unchanged on this path). All sysctls at their defaults; rr
scheduler. We have not run 7.0; going by the code, this comes from the
same commit as the conn_reuse report:

#regzbot introduced: 2fa7cc9c7025

Example (capture on the client, port 45018, VIP1 10.96.0.10, VIP2
10.96.0.11; the VIP1 connection on this port had ended 50 ms earlier):

       +0.0 ms  10.1.0.2.45018 > 10.96.0.11.80: [S]  seq 2781900371
       +0.0 ms  10.96.0.10.80 > 10.1.0.2.45018: [S.] seq 313299061,
                                                    ack 2781900372
       +0.0 ms  10.1.0.2.45018 > 10.96.0.10.80: [R]  seq 2781900372
    +1026.7 ms  10.1.0.2.45018 > 10.96.0.11.80: [S]  seq 2781900371
    +1026.8 ms  10.96.0.10.80 > 10.1.0.2.45018: [S.] seq 330082370,
                                                    ack 2781900372
    +1026.8 ms  10.1.0.2.45018 > 10.96.0.10.80: [R]  seq 2781900372

The client's RST to VIP1:80 matches the VIP1 entry and apparently
resets the half-open connection on the real server (the next SYN-ACK
has a new ISN). The SYN retransmitted 1 s later gets the same wrong
answer, long after the resize (a few ms) has finished.


Analysis
--------

ip_vs_conn_out_get() keys on protocol, real server and client, without
the virtual address. Entry A (client:45018 -> VIP1 -> RS:8080,
TIME_WAIT) and entry B (client:45018 -> VIP2 -> RS:8080) therefore both
match RS:8080 -> client:45018. Their in-direction keys differ, so
conn_reuse_mode is not involved and A is not marked IP_VS_CONN_F_REUSED.

Before 7.1, B was hashed at the bucket head and found first. With the
resizable table, conn_resize_work_handler() moves A to the head of its
bucket in the new table, in front of B, and that order stays until A
expires. ip_vs_out() then SNATs B's replies with VIP1. (While the
resize runs, the old table being walked first has the same effect, but
only for those few ms.)

On the real server A and B are the same 4-tuple, so only one of them
can exist there at a time and any reply from it belongs to the newest
entry. A is still needed for late packets from the client to VIP1.


Reproduction
------------

The script below sets up VIP1 and VIP2 in front of one real server.
1000 threads cycle through ports 45000-45999 (VIP1, then VIP2 from the
same port) while 4 threads connect from ephemeral ports; a client
capture counts SYN-ACKs whose source is not the VIP of the SYN they
acknowledge. Modes (force, grow, noresize) are the same as in the
conn_reuse reproducer.

SYN-ACKs from the wrong VIP on net (7.4.0-rc4, 8-vCPU KVM guest, one
guest per run):

  mode               net       net + RFC patch
  force, 30 s       12683           8536
  grow, 60 s        58, 0, 145      0, 1044, 377    (3 runs each)
  noresize, 30 s        0              0

With the RFC patch, the conn_reuse reproducer showed no misrouted
connection in the same guests. On 7.3.4 bare metal, a 30 s grow run had
2225 wrong-VIP SYN-ACKs and 1428 of 94832 VIP2 connections timed out
after 2 s, vs 0 in noresize.

---8<--- repro.sh ---8<---
#!/bin/bash
# IPVS: two virtual services with the same real server. A client connects
# to VIP1, then from the same source port to VIP2. Each reply to the VIP2
# connection must have VIP2 as its source; the client capture counts the
# replies to a port's VIP2 connection that came from VIP1.
#
# usage: sudo ./repro.sh [force|grow|noresize] [seconds]
#   force     switch conn_lfactor every 100 ms: one resize each time
#   grow      kernel defaults; the table grows with the connection count
#   noresize  conn_lfactor=8: no resize under this load (control)
set -euo pipefail
MODE=${1:-force}
SECS=${2:-30}
V1=10.96.0.10 V2=10.96.0.11 RS=10.2.1.2
NS="xv-cli xv-lb xv-rs"
DIR=$(mktemp -d)
PIDS=()
cleanup() {
	for p in "${PIDS[@]}"; do kill "$p" 2>/dev/null || true; done
	wait 2>/dev/null || true
	for n in $NS; do ip netns del "$n" 2>/dev/null || true; done
}
trap cleanup EXIT
lb() { ip netns exec xv-lb "$@"; }
for n in $NS; do ip netns add "$n"; ip -n "$n" link set lo up; done
link() {
	ip link add "$2" netns "$1" type veth peer name "$5" netns "$4"
	ip -n "$1" addr add "$3/24" dev "$2"; ip -n "$1" link set "$2" up
	ip -n "$4" addr add "$6/24" dev "$5"; ip -n "$4" link set "$5" up
}
link xv-lb cli 10.1.0.1 xv-cli eth0 10.1.0.2
link xv-lb rs 10.2.1.1 xv-rs eth0 $RS
ip -n xv-cli route add default via 10.1.0.1
ip -n xv-rs route add default via 10.2.1.1
ip netns exec xv-rs python3 -c '
import socket, threading
s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("10.2.1.2", 8080)); s.listen(1024)
def serve(c):
    try:
        c.settimeout(5)
        if c.recv(64): c.sendall(b"ok")
    except OSError: pass
    c.close()  # the real server closes first
while True:
    threading.Thread(target=serve, args=(s.accept()[0],), daemon=True).start()
' &
PIDS+=($!)
lb sysctl -qw net.ipv4.ip_forward=1
ip -n xv-lb link add ipvs0 type dummy
ip -n xv-lb addr add $V1/32 dev ipvs0
ip -n xv-lb addr add $V2/32 dev ipvs0
lb ipvsadm -A -t $V1:80 -s rr
lb ipvsadm -A -t $V2:80 -s rr
lb ipvsadm -a -t $V1:80 -r $RS:8080 -m
lb ipvsadm -a -t $V2:80 -r $RS:8080 -m
LF=$(lb sysctl -n net.ipv4.vs.conn_lfactor)
if [ "$MODE" = noresize ]; then LF=8; lb sysctl -qw net.ipv4.vs.conn_lfactor=8; fi
sleep 1
ip netns exec xv-cli tcpdump -i eth0 -nn -s 96 -U -w "$DIR/cli.pcap" \
	'tcp portrange 45000-45999 and tcp[tcpflags] & tcp-syn != 0' 2>/dev/null &
PIDS+=($!)
sleep 1
if [ "$MODE" = force ]; then
	( v=$LF; while :; do
		v=$(( v == LF ? LF + 1 : LF ))
		lb sysctl -qw net.ipv4.vs.conn_lfactor=$v
		sleep 0.1
	done ) &
	PIDS+=($!)
fi
# 4 threads of connections from ephemeral ports to VIP1 keep a few thousand
# entries in the table; 1000 threads cycle through ports 45000-45999: VIP1,
# then VIP2 from the same port.
ip netns exec xv-cli python3 -c '
import socket, sys, threading, time
v1, v2, stop = sys.argv[1], sys.argv[2], time.monotonic() + float(sys.argv[3])
res = {"ok": 0, "fail": 0, "slow": 0}
lock = threading.Lock()
def one(vip, port):
    s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.settimeout(2)
    t = time.monotonic()
    try:
        if port: s.bind(("0.0.0.0", port))
        s.connect((vip, 80)); s.sendall(b"x"); s.recv(64)
        while s.recv(64): pass
        return time.monotonic() - t
    except OSError:
        return None
    finally: s.close()
def pairs(port):
    while time.monotonic() < stop:
        one(v1, port); time.sleep(0.05)
        d = one(v2, port)
        with lock:
            res["fail" if d is None else "slow" if d > 0.5 else "ok"] += 1
        time.sleep(0.05)
def load():
    while time.monotonic() < stop: one(v1, 0)
ts = [threading.Thread(target=load) for _ in range(4)]
ts += [threading.Thread(target=pairs, args=(p,)) for p in range(45000, 46000)]
for t in ts: t.start()
for t in ts: t.join()
print(f"  VIP2 connections: {res}")
' $V1 $V2 "$SECS"
sleep 1
kill "${PIDS[-1]}" 2>/dev/null || true
[ "$MODE" = force ] && { kill "${PIDS[-2]}" 2>/dev/null || true; }
sleep 1
# Pair each SYN-ACK with the SYN it acknowledges: its source must be the
# VIP that SYN went to.
tcpdump -nn -S -r "$DIR/cli.pcap" 2>/dev/null | python3 -c '
import re, sys
syn, n = {}, {"right": 0, "wrong": 0, "unpaired": 0}
for l in sys.stdin:
    m = re.search(r"IP 10\.1\.0\.2\.(\d+) > (10\.96\.0\.1[01])\.80: Flags \[S\], seq (\d+)", l)
    if m:
        syn[(m.group(1), int(m.group(3)))] = m.group(2); continue
    m = re.search(r"IP (10\.96\.0\.1[01])\.80 > 10\.1\.0\.2\.(\d+): Flags \[S\.\], seq \d+, ack (\d+)", l)
    if m:
        d = syn.get((m.group(2), (int(m.group(3)) - 1) % 2**32))
        n["unpaired" if d is None else "right" if d == m.group(1) else "wrong"] += 1
        if d and d != m.group(1) and n["wrong"] <= 3: print("   ", l.strip()[:110], "| SYN went to", d)
print(f"  SYN-ACKs: {n}")
'
echo "  max conn entries: $(lb ipvsadm -Lnc | wc -l)"
---8<--- end of repro.sh ---8<---

Either a separate flag set on older entries with the same out-direction
key when hashing a NAT connection (not IP_VS_CONN_F_REUSED, since A
must still match client packets and be synced), or adding moved entries
at the tail of the new bucket instead of the head, might avoid this
(untested). With [1], in-direction lookups no longer depend on the
order.

Xing Feng, Peng Zhang (Cc'd) and I found this with the same runtime
checker against kube-proxy in IPVS mode, where two Services selecting
the same pods share real servers.

[1] https://lore.kernel.org/netfilter-devel/20261125190940.118112-1-ja@ssi.bg/

Thanks,
Zhenrong (Daniel) Gu


^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: [BUG] ipvs: replies of a connection leave with the address of another virtual service after a conn_tab resize
  2026-11-30  6:42 [BUG] ipvs: replies of a connection leave with the address of another virtual service after a conn_tab resize Zhenrong (Daniel) Gu
@ 2026-12-01  7:35 ` Julian Anastasov
  0 siblings, 0 replies; 2+ messages in thread
From: Julian Anastasov @ 2026-12-01  7:35 UTC (permalink / raw)
  To: Zhenrong (Daniel) Gu
  Cc: Simon Horman, Pablo Neira Ayuso, Florian Westphal, lvs-devel,
	netfilter-devel, netdev, regressions, Xing Feng, Peng Zhang


	Hello,

On Mon, 30 Nov 2026, Zhenrong (Daniel) Gu wrote:

> Hello Julian,
> 
> This is a second ordering problem with the resizable connection table,
> next to the conn_reuse one in "[PATCH nf v2] ipvs: fix connection
> reuse with the resizable hash tables" [1]. This one is in the out
> direction, and that patch does not cover it.
> 
> Two NAT virtual services, VIP1:80 and VIP2:80, share a real server
> RS:8080. A client connects to VIP1, the real server closes, and the
> client connects from the same source port to VIP2. If conn_tab is
> resized while the VIP1 entry is still in TIME_WAIT, the SYN-ACK of the
> VIP2 connection leaves the director with VIP1 as its source. The client
> has no such connection and answers with a RST, so the connection fails.
> 
> Seen on 7.3.4 (Fedora 7.3.4-300.fc45.x86_64) and on net at
> e9e45fcb6d39 (7.4.0-rc4), with and without the RFC version of [1] (v2
> is unchanged on this path). All sysctls at their defaults; rr
> scheduler. We have not run 7.0; going by the code, this comes from the
> same commit as the conn_reuse report:
> 
> #regzbot introduced: 2fa7cc9c7025
> 
> Example (capture on the client, port 45018, VIP1 10.96.0.10, VIP2
> 10.96.0.11; the VIP1 connection on this port had ended 50 ms earlier):
> 
>        +0.0 ms  10.1.0.2.45018 > 10.96.0.11.80: [S]  seq 2781900371
>        +0.0 ms  10.96.0.10.80 > 10.1.0.2.45018: [S.] seq 313299061,
>                                                     ack 2781900372
>        +0.0 ms  10.1.0.2.45018 > 10.96.0.10.80: [R]  seq 2781900372
>     +1026.7 ms  10.1.0.2.45018 > 10.96.0.11.80: [S]  seq 2781900371
>     +1026.8 ms  10.96.0.10.80 > 10.1.0.2.45018: [S.] seq 330082370,
>                                                     ack 2781900372
>     +1026.8 ms  10.1.0.2.45018 > 10.96.0.10.80: [R]  seq 2781900372
> 
> The client's RST to VIP1:80 matches the VIP1 entry and apparently
> resets the half-open connection on the real server (the next SYN-ACK
> has a new ISN). The SYN retransmitted 1 s later gets the same wrong
> answer, long after the resize (a few ms) has finished.
> 
> 
> Analysis
> --------
> 
> ip_vs_conn_out_get() keys on protocol, real server and client, without
> the virtual address. Entry A (client:45018 -> VIP1 -> RS:8080,
> TIME_WAIT) and entry B (client:45018 -> VIP2 -> RS:8080) therefore both
> match RS:8080 -> client:45018. Their in-direction keys differ, so
> conn_reuse_mode is not involved and A is not marked IP_VS_CONN_F_REUSED.
> 
> Before 7.1, B was hashed at the bucket head and found first. With the
> resizable table, conn_resize_work_handler() moves A to the head of its
> bucket in the new table, in front of B, and that order stays until A
> expires. ip_vs_out() then SNATs B's replies with VIP1. (While the
> resize runs, the old table being walked first has the same effect, but
> only for those few ms.)
> 
> On the real server A and B are the same 4-tuple, so only one of them
> can exist there at a time and any reply from it belongs to the newest
> entry. A is still needed for late packets from the client to VIP1.
> 
> 
> Reproduction
> ------------
> 
> The script below sets up VIP1 and VIP2 in front of one real server.
> 1000 threads cycle through ports 45000-45999 (VIP1, then VIP2 from the
> same port) while 4 threads connect from ephemeral ports; a client
> capture counts SYN-ACKs whose source is not the VIP of the SYN they
> acknowledge. Modes (force, grow, noresize) are the same as in the
> conn_reuse reproducer.
> 
> SYN-ACKs from the wrong VIP on net (7.4.0-rc4, 8-vCPU KVM guest, one
> guest per run):
> 
>   mode               net       net + RFC patch
>   force, 30 s       12683           8536
>   grow, 60 s        58, 0, 145      0, 1044, 377    (3 runs each)
>   noresize, 30 s        0              0
> 
> With the RFC patch, the conn_reuse reproducer showed no misrouted
> connection in the same guests. On 7.3.4 bare metal, a 30 s grow run had
> 2225 wrong-VIP SYN-ACKs and 1428 of 94832 VIP2 connections timed out
> after 2 s, vs 0 in noresize.
> 
> ---8<--- repro.sh ---8<---
> #!/bin/bash
> # IPVS: two virtual services with the same real server. A client connects
> # to VIP1, then from the same source port to VIP2. Each reply to the VIP2
> # connection must have VIP2 as its source; the client capture counts the
> # replies to a port's VIP2 connection that came from VIP1.
> #
> # usage: sudo ./repro.sh [force|grow|noresize] [seconds]
> #   force     switch conn_lfactor every 100 ms: one resize each time
> #   grow      kernel defaults; the table grows with the connection count
> #   noresize  conn_lfactor=8: no resize under this load (control)
> set -euo pipefail
> MODE=${1:-force}
> SECS=${2:-30}
> V1=10.96.0.10 V2=10.96.0.11 RS=10.2.1.2
> NS="xv-cli xv-lb xv-rs"
> DIR=$(mktemp -d)
> PIDS=()
> cleanup() {
> 	for p in "${PIDS[@]}"; do kill "$p" 2>/dev/null || true; done
> 	wait 2>/dev/null || true
> 	for n in $NS; do ip netns del "$n" 2>/dev/null || true; done
> }
> trap cleanup EXIT
> lb() { ip netns exec xv-lb "$@"; }
> for n in $NS; do ip netns add "$n"; ip -n "$n" link set lo up; done
> link() {
> 	ip link add "$2" netns "$1" type veth peer name "$5" netns "$4"
> 	ip -n "$1" addr add "$3/24" dev "$2"; ip -n "$1" link set "$2" up
> 	ip -n "$4" addr add "$6/24" dev "$5"; ip -n "$4" link set "$5" up
> }
> link xv-lb cli 10.1.0.1 xv-cli eth0 10.1.0.2
> link xv-lb rs 10.2.1.1 xv-rs eth0 $RS
> ip -n xv-cli route add default via 10.1.0.1
> ip -n xv-rs route add default via 10.2.1.1
> ip netns exec xv-rs python3 -c '
> import socket, threading
> s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
> s.bind(("10.2.1.2", 8080)); s.listen(1024)
> def serve(c):
>     try:
>         c.settimeout(5)
>         if c.recv(64): c.sendall(b"ok")
>     except OSError: pass
>     c.close()  # the real server closes first
> while True:
>     threading.Thread(target=serve, args=(s.accept()[0],), daemon=True).start()
> ' &
> PIDS+=($!)
> lb sysctl -qw net.ipv4.ip_forward=1
> ip -n xv-lb link add ipvs0 type dummy
> ip -n xv-lb addr add $V1/32 dev ipvs0
> ip -n xv-lb addr add $V2/32 dev ipvs0
> lb ipvsadm -A -t $V1:80 -s rr
> lb ipvsadm -A -t $V2:80 -s rr
> lb ipvsadm -a -t $V1:80 -r $RS:8080 -m
> lb ipvsadm -a -t $V2:80 -r $RS:8080 -m
> LF=$(lb sysctl -n net.ipv4.vs.conn_lfactor)
> if [ "$MODE" = noresize ]; then LF=8; lb sysctl -qw net.ipv4.vs.conn_lfactor=8; fi
> sleep 1
> ip netns exec xv-cli tcpdump -i eth0 -nn -s 96 -U -w "$DIR/cli.pcap" \
> 	'tcp portrange 45000-45999 and tcp[tcpflags] & tcp-syn != 0' 2>/dev/null &
> PIDS+=($!)
> sleep 1
> if [ "$MODE" = force ]; then
> 	( v=$LF; while :; do
> 		v=$(( v == LF ? LF + 1 : LF ))
> 		lb sysctl -qw net.ipv4.vs.conn_lfactor=$v
> 		sleep 0.1
> 	done ) &
> 	PIDS+=($!)
> fi
> # 4 threads of connections from ephemeral ports to VIP1 keep a few thousand
> # entries in the table; 1000 threads cycle through ports 45000-45999: VIP1,
> # then VIP2 from the same port.
> ip netns exec xv-cli python3 -c '
> import socket, sys, threading, time
> v1, v2, stop = sys.argv[1], sys.argv[2], time.monotonic() + float(sys.argv[3])
> res = {"ok": 0, "fail": 0, "slow": 0}
> lock = threading.Lock()
> def one(vip, port):
>     s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
>     s.settimeout(2)
>     t = time.monotonic()
>     try:
>         if port: s.bind(("0.0.0.0", port))
>         s.connect((vip, 80)); s.sendall(b"x"); s.recv(64)
>         while s.recv(64): pass
>         return time.monotonic() - t
>     except OSError:
>         return None
>     finally: s.close()
> def pairs(port):
>     while time.monotonic() < stop:
>         one(v1, port); time.sleep(0.05)
>         d = one(v2, port)
>         with lock:
>             res["fail" if d is None else "slow" if d > 0.5 else "ok"] += 1
>         time.sleep(0.05)
> def load():
>     while time.monotonic() < stop: one(v1, 0)
> ts = [threading.Thread(target=load) for _ in range(4)]
> ts += [threading.Thread(target=pairs, args=(p,)) for p in range(45000, 46000)]
> for t in ts: t.start()
> for t in ts: t.join()
> print(f"  VIP2 connections: {res}")
> ' $V1 $V2 "$SECS"
> sleep 1
> kill "${PIDS[-1]}" 2>/dev/null || true
> [ "$MODE" = force ] && { kill "${PIDS[-2]}" 2>/dev/null || true; }
> sleep 1
> # Pair each SYN-ACK with the SYN it acknowledges: its source must be the
> # VIP that SYN went to.
> tcpdump -nn -S -r "$DIR/cli.pcap" 2>/dev/null | python3 -c '
> import re, sys
> syn, n = {}, {"right": 0, "wrong": 0, "unpaired": 0}
> for l in sys.stdin:
>     m = re.search(r"IP 10\.1\.0\.2\.(\d+) > (10\.96\.0\.1[01])\.80: Flags \[S\], seq (\d+)", l)
>     if m:
>         syn[(m.group(1), int(m.group(3)))] = m.group(2); continue
>     m = re.search(r"IP (10\.96\.0\.1[01])\.80 > 10\.1\.0\.2\.(\d+): Flags \[S\.\], seq \d+, ack (\d+)", l)
>     if m:
>         d = syn.get((m.group(2), (int(m.group(3)) - 1) % 2**32))
>         n["unpaired" if d is None else "right" if d == m.group(1) else "wrong"] += 1
>         if d and d != m.group(1) and n["wrong"] <= 3: print("   ", l.strip()[:110], "| SYN went to", d)
> print(f"  SYN-ACKs: {n}")
> '
> echo "  max conn entries: $(lb ipvsadm -Lnc | wc -l)"
> ---8<--- end of repro.sh ---8<---
> 
> Either a separate flag set on older entries with the same out-direction
> key when hashing a NAT connection (not IP_VS_CONN_F_REUSED, since A
> must still match client packets and be synced), or adding moved entries
> at the tail of the new bucket instead of the head, might avoid this
> (untested). With [1], in-direction lookups no longer depend on the
> order.

	If we add new flag REUSED_OUT just to let client's packets
to reach the real server, the acks from real server still will be
dropped. If we tracked the SEQs we can probably determine the
right connection from the packet from real server but what happens
if they are many... The chance for error increases.

	So, in the following patch I decided to drop the new
packets, if both ends from the old connection send FIN and we
enter sTW, the traffic will be allowed for the new connection.
The drawback is that we drop any retransmissions on packet loss
once the old connection is marked as reused.

> Xing Feng, Peng Zhang (Cc'd) and I found this with the same runtime
> checker against kube-proxy in IPVS mode, where two Services selecting
> the same pods share real servers.
> 
> [1] https://lore.kernel.org/netfilter-devel/20261125190940.118112-1-ja@ssi.bg/
> 
> Thanks,
> Zhenrong (Daniel) Gu

	In fact, I found this patch in the 2018 archives, it was
forgotten during discussions. It always dropped the new packets,
now I added check for the finished state. This is not tested yet.

[PATCH nf] ipvs: drop duplicate NAT connections

Zhenrong (Daniel) Gu, Xing Feng and Peng Zhang report for
a problem on NAT collision while testing a passive runtime
checker for L4 load balancers against kube-proxy in IPVS mode.

Setups with one or many virtual IPs using IPVS NAT rules to
redirect to same real server IP/port are prone to be attacked
with traffic that causes long hash table chains because such
connections according to the real server have same addresses
and ports (duplicates) and are hashed in same bucket.

Additionally, with the introduction of the resizable connection
hash table which started to reverse the order of connections
each time the table is resized, we can see outdated duplicate
connection to be hit for packets from real server which are
part of a new connection. As result, the client can see packets
coming from the wrong (old) virtual IP.

Fix it by adding collision check when creating NAT connections.
The collision is resolved based on the conn_reuse_mode sysctl
var: if old connection from CADDR:CPORT to any virtual IP is
finished (both sides closed it and we are in sTW/sCL), it can
be marked as reused.

If the old connection is not finished, we drop the new traffic.
Collisions can be avoided if administrators use unique RIP/RPORT
for every used VIP/VPORT.

This change depends on the commit that marks reused connections:
"ipvs: fix connection reuse with the resizable hash tables".

Reported-by: "Zhenrong (Daniel) Gu" <zrgu@stu.xjtu.edu.cn>
Reported-by: Xing Feng <xingfeng@stu.xjtu.edu.cn>
Reported-by: Peng Zhang <p-zhang@xjtu.edu.cn>
Link: https://lore.kernel.org/all/aw0a1va6B42zeaKL@fxxowodeMacBook-Pro.local/
Fixes: 2fa7cc9c7025 ("ipvs: switch to per-net connection table")
Signed-off-by: Julian Anastasov <ja@ssi.bg>
---
 net/netfilter/ipvs/ip_vs_core.c | 60 +++++++++++++++++++++++++++++++++
 1 file changed, 60 insertions(+)

diff --git a/net/netfilter/ipvs/ip_vs_core.c b/net/netfilter/ipvs/ip_vs_core.c
index 5354ecfe2607..ef9c4008d7bd 100644
--- a/net/netfilter/ipvs/ip_vs_core.c
+++ b/net/netfilter/ipvs/ip_vs_core.c
@@ -86,6 +86,9 @@ static atomic_t ipvs_netns_cnt = ATOMIC_INIT(0);
 #define icmp_id(icmph)          (((icmph)->un).echo.id)
 #define icmpv6_id(icmph)        (icmph->icmp6_dataun.u_echo.identifier)
 
+static bool ip_vs_conn_out_collision(struct netns_ipvs *ipvs,
+				     const struct ip_vs_conn_param *p);
+
 const char *ip_vs_proto_name(unsigned int proto)
 {
 	static char buf[20];
@@ -568,6 +571,19 @@ ip_vs_sched_persist(struct ip_vs_service *svc,
 		 && iph->protocol == IPPROTO_UDP) ?
 		IP_VS_CONN_F_ONE_PACKET : 0;
 
+	/* Avoid many duplicate connections from client to same server */
+	if (IP_VS_DFWD_METHOD(dest) == IP_VS_CONN_F_MASQ &&
+	    !(flags & IP_VS_CONN_F_ONE_PACKET)) {
+		ip_vs_conn_fill_param(svc->ipvs, svc->af, iph->protocol,
+				&dest->addr, dport, src_addr, src_port,
+				&param);
+		if (ip_vs_conn_out_collision(svc->ipvs, &param)) {
+			ip_vs_conn_put(ct);
+			*ignored = -1;
+			return NULL;
+		}
+	}
+
 	/*
 	 *    Create a new connection according to the template
 	 */
@@ -715,6 +731,20 @@ ip_vs_schedule(struct ip_vs_service *svc, struct sk_buff *skb,
 		 && iph->protocol == IPPROTO_UDP) ?
 		IP_VS_CONN_F_ONE_PACKET : 0;
 
+	/* Avoid many duplicate connections from client to same server */
+	if (IP_VS_DFWD_METHOD(dest) == IP_VS_CONN_F_MASQ &&
+	    !(flags & IP_VS_CONN_F_ONE_PACKET)) {
+		struct ip_vs_conn_param p;
+
+		ip_vs_conn_fill_param(svc->ipvs, svc->af, iph->protocol,
+				&dest->addr, dest->port ? dest->port : vport,
+				caddr, cport, &p);
+		if (ip_vs_conn_out_collision(svc->ipvs, &p)) {
+			*ignored = -1;
+			return NULL;
+		}
+	}
+
 	/*
 	 *    Create a connection entry.
 	 */
@@ -1299,6 +1329,36 @@ static inline bool is_new_conn_expected(const struct ip_vs_conn *cp,
 	}
 }
 
+/* Avoid large hash chains in conn_tab: check for in->out collision.
+ * Called for pkts coming from INside-to-OUTside.
+ *   p->caddr, p->cport: pkt source address (inside host)
+ *   p->vaddr, p->vport: pkt dest address (foreign host)
+ */
+static bool ip_vs_conn_out_collision(struct netns_ipvs *ipvs,
+				     const struct ip_vs_conn_param *p)
+{
+	struct ip_vs_conn *cp = ip_vs_conn_out_get(p);
+	bool ret = false;
+
+	if (cp) {
+		IP_VS_DBG_BUF(9, "lookup/out %s %s:%d->%s:%d collision\n",
+			      ip_vs_proto_name(p->protocol),
+			      IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
+			      IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport));
+		if (is_new_conn_expected(cp, sysctl_conn_reuse_mode(ipvs))) {
+			ip_vs_conn_mark_reused(cp);
+			if (!atomic_read(&cp->n_control))
+				ip_vs_conn_expire_now(cp);
+		} else {
+			/* Avoid new connection while another is active */
+			ret = true;
+		}
+		__ip_vs_conn_put(cp);
+	}
+
+	return ret;
+}
+
 /* Generic function to create new connections for outgoing RS packets
  *
  * Pre-requisites for successful connection creation:

Prerequisite-Message-Id: <20261103165746.39516-1-axel.mierczuk@1password.com>
Prerequisite-Message-Id: <20261125190940.118112-1-ja@ssi.bg>
-- 
2.56.1


Regards

--
Julian Anastasov <ja@ssi.bg>


^ permalink raw reply related	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2026-12-01  7:35 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-30  6:42 [BUG] ipvs: replies of a connection leave with the address of another virtual service after a conn_tab resize Zhenrong (Daniel) Gu
2026-12-01  7:35 ` Julian Anastasov

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox