Skip to content

atunnel: support IPv6 original destination lookup - #753

Open
Bingtan Lu (lubingtan) wants to merge 3 commits into
agent-substrate:mainfrom
lubingtan:686-atunnel-ipv6-original-dst
Open

atunnel: support IPv6 original destination lookup#753
Bingtan Lu (lubingtan) wants to merge 3 commits into
agent-substrate:mainfrom
lubingtan:686-atunnel-ipv6-original-dst

Conversation

@lubingtan

@lubingtan Bingtan Lu (lubingtan) commented Aug 5, 2026

Copy link
Copy Markdown

Fixes #686

It's a good idea to open an issue first for discussion.

  • Tests pass
  • Appropriate changes to documentation are included in the PR

Solution

TCPOriginalDestination first queries the existing IPv4 SOL_IP / SO_ORIGINAL_DST socket option. Linux returns ENOENT when that option is queried for a redirected IPv6 connection, so only in that case it falls back to SOL_IPV6 / IP6T_SO_ORIGINAL_DST (value 80 from linux/netfilter_ipv6/ip6_tables.h). Other IPv4 errors are returned unchanged.

The IPv6 lookup decodes RawSockaddrInet6 and formats the result with net.JoinHostPort, preserving the required bracketed address form.

Tests

The new root-gated integration tests model the production egress path for both address families: an actor-like network namespace sends TCP through a veth, an nftables PREROUTING rule redirects it to a local listener, and the listener verifies that TCPOriginalDestination returns the actor's pre-redirect target. The IPv6 test also disables DAD for the test-only veth addresses so listeners can bind deterministically.

Validation

  • go test ./internal/atunnel (privileged IPv4 and IPv6 redirect tests)
  • NO_COLOR= GOCACHE=/tmp/substrate-go-build-user make verify

@krsnaSuraj

Copy link
Copy Markdown

Deep-reviewed this against current Linux master kernel sources (net/netfilter/nf_conntrack_proto.c, net/ipv4/netfilter/ip_tables.c, net/ipv6/netfilter/ip6_tables.c, net/ipv6/af_inet6.c, include/uapi/linux/netfilter_ipv6/ip6_tables.h) and ran a live veth/netns/nftables repro. The core approach is correct; a few issues below.

Verified correct

  1. Constant 80 is right. IP6T_SO_ORIGINAL_DST = 80 confirmed in ip6_tables.h (master and v5.4). The kernel handler is so_getorigdst6 in nf_conntrack_proto.c, reached via ipv6_getsockopt → do_ipv6_getsockopt → nf_getsockopt(PF_INET6, 80).
  2. ENOENT fallback is sound. For a pure-v6 accepted socket, SOL_IP/SO_ORIGINAL_DST routes through ip_getsockopt and builds a PF_INET conntrack tuple from inet_rcv_saddr/inet_daddr — which are zeroed for pure-v6 sockets (verified in af_inet6.c), so the lookup deterministically misses with ENOENT and the fallback fires correctly. errors.Is(errno, unix.ENOENT) works (Errno implements Is).
  3. atunnel: bind actor ingress/egress listeners dual-stack (:port) #978 scenario handled. A v6 flow accepted then failing the v4 lookup is exactly the case the ENOENT→SOL_IPV6+80 fallback resolves, verified through the full kernel dispatch chain and the downstream Go CONNECT path (validateDestination/requestHostname accept bracketed [fd00::1]:port).

Findings

MAJOR-1: Error masking on ordinary IPv4 sockets

original_dst_linux.go:48-55 — for a normal IPv4 connection (no REDIRECT, no conntrack entry), SOL_IP+80 returns ENOENT, then the code tries SOL_IPV6+80 on an AF_INET socket. Kernel behavior: do_ip_getsockopt returns -EOPNOTSUPP for level != SOL_IP, and ip_getsockopt only falls through to nf_getsockopt on -ENOPROTOOPT — so the v6 attempt overwrites the meaningful ENOENT with EOPNOTSUPP, and callers now get operation not supported instead of no such file or directory. Real behavior regression for non-redirected connections.

Fix: only attempt the v6 fallback when the socket is actually v6 (conn.RemoteAddr()/LocalAddr() .To4() == nil), or preserve the original ENOENT when the v6 attempt fails with EOPNOTSUPP/ENOPROTOOPT.

MAJOR-2: Tests hard-fail (not skip) on hosts with a default-deny input firewall

