Skip to content

atunnel: support IPv6 original destination lookup - #753

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

atunnel: support IPv6 original destination lookup#753
Bingtan Lu (lubingtan) wants to merge 1 commit 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.

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