Skip to contentSkip to conversation

ipvs: replies of a connection leave with the address of another virtual service after a conn_tab resize

BUG Zhenrong (Daniel) Gu 1 participant 1 message Nov 30

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

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/[email protected]/

Thanks,
Zhenrong (Daniel) Gu