package traffic import ( "context" "encoding/binary" "fmt" "io" "net" "net/http" "net/url" "testing" "time" "gvisor.dev/gvisor/pkg/tcpip" "gvisor.dev/gvisor/pkg/tcpip/checksum" "gvisor.dev/gvisor/pkg/tcpip/header" ) // memTunPipe simulates a Linux TUN L3 packet device in memory so NetstackGateway's // deferred TCP handshake (SYN-ACK on open vs RST on closed/blocked) can be tested // deterministically on any OS without CAP_NET_ADMIN. type memTunPipe struct { in chan []byte out chan []byte end chan struct{} } func newMemTunPipe() *memTunPipe { return &memTunPipe{ in: make(chan []byte, 64), out: make(chan []byte, 64), end: make(chan struct{}), } } func (p *memTunPipe) Read(b []byte) (int, error) { select { case pkt := <-p.in: return copy(b, pkt), nil case <-p.end: return 0, io.EOF } } func (p *memTunPipe) Write(b []byte) (int, error) { cp := append([]byte(nil), b...) select { case p.out <- cp: return len(b), nil case <-p.end: return 0, io.ErrClosedPipe } } func (p *memTunPipe) Close() error { select { case <-p.end: default: close(p.end) } return nil } func buildIPv4TCPSYN(srcIP, dstIP net.IP, srcPort, dstPort uint16, seq uint32) []byte { const ipLen = header.IPv4MinimumSize const tcpLen = header.TCPMinimumSize pkt := make([]byte, ipLen+tcpLen) ip := header.IPv4(pkt[:ipLen]) ip.Encode(&header.IPv4Fields{ TotalLength: uint16(len(pkt)), ID: 1, TTL: 64, Protocol: uint8(header.TCPProtocolNumber), SrcAddr: header.IPv4(pkt).SourceAddress(), // overwritten below }) copy(pkt[12:16], srcIP.To4()) copy(pkt[16:20], dstIP.To4()) ip.SetChecksum(0) ip.SetChecksum(^ip.CalculateChecksum()) tcpHdr := header.TCP(pkt[ipLen:]) binary.BigEndian.PutUint16(tcpHdr[0:2], srcPort) binary.BigEndian.PutUint16(tcpHdr[2:4], dstPort) binary.BigEndian.PutUint32(tcpHdr[4:8], seq) tcpHdr[12] = (tcpLen / 4) << 4 tcpHdr[13] = uint8(header.TCPFlagSyn) binary.BigEndian.PutUint16(tcpHdr[14:16], 65535) xsum := header.PseudoHeaderChecksum(header.TCPProtocolNumber, ip.SourceAddress(), ip.DestinationAddress(), uint16(tcpLen)) xsum = checksum.Checksum(tcpHdr, xsum) tcpHdr.SetChecksum(^xsum) return pkt } func parseTCPFlags(pkt []byte) (header.TCPFlags, bool) { if len(pkt) < header.IPv4MinimumSize+header.TCPMinimumSize || header.IPVersion(pkt) != header.IPv4Version { return 0, false } ip := header.IPv4(pkt) if ip.TransportProtocol() != header.TCPProtocolNumber { return 0, false } tcpHdr := header.TCP(pkt[ip.HeaderLength():]) return tcpHdr.Flags(), true } func TestNetstackDeferredTCPHandshakeOpenClosedBlocked(t *testing.T) { tr, err := Open(t.TempDir(), "127.0.0.1:0") if err != nil { t.Fatalf("open traffic: %v", err) } defer tr.Close() tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { if srcIP == "172.30.0.3" { return SourceIdentity{Scope: "task", OwnerID: "218", ContainerID: "sbx218", SrcIP: srcIP}, true } return SourceIdentity{}, false }) tr.SetEgressBlacklist([]EgressBlacklistRule{ {ID: "blk-1", Enabled: true, Kind: "ip", Pattern: "198.51.100.99"}, }) // 1. Start a real open TCP listener on loopback. openLn, err := net.Listen("tcp4", "127.0.0.1:0") if err != nil { t.Fatalf("listen open: %v", err) } defer openLn.Close() go func() { for { c, err := openLn.Accept() if err != nil { return } _ = c.Close() } }() openPort := uint16(openLn.Addr().(*net.TCPAddr).Port) // 2. Reserve and immediately close a port to guarantee ECONNREFUSED ("closed"). closedLn, err := net.Listen("tcp4", "127.0.0.1:0") if err != nil { t.Fatalf("listen closed probe: %v", err) } closedPort := uint16(closedLn.Addr().(*net.TCPAddr).Port) _ = closedLn.Close() pipe := newMemTunPipe() ns, err := NewNetstackGateway(pipe, NetstackConfig{ DialTimeout: 200 * time.Millisecond, PeekTimeout: 50 * time.Millisecond, DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) { switch target { case fmt.Sprintf("203.0.113.10:%d", openPort): return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", openPort), timeout) case fmt.Sprintf("203.0.113.10:%d", closedPort): return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", closedPort), timeout) case "203.0.113.20:80": return nil, context.DeadlineExceeded default: return dialTCPThroughUpstream(ctx, upstream, target, timeout) } }, }, LocalTransparentBackend{T: tr}) if err != nil { t.Fatalf("NewNetstackGateway: %v", err) } ns.Start() defer ns.Close() readReplyFlags := func(t *testing.T, label string) header.TCPFlags { t.Helper() select { case pkt := <-pipe.out: flags, ok := parseTCPFlags(pkt) if !ok { t.Fatalf("%s: non-TCP reply packet (%d bytes)", label, len(pkt)) } return flags case <-time.After(3 * time.Second): t.Fatalf("%s: timed out waiting for reply packet", label) return 0 } } // Case A: OPEN port => MUST reply SYN+ACK. pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 41001, openPort, 100) flagsOpen := readReplyFlags(t, "open port") if !flagsOpen.Contains(header.TCPFlagSyn | header.TCPFlagAck) { t.Fatalf("open port: expected SYN+ACK, got flags=%v", flagsOpen) } // Case B: CLOSED port (ECONNREFUSED) => MUST reply RST (NEVER SYN+ACK -> zero nmap false positives!). pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 41002, closedPort, 200) flagsClosed := readReplyFlags(t, "closed port") if !flagsClosed.Contains(header.TCPFlagRst) || flagsClosed.Contains(header.TCPFlagSyn) { t.Fatalf("closed port: expected RST without SYN, got flags=%v", flagsClosed) } // Case C: FILTERED port (timeout) => MUST drop silently (neither SYN+ACK nor RST!). pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.20"), 41004, 80, 250) select { case pkt := <-pipe.out: flags, _ := parseTCPFlags(pkt) t.Fatalf("filtered port: expected silent drop, got reply packet with flags=%v", flags) case <-time.After(150 * time.Millisecond): } // Case D: BLACKLISTED IP => MUST reply immediate RST and record net_flows(action=block). pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("198.51.100.99"), 41003, 80, 300) flagsBlocked := readReplyFlags(t, "blacklisted IP") if !flagsBlocked.Contains(header.TCPFlagRst) || flagsBlocked.Contains(header.TCPFlagSyn) { t.Fatalf("blacklisted IP: expected RST without SYN, got flags=%v", flagsBlocked) } deadline := time.Now().Add(2 * time.Second) var blocked []NetFlowRecord for time.Now().Before(deadline) { rows, _, _ := tr.PageNetFlows(NetFlowQuery{OwnerTaskID: "218", Action: "block"}, 0, 10) if len(rows) > 0 { blocked = rows break } time.Sleep(20 * time.Millisecond) } if len(blocked) != 1 || blocked[0].DstIP != "198.51.100.99" { t.Fatalf("expected 1 blocked net_flow for 198.51.100.99, got %+v", blocked) } } func TestGatewayTokenAttributionAcrossDockerBridge(t *testing.T) { tr, err := Open(t.TempDir(), "127.0.0.1:0") if err != nil { t.Fatalf("open traffic: %v", err) } defer tr.Close() tr.SetGatewayToken("gw-secret-218") tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { if srcIP == "172.30.0.3" { return SourceIdentity{Scope: "session", OwnerID: "conv-6", ContainerID: "abcdef123456", SrcIP: srcIP}, true } return SourceIdentity{}, false }) // Simulated docker-proxy source IP (172.19.0.1) carrying valid gateway token must resolve to 172.30.0.3 / session:conv-6. authVal := FormatProxyContextAuthValue(SourceIdentity{SrcIP: "172.30.0.3"}, "gw-secret-218") h := http.Header{"Proxy-Authorization": []string{"Basic " + authVal}} src := tr.resolveSourceForConn("172.19.0.1:51234", h) if src.SrcIP != "172.30.0.3" || src.Scope != "session" || src.OwnerID != "conv-6" { t.Fatalf("valid gateway token from docker-proxy should preserve attribution, got %+v", src) } // Wrong token from non-loopback must NOT trust forwarded SrcIP. badVal := FormatProxyContextAuthValue(SourceIdentity{SrcIP: "172.30.0.3"}, "wrong-token") hBad := http.Header{"Proxy-Authorization": []string{"Basic " + badVal}} srcBad := tr.resolveSourceForConn("172.19.0.1:51235", hBad) if srcBad.SrcIP != "172.19.0.1" || srcBad.Scope != "" { t.Fatalf("invalid gateway token must not spoof attribution, got %+v", srcBad) } } func TestSSRFGuardHostNetworkModeInfraPorts(t *testing.T) { g := newSSRFGuard(SSRFGuardConfig{ Enabled: true, InfraIPs: []net.IP{net.ParseIP("192.168.110.238")}, HostNetworkMode: true, }) if r := g.Check("192.168.110.238:8787"); r == "" { t.Fatalf("expected :8787 on host LAN IP to be blocked") } if r := g.Check("192.168.110.238:8788"); r == "" { t.Fatalf("expected :8788 on host LAN IP to be blocked") } if r := g.Check("192.168.110.238:22"); r != "" { t.Fatalf("expected :22 on host LAN IP to remain reachable, got %q", r) } if r := g.Check("127.0.0.1:80"); r == "" { t.Fatalf("expected loopback 127.0.0.1:80 to remain blocked") } } func buildIPv4ICMPEcho(srcIP, dstIP net.IP, id, seq uint16, payload []byte) []byte { totalLen := header.IPv4MinimumSize + header.ICMPv4MinimumSize + len(payload) pkt := make([]byte, totalLen) ip := header.IPv4(pkt[:header.IPv4MinimumSize]) ip.Encode(&header.IPv4Fields{ TotalLength: uint16(totalLen), TTL: 64, Protocol: uint8(header.ICMPv4ProtocolNumber), SrcAddr: tcpip.AddrFrom4Slice(srcIP.To4()), DstAddr: tcpip.AddrFrom4Slice(dstIP.To4()), }) ip.SetChecksum(^ip.CalculateChecksum()) icmp := header.ICMPv4(pkt[header.IPv4MinimumSize:]) icmp.SetType(header.ICMPv4Echo) icmp.SetCode(0) icmp.SetIdent(id) icmp.SetSequence(seq) copy(pkt[header.IPv4MinimumSize+header.ICMPv4MinimumSize:], payload) icmp.SetChecksum(0) icmp.SetChecksum(header.ICMPv4Checksum(icmp, 0)) return pkt } func TestNetstackAntiSpoofingAndICMPProxy(t *testing.T) { tr, err := Open(t.TempDir(), "127.0.0.1:0") if err != nil { t.Fatalf("open traffic: %v", err) } defer tr.Close() tr.SetEgressBlacklist([]EgressBlacklistRule{{ ID: "blk-icmp", Kind: "ip", Pattern: "203.0.113.99", Enabled: true, }}) pipe := newMemTunPipe() ng, err := NewNetstackGateway(pipe, NetstackConfig{ DialTimeout: 300 * time.Millisecond, AllowedSrcCIDR: "172.30.0.0/16", DeniedSrcIPs: []string{"172.30.0.1"}, ICMPPingFunc: func(_ context.Context, dstIP net.IP, _ uint16, payload []byte) ([]byte, error) { if dstIP.String() == "203.0.113.10" { return payload, nil } return nil, context.DeadlineExceeded }, }, LocalTransparentBackend{T: tr}) if err != nil { t.Fatalf("NewNetstackGateway: %v", err) } ng.Start() defer ng.Close() // 1. Live host ICMP Echo -> genuine Echo Reply with matching ID/Seq/Payload. pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 0x1234, 7, []byte("ping-ok")) select { case resp := <-pipe.out: ip4 := header.IPv4(resp) if ip4.Protocol() != uint8(header.ICMPv4ProtocolNumber) { t.Fatalf("expected ICMPv4 reply, got proto=%d", ip4.Protocol()) } icmp := header.ICMPv4(resp[ip4.HeaderLength():]) if icmp.Type() != header.ICMPv4EchoReply || icmp.Ident() != 0x1234 || icmp.Sequence() != 7 || string(icmp.Payload()) != "ping-ok" { t.Fatalf("unexpected ICMP echo reply: type=%d id=%#x seq=%d payload=%q", icmp.Type(), icmp.Ident(), icmp.Sequence(), string(icmp.Payload())) } case <-time.After(2 * time.Second): t.Fatal("timed out waiting for ICMP echo reply from live target") } // 2. Dead host ICMP Echo -> MUST NOT receive a fake local Echo Reply from gVisor. pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.55"), 0x1234, 8, []byte("ping-dead")) select { case resp := <-pipe.out: t.Fatalf("dead host must not receive synthetic reply, got %d bytes", len(resp)) case <-time.After(250 * time.Millisecond): } // 3. Blacklisted host ICMP Echo -> no reply + recorded as blocked flow. pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.99"), 0x1234, 9, []byte("ping-blk")) select { case resp := <-pipe.out: t.Fatalf("blacklisted host must not receive reply, got %d bytes", len(resp)) case <-time.After(200 * time.Millisecond): } // 4. Spoofed source IP outside AllowedSrcCIDR or equal to gateway IP -> silently dropped. pipe.in <- buildIPv4ICMPEcho(net.ParseIP("10.99.0.5"), net.ParseIP("203.0.113.10"), 0x5678, 1, []byte("spoof-ext")) pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.1"), net.ParseIP("203.0.113.10"), 0x5678, 2, []byte("spoof-gw")) select { case resp := <-pipe.out: t.Fatalf("spoofed source packet must be dropped, got %d bytes", len(resp)) case <-time.After(200 * time.Millisecond): } deadline := time.Now().Add(2 * time.Second) var flows []NetFlowRecord var total int for time.Now().Before(deadline) { flows, total, err = tr.PageNetFlows(NetFlowQuery{Protocol: "icmp"}, 0, 20) if err == nil && total >= 3 { break } time.Sleep(20 * time.Millisecond) } if err != nil || total < 3 { t.Fatalf("expected >=3 recorded icmp flows (allow/error/block), got total=%d err=%v flows=%+v", total, err, flows) } }