original_dst_linux_test.go:78-84,128-135 — both tests install a REDIRECT into { type nat hook prerouting }, but the redirected SYN is locally delivered and traverses the host INPUT chain. On hosts running ufw/firewalld with default-deny input (verified live on this host), the SYN is dropped, the 1s accept deadline expires, and the test calls t.Fatalf. Skips only cover EPERM (CAP failure), not firewall policy. hack/run-root-tests.sh runs these under sudo on dev machines, so this will red on common Ubuntu/Proxmox setups — even though GitHub ubuntu-latest (no ufw) passes.

Fix: have the test install its own filter-chain accept rule for the redirect port (own table, priority filter, before ufw), matching production wiring — or probe the connect and t.Skip with a clear reason. Consider raising the 1s deadline.

MINOR-3: Production IPv6 path is still dead code

cmd/ateom-gvisor/main.go:62,206 and cmd/ateom-microvm/main.go bind egress to 0.0.0.0:15001 (IPv4-only), and internal/ateomnet/net.go:243 says actor networking is IPv4-only (TODO for IPv6 veth/nftables; InstallActorNftablesRules uses TableFamilyIPv4 only). So no production v6 flow can reach TCPOriginalDestination today — this PR is preparatory, not e2e-complete. Worth marking it as such and referencing the follow-up (#1057/#945/#686).

NIT-4: ENOENT mechanism undocumented

Add the why: pure-v6 sockets leave inet_rcv_saddr/inet_daddr zeroed → PF_INET tuple of 0.0.0.0:port–0.0.0.0:port → conntrack miss; v4-mapped flows stay on the v4 path. This also documents the theoretical false-hit assumption.

NIT-5: getOriginalDestination ignores size in/out

Kernel validates *len >= sizeof(sockaddr_in[6]) and returns EINVAL otherwise; the PR passes exact sizes so it works, but a comment documenting 16/28-byte buffers would harden future edits.

NIT-6: No unprivileged unit tests

All 395 lines are root-gated integration tests (valuable!). But formatOriginalDestination (port-zero handling, v4/v6 formatting) and the fallback decision have zero unit coverage — those would run on any dev machine.

NIT-7: Test hygiene

installOriginalDstRedirect/installOriginalDstIPv6Redirect don't restrict by iif; fine in isolation, but adding iif vrepro0/atod* would make rules collision-proof. The ~60-line duplicated veth setup could be shared.


Overall: solid kernel-correct change; address MAJOR-1 (error masking) before merge, and consider MAJOR-2 for dev-machine friendliness. The rest are nits.

@ygao-g

Yuan Gao (ygao-g) commented Aug 20, 2026

Copy link
Copy Markdown
Collaborator

Two asks; the rest of the PR I would take as is.

1. Gate the IPv6 fallback on the connection's family. krsnaSuraj's MAJOR-1, taking the first of the two options they offered — To4() on the local address rather than the socket domain, so a v4-mapped connection is still treated as IPv4. Drops a syscall on the common path too.

diff --git a/internal/atunnel/original_dst_linux.go b/internal/atunnel/original_dst_linux.go
index 8b430911..bd8b7646 100644
--- a/internal/atunnel/original_dst_linux.go
+++ b/internal/atunnel/original_dst_linux.go
@@ -43,14 +43,23 @@ func TCPOriginalDestination(conn net.Conn) (string, error) {
 		return "", fmt.Errorf("atunnel: acquiring TCP syscall connection: %w", err)
 	}
 
+	// The IPv6 option is only meaningful on an AF_INET6 socket: on AF_INET the
+	// kernel returns EOPNOTSUPP, which would mask the real IPv4 error. A
+	// v4-mapped local address still means an IPv4 flow, so To4 is the test.
+	local, ok := tcpConn.LocalAddr().(*net.TCPAddr)
+	if !ok {
+		return "", fmt.Errorf("atunnel: original destination requires a TCP local address, got %T", tcpConn.LocalAddr())
+	}
+	isIPv6 := local.IP.To4() == nil
+
 	var sockoptErr error
 	var destination string
 	if err := rawConn.Control(func(fd uintptr) {
 		destination, sockoptErr = originalIPv4Destination(fd)
-		// Linux returns ENOENT when the IPv4 original-destination option is
-		// queried on a redirected IPv6 connection. Only then try the IPv6
-		// equivalent, so unrelated IPv4 failures retain their original error.
-		if errors.Is(sockoptErr, unix.ENOENT) {
+		// A pure-IPv6 socket leaves the inet addresses zeroed, so the IPv4
+		// conntrack lookup always misses with ENOENT. That is the redirected
+		// IPv6 connection, and the only case worth retrying.
+		if isIPv6 && errors.Is(sockoptErr, unix.ENOENT) {
 			destination, sockoptErr = originalIPv6Destination(fd)
 		}
 	}); err != nil {

2. A regression test. The non-obvious part is that it has to run in a fresh netns. Conntrack tracks loopback in any namespace carrying nftables rules, including the one Docker runs in, so in the host namespace SOL_IP/80 succeeds and the unfixed code passes — my first attempt at this unprivileged was green against the bug. In a clean namespace it is a real gate: operation not supported without the change, pass with it. Both existing tests still pass.

Test diff
diff --git a/internal/atunnel/original_dst_linux_test.go b/internal/atunnel/original_dst_linux_test.go
index 4f26d980..36122c5d 100644
--- a/internal/atunnel/original_dst_linux_test.go
+++ b/internal/atunnel/original_dst_linux_test.go
@@ -22,6 +22,7 @@ import (
 	"fmt"
 	"net"
 	"os"
+	"runtime"
 	"strings"
 	"testing"
 	"time"
@@ -37,6 +38,63 @@ import (
 	"github.com/agent-substrate/substrate/internal/roottest"
 )
 
+// TestTCPOriginalDestinationPreservesErrno covers the failure path on an
+// ordinary connection that no REDIRECT rule touched. The IPv4 lookup misses
+// and reports ENOENT; that error must reach the caller. Retrying the IPv6
+// option on an AF_INET socket would replace it with EOPNOTSUPP, which says
+// nothing about why the lookup failed.
+//
+// It runs in a fresh namespace because conntrack tracks loopback in any
+// namespace that has nftables rules — including the one docker runs in — and a
+// tracked connection returns its real destination instead of missing.
+func TestTCPOriginalDestinationPreservesErrno(t *testing.T) {
+	roottest.Require(t, "CAP_SYS_ADMIN for a network namespace with no conntrack hooks")
+
+	ns := newTestNetNS(t)
+	runtime.LockOSThread()
+	defer runtime.UnlockOSThread()
+	host, err := netns.Get()
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer func() {
+		if err := netns.Set(host); err != nil {
+			t.Errorf("restoring host network namespace: %v", err)
+		}
+		_ = host.Close()
+	}()
+	if err := netns.Set(ns); err != nil {
+		t.Fatal(err)
+	}
+	loopback, err := netlink.LinkByName("lo")
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := netlink.LinkSetUp(loopback); err != nil {
+		t.Fatal(err)
+	}
+
+	listener, err := net.Listen("tcp4", "127.0.0.1:0")
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer listener.Close()
+	client, err := net.Dial("tcp4", listener.Addr().String())
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer client.Close()
+	server, err := listener.Accept()
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer server.Close()
+
+	if _, err := TCPOriginalDestination(server); !errors.Is(err, unix.ENOENT) {
+		t.Fatalf("want the IPv4 lookup's ENOENT, got %v", err)
+	}
+}
+
 func TestTCPOriginalDestination(t *testing.T) {
 	roottest.Require(t, "CAP_NET_ADMIN + CAP_SYS_ADMIN for an actor-like network namespace and nftables REDIRECT rule")

On MAJOR-1's severity. I probed the errnos directly:

socket conntrack entry SOL_IP/80 SOL_IPV6/80
tcp4 yes OK EOPNOTSUPP(95)
tcp4 no ENOENT(2) EOPNOTSUPP(95)
tcp6 yes ENOENT(2) OK
tcp6 no ENOENT(2) ENOENT(2)

Row 3 is your design, working as intended. Row 2 is the bug — but it needs an IPv4 connection with no conntrack entry, and the one consumer in egress.go logs the error without inspecting it. That makes it one log line's wording on an already-failing path: worth fixing, but I would not block on it.

Your tests have run in CI, just not here. This PR's workflow has been queued in action_required since 2026-08-05, but the commit rides in #1084 (729f95f1) and #1065 (5ad28ad0), and pr-workflow is green on both — run 32332600501, where TestTCPOriginalDestination and TestTCPOriginalDestinationIPv6 both pass. That also settles MAJOR-2 for the merge gate: no default-deny firewall on the runner.

Diffs are illustration, not a patch to apply verbatim.

@ygao-g Yuan Gao (ygao-g) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The IPv6 support looks right. One thing to fix before it merges: TestTCPOriginalDestinationIPv6 is flaky at about 15%.

The fix: raise the four hardcoded one-second deadlines in internal/atunnel/original_dst_linux_test.go to ten seconds — the dial timeout and the accept deadline in each of the two tests:

line today proposed
70 net.DialTimeout("tcp4", …, time.Second) 10*time.Second
78 SetDeadline(time.Now().Add(time.Second)) Add(10*time.Second)
120 net.DialTimeout("tcp6", …, time.Second) 10*time.Second
128 SetDeadline(time.Now().Add(time.Second)) Add(10*time.Second)

Nothing waits out the full timeout on a passing run, so this costs no wall clock.

Why: 60 runs on this branch alone gave 9 failures, always the same shape:

original_dst_linux_test.go:133: accepting redirected IPv6 connection:
  accept tcp6 [fd00:198:18:b163::1]:41753: i/o timeout

The slow passes land at 1.05–1.13s — one dropped SYN retransmitted at TCP's 1s initial RTO while neighbour discovery resolves on a just-created veth. It isn't DAD; both addresses already carry IFA_F_NODAD. With all four raised I measured 0 failures in 60 runs.

This is consistent with the green run I cited in my earlier comment — one pass doesn't exclude a 15% rate.

The IPv4 test carries the same two deadlines and the same exposure — it just wins the race more often, because ARP resolves faster than ND. The root-gated suite runs rarely today so the rate is invisible upstream, but it will start failing unrelated PRs once this is in.

@lubingtan

Copy link
Copy Markdown
Author

Thanks, Yuan Gao (@ygao-g) — addressed both points in the latest two commits:

  1. 0074fcc5 gates the IPv6 retry on a pure IPv6 local address (To4() == nil), so IPv4 and v4-mapped connections preserve the IPv4 lookup's original error. It also adds TestTCPOriginalDestinationPreservesErrno, which runs an ordinary IPv4 loopback connection in a fresh network namespace and asserts that an untouched connection returns ENOENT. Before the guard, this regression test reproduces the EOPNOTSUPP masking behavior.
  2. 1bd1af53 raises the dial timeout and accept deadline from one to ten seconds in both the IPv4 and IPv6 redirect tests, avoiding the veth neighbour-resolution retransmission race without adding latency to successful runs.

Thanks for the detailed errno matrix and the flake investigation.

Comment on lines +57 to 63
destination, sockoptErr = originalIPv4Destination(fd)
// A pure-IPv6 socket leaves the inet addresses zeroed, so the IPv4
// conntrack lookup always misses with ENOENT. That is the redirected
// IPv6 connection, and the only case worth retrying.
if isIPv6 && errors.Is(sockoptErr, unix.ENOENT) {
destination, sockoptErr = originalIPv6Destination(fd)
}

@ygao-g Yuan Gao (ygao-g) Aug 21, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: dispatch on isIPv6 rather than falling back on ENOENT.

Suggested change
destination, sockoptErr = originalIPv4Destination(fd)
// A pure-IPv6 socket leaves the inet addresses zeroed, so the IPv4
// conntrack lookup always misses with ENOENT. That is the redirected
// IPv6 connection, and the only case worth retrying.
if isIPv6 && errors.Is(sockoptErr, unix.ENOENT) {
destination, sockoptErr = originalIPv6Destination(fd)
}
if isIPv6 {
destination, sockoptErr = originalIPv6Destination(fd)
return
}
destination, sockoptErr = originalIPv4Destination(fd)

As written the IPv4 lookup always runs first, and on a pure IPv6 socket it is guaranteed to miss — the PF_INET conntrack tuple is built from inet_rcv_saddr/inet_daddr, which are zeroed — so that guaranteed ENOENT is what signals the retry. Dispatching directly is one syscall on both paths and doesn't rest on that detail, since isIPv6 already holds the answer.

Worth landing together with a dual-stack test case: the unconditional IPv4 call currently covers for a misclassified v4-mapped flow, and this makes To4() load-bearing.

return "", fmt.Errorf("atunnel: accessing TCP socket: %w", err)
}
if sockoptErr != nil {
return "", fmt.Errorf("atunnel: reading original TCP destination: %w", sockoptErr)

@ygao-g Yuan Gao (ygao-g) Aug 21, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: name the family that missed.

Suggested change
return "", fmt.Errorf("atunnel: reading original TCP destination: %w", sockoptErr)
family := "IPv4"
if isIPv6 {
family = "IPv6"
}
return "", fmt.Errorf("atunnel: reading original %s TCP destination: %w", family, sockoptErr)

Both option levels report a miss as ENOENT, so the message as it stands doesn't say which lookup ran.

@ygao-g

Copy link
Copy Markdown
Collaborator

I put your three commits on a branch with the two suggested changes applied, so there's something concrete to look at rather than just prose:

https://github.com/ygao-g/substrate/pull/8/files

It's on my fork and isn't proposed for merge. Your three commits are unchanged and still authored by you; the two on top are the suggestions — e6969fab for the dispatch and dc915c6c for the tests. Cherry-pick, adapt or ignore.

Two suggestions are inline above. The rest:

Run the redirect tests in their own netns. They currently build the veth, the NAT table and both listeners in the host namespace. Under a default-deny INPUT policy the redirected SYN is dropped and both tests fail on the accept deadline — 10s each, so the 1s→10s change made them fail slower rather than pass. In throwaway namespaces the same tests pass in 0.07s. Root-gated tests run on every PR now, so as written this reds for anyone with ufw or firewalld on. Private namespaces also make the PID-derived addresses and interface names unnecessary — uint16(os.Getpid()) truncates wherever pid_max is above 65535.

Add a dual-stack case. atunnel listens on an unspecified address, which Go opens as one dual-stack AF_INET6 socket, so every IPv4 actor arrives with a v4-mapped local address. That's the case To4() exists for and nothing covers it — I checked by seeding that misclassification, and every test here passes against it.

Cover formatOriginalDestination without root. All 442 new lines are root-gated, so the ordinary go test ./... lane runs nothing for this file. Port-zero rejection, bracketing and v4-mapped rendering are pure functions.

Worth rebasing before any of this — you're 177 behind main, and pr-workflow gained the root-gated step inside that window — then asking a maintainer to approve workflows. CI has never run on this PR: action_required on both head SHAs. The branch above is green in an integration branch that does have CI.

One difference there: ateomnet.IPv6SourceEqual doesn't exist on main yet, so the IPv6 source match is a local helper in the test rather than a call into ateomnet.

@ygao-g

Copy link
Copy Markdown
Collaborator

SURAJ KUMAR (@krsnaSuraj) on MINOR-3 — the conclusion holds, but one detail in the reasoning doesn't.

0.0.0.0:15001 is not an IPv4 pin. cmd/ateom-gvisor/main.go:280 does net.Listen("tcp", *atunnelEgressListenAddress), and Go's favoriteAddrFamily returns AF_INET6 with IPV6_V6ONLY off for any unspecified address, so 0.0.0.0:15001 and :15001 produce the identical dual-stack socket. Worth flagging because it's the reverse of Envoy, where the spelling genuinely does pin the family.

The other half of MINOR-3 is the load-bearing one and it's right: internal/ateomnet/net.go:233 and the TableFamilyIPv4 at :251 are what keep any v6 flow away from this code, so the PR is preparatory either way. #1116 and #1057 are the actual gate. #1080 makes the same spelling change for the ingress defaults; egress 15001 still reads as IPv4-only and isn't covered by it.

@krsnaSuraj

Copy link
Copy Markdown

Yuan Gao (@ygao-g) — you're right, and I was wrong on the load-bearing detail. Confirmed empirically on Go 1.26.3: net.Listen("tcp", "0.0.0.0:15001") binds [::]:15001 with IPV6_V6ONLY=0 / SO_DOMAIN=10 (AF_INET6), so it is not an IPv4 pin — 0.0.0.0:15001 and :15001 yield the identical dual-stack socket. My "IPv4-only" characterisation in MINOR-3 was incorrect.

The conclusion still holds — production IPv6 remains dead code until the veth/nftables path gains dual-stack (internal/ateomnet/net.go TableFamilyIPv4 and the TCPOriginalDestination TODO), so this PR is preparatory — but the reasoning needs the correction you made: the local.IP.To4() == nil classification is what's load-bearing, and the zeroed-inet-addresses detail is the mechanism, not a reason to read the socket as IPv4.

Also agreed on the dispatch suggestion and the family-in-error-message nit — both are strictly cleaner than the ENOENT-fallback and I'd take them. Thanks for the dual-stack test-case warning too; that's exactly the v4-mapped blind spot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

atunnel: IPv6 support for original destination lookup

3 participants