Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion e2e/Dockerfile.devcontainer
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ FROM alpine:3.20
# Install runtime dependencies
# iptables is needed for traffic interception
# openssh-client is needed for SSH connections
RUN apk add --no-cache ca-certificates iptables openssh-client busybox-extras curl
# shadow-login provides sg, which the bridge feature runs intercept under
RUN apk add --no-cache ca-certificates iptables openssh-client busybox-extras curl shadow-login

# The group the bridge feature runs intercept as, so iptables can tell
# bridge's own traffic apart from the app's.
RUN addgroup -S _bridge

# Copy the pre-built binary
COPY bridge /usr/local/bin/bridge
Expand Down
69 changes: 69 additions & 0 deletions e2e/intercept_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,75 @@ func (s *InterceptSuite) TestIngress() {
require.Contains(t, wgetOutput, "ok", "expected 'ok' from test server via ingress tunnel")
}

// startWitness starts a container on the bridge network under the alias
// "witness", a name the intercept container's own Docker DNS can answer
// without the tunnel. It returns the witness's IP.
func (s *InterceptSuite) startWitness(t *testing.T) string {
witnessC, err := testcontainers.GenericContainer(s.ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: s.interceptImg,
Cmd: []string{"sleep", "300"},
Networks: []string{s.bridgeNet.Name},
NetworkAliases: map[string][]string{
s.bridgeNet.Name: {"witness"},
},
},
Started: true,
})
require.NoError(t, err, "failed to start witness container")
t.Cleanup(func() { testcontainers.TerminateContainer(witnessC) })

inspect, err := witnessC.Inspect(s.ctx)
require.NoError(t, err, "failed to inspect witness container")
ip := inspect.NetworkSettings.Networks[s.bridgeNet.Name].IPAddress
require.NotEmpty(t, ip, "witness container has no IP on bridge network")
return ip
}

// TestBridgeResolvesWhileTunnelIsDown drops the tunnel under a running
// intercept. Redialing the proxy needs real DNS (in a cluster: the API server,
// then aws eks get-token → STS), so bridge's own group must still resolve
// names while the tunnel is down, or the redial asks the broken tunnel and the
// intercept never recovers. The app must not: its names belong to the tunnel.
func (s *InterceptSuite) TestBridgeResolvesWhileTunnelIsDown() {
t := s.T()

proxyC, proxyIP := s.startProxy(t, []string{"bridge", "--log-paths", "stderr", "server", "--addr", ":9090"})
interceptC := s.startIntercept(t)
witnessIP := s.startWitness(t)

// Run intercept the way the bridge feature does: as root, under _bridge.
exitCode, reader, err := interceptC.Exec(s.ctx, []string{
"sh", "-c",
fmt.Sprintf(`sg _bridge -c 'bridge --log-paths stderr intercept --server-addr %s:9090 --forward-domains "*"' > /tmp/bridge-intercept.log 2>&1 &`, proxyIP),
})
require.NoError(t, err, "failed to exec bridge intercept")
io.Copy(io.Discard, reader)
require.Equal(t, 0, exitCode, "bridge intercept exec failed")

ct := container.NewDockerClient()
require.NoError(t, intercept.WaitForReady(s.ctx, ct, interceptC.GetContainerID()), "bridge intercept did not become ready")

stopTimeout := 5 * time.Second
require.NoError(t, proxyC.Stop(s.ctx, &stopTimeout), "failed to stop proxy")
t.Log("Proxy stopped; the tunnel is down")

lookup := func(cmd string) string {
_, reader, err := interceptC.Exec(s.ctx, []string{"sh", "-c", cmd})
require.NoError(t, err, "lookup exec failed: %s", cmd)
data, _ := io.ReadAll(reader)
t.Logf("[%s]\n%s", cmd, strings.TrimSpace(string(data)))
return string(data)
}

// The trailing dot stops busybox nslookup from trying only the host's
// search domain (GitHub runners inherit an Azure one).
require.Contains(t, lookup(`sg _bridge -c 'nslookup witness.'`), witnessIP,
"bridge's own lookups must not depend on the tunnel")
require.NotContains(t, lookup(`nslookup witness.`), witnessIP,
"the app's lookups must still go through the tunnel, not around it")
}

func TestInterceptSuite(t *testing.T) {
suite.Run(t, new(InterceptSuite))
}
32 changes: 23 additions & 9 deletions pkg/commands/intercept.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ func doIntercept(ctx context.Context, c *cli.Command) error {
registry := conntrack.New(pool)

// Start DNS (optional)
var dns *DNSComponent
var dns, bypassDNS *DNSComponent
var originalResolvConf []byte
if len(forwardDomains) > 0 {
// Read the original nameserver before we modify /etc/resolv.conf
Expand All @@ -228,6 +228,13 @@ func doIntercept(ctx context.Context, c *cli.Command) error {
return fmt.Errorf("failed to start DNS: %w", err)
}

bypassDNS, err = StartBypassDNS(originalNS)
if err != nil {
dns.Stop()
registry.Stop()
return fmt.Errorf("failed to start bypass DNS: %w", err)
}

// Point /etc/resolv.conf at our DNS server
originalResolvConf, err = updateResolvConf("127.0.0.1")
if err != nil {
Expand All @@ -236,21 +243,25 @@ func doIntercept(ctx context.Context, c *cli.Command) error {
}

// Start proxy (transparent proxy + tunnel)
var dnsPortForIPTables int
var dnsPortForIPTables, bypassDNSPort int
if dns != nil {
dnsPortForIPTables = dns.Port()
}
if bypassDNS != nil {
bypassDNSPort = bypassDNS.Port()
}

// Pass the current process GID so iptables can exclude bridge's own DNS
// traffic from the UDP redirect. This prevents a circular dependency when
// Pass the current process GID so iptables can send bridge's own DNS
// traffic to the bypass server. This prevents a circular dependency when
// gRPC reconnects and needs real DNS for EKS auth. GID 0 (root) is not
// excluded since that would bypass the redirect for most container processes.
proxyComp, err := StartProxy(ProxyConfig{
Tunnel: tun,
ProxyPort: proxyPort,
Registry: registry,
DNSPort: dnsPortForIPTables,
ExcludeGID: os.Getgid(),
Tunnel: tun,
ProxyPort: proxyPort,
Registry: registry,
DNSPort: dnsPortForIPTables,
ExcludeGID: os.Getgid(),
BypassDNSPort: bypassDNSPort,
})
if err != nil {
return fmt.Errorf("failed to start proxy listener: %w", err)
Expand Down Expand Up @@ -317,6 +328,9 @@ func doIntercept(ctx context.Context, c *cli.Command) error {
if dns != nil {
dns.Stop()
}
if bypassDNS != nil {
bypassDNS.Stop()
}
restoreResolvConf(originalResolvConf)
registry.Stop()
proxyComp.Stop()
Expand Down
27 changes: 27 additions & 0 deletions pkg/commands/intercept_dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,33 @@ func StartDNS(cfg DNSConfig) (*DNSComponent, error) {
}, nil
}

// StartBypassDNS starts a DNS server on a random loopback port that only asks
// upstream, never the tunnel. SetupIptables sends the intercept's own group's
// DNS here, so re-establishing a dropped tunnel never waits on that tunnel.
func StartBypassDNS(upstream string) (*DNSComponent, error) {
dnsServer, err := bridgedns.New(bridgedns.Config{
ListenAddr: "127.0.0.1:0",
Client: bridgedns.NewSystemExchangeClient(upstream),
})
if err != nil {
return nil, fmt.Errorf("failed to create bypass DNS server: %w", err)
}

go func() {
if err := dnsServer.ListenAndServe(); err != nil {
slog.Error("Bypass DNS server error", "error", err)
}
}()

port := dnsServer.Port()
slog.Info("Bypass DNS enabled for bridge's own lookups", "port", port, "upstream", upstream)

return &DNSComponent{
server: dnsServer,
port: port,
}, nil
}

// Port returns the port the DNS server is listening on.
func (d *DNSComponent) Port() int {
return d.port
Expand Down
74 changes: 42 additions & 32 deletions pkg/commands/intercept_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,23 @@ const (

// ProxyComponent manages the transparent proxy listener, tunnel client, and iptables rules.
type ProxyComponent struct {
tunnel tunnel.Tunnel
listener net.Listener
port int
registry *conntrack.Registry
dnsPort int
excludeGID int
tunnel tunnel.Tunnel
listener net.Listener
port int
registry *conntrack.Registry
dnsPort int
excludeGID int
bypassDNSPort int
}

// ProxyConfig holds configuration for starting the proxy component.
type ProxyConfig struct {
Tunnel tunnel.Tunnel
ProxyPort int // 0 = random
Registry *conntrack.Registry
DNSPort int // If >0, redirect all UDP :53 traffic to this port
ExcludeGID int // If >0, exclude this GID from DNS redirect
Tunnel tunnel.Tunnel
ProxyPort int // 0 = random
Registry *conntrack.Registry
DNSPort int // If >0, redirect all UDP :53 traffic to this port
ExcludeGID int // If >0, send this GID's UDP :53 traffic to BypassDNSPort instead
BypassDNSPort int // Upstream-only DNS server for ExcludeGID
}

// StartProxy creates a transparent proxy listener and initializes the tunnel client.
Expand All @@ -46,12 +48,13 @@ func StartProxy(cfg ProxyConfig) (*ProxyComponent, error) {
addr := listener.Addr().(*net.TCPAddr)

p := &ProxyComponent{
tunnel: cfg.Tunnel,
listener: listener,
port: addr.Port,
registry: cfg.Registry,
dnsPort: cfg.DNSPort,
excludeGID: cfg.ExcludeGID,
tunnel: cfg.Tunnel,
listener: listener,
port: addr.Port,
registry: cfg.Registry,
dnsPort: cfg.DNSPort,
excludeGID: cfg.ExcludeGID,
bypassDNSPort: cfg.BypassDNSPort,
}

return p, nil
Expand All @@ -69,6 +72,19 @@ func (p *ProxyComponent) SetupIptables() error {
return fmt.Errorf("iptables not found: %w", err)
}

for _, args := range p.iptablesRules() {
cmd := exec.Command(args[0], args[1:]...)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("iptables %v failed: %w: %s", args[1:], err, output)
}
}

slog.Info("iptables rules configured", "proxy_port", p.port, "proxy_cidr", proxyCIDR)
return nil
}

// iptablesRules returns the iptables commands SetupIptables runs, in order.
func (p *ProxyComponent) iptablesRules() [][]string {
cmds := [][]string{
// Create a new chain for our rules
{"iptables", "-t", "nat", "-N", "BRIDGE_INTERCEPT"},
Expand All @@ -85,17 +101,19 @@ func (p *ProxyComponent) SetupIptables() error {
// instead of /etc/resolv.conf. The DNS server's own fallback queries use
// TCP, so they are not affected by this rule.
if p.dnsPort > 0 {
// Exclude bridge's own GID from the DNS redirect. When the gRPC
// connection drops and reconnects, the k8spf dialer calls
// Send bridge's own GID to the bypass DNS server instead. When the
// gRPC connection drops and reconnects, the k8spf dialer calls
// resolvePod → K8s API → aws eks get-token, which needs real DNS
// to reach sts.amazonaws.com. Without this exclusion, the query
// loops back to our DNS server which depends on the broken tunnel.
if p.excludeGID > 0 {
// for the API server and sts.amazonaws.com. /etc/resolv.conf names
// only our DNS server, which asks the broken tunnel, so a RETURN
// here isn't enough: the query still reaches 127.0.0.1:53 and the
// intercept never recovers.
if p.excludeGID > 0 && p.bypassDNSPort > 0 {
cmds = append(cmds,
[]string{"iptables", "-t", "nat", "-A", "BRIDGE_INTERCEPT",
"-p", "udp", "--dport", "53",
"-m", "owner", "--gid-owner", fmt.Sprintf("%d", p.excludeGID),
"-j", "RETURN"},
"-j", "REDIRECT", "--to-ports", fmt.Sprintf("%d", p.bypassDNSPort)},
)
}
cmds = append(cmds,
Expand All @@ -104,15 +122,7 @@ func (p *ProxyComponent) SetupIptables() error {
)
}

for _, args := range cmds {
cmd := exec.Command(args[0], args[1:]...)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("iptables %v failed: %w: %s", args[1:], err, output)
}
}

slog.Info("iptables rules configured", "proxy_port", p.port, "proxy_cidr", proxyCIDR)
return nil
return cmds
}

// Start begins the transparent proxy accept loop in the background.
Expand Down
56 changes: 56 additions & 0 deletions pkg/commands/intercept_proxy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package commands

import (
"slices"
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func ruleIndex(rules [][]string, contains ...string) int {
return slices.IndexFunc(rules, func(rule []string) bool {
joined := strings.Join(rule, " ")
for _, s := range contains {
if !strings.Contains(joined, s) {
return false
}
}
return true
})
}

// The intercept's own lookups (the k8spf redial: API server, then aws eks
// get-token → STS) must reach the bypass DNS server, never the one that asks
// the tunnel they are trying to rebuild. /etc/resolv.conf names only
// 127.0.0.1, so letting the group skip the redirect isn't enough.
func TestIptablesRules_SendsBridgesOwnDNSToTheBypassServer(t *testing.T) {
p := &ProxyComponent{port: 15001, dnsPort: 53, excludeGID: 999, bypassDNSPort: 40123}
rules := p.iptablesRules()

own := ruleIndex(rules, "--gid-owner 999", "-p udp --dport 53", "-j REDIRECT --to-ports 40123")
require.NotEqual(t, -1, own, "bridge's group must be redirected to the bypass DNS server")
assert.Equal(t, -1, ruleIndex(rules, "--gid-owner 999", "-j RETURN"),
"RETURN leaves the query going to 127.0.0.1:53, which asks the broken tunnel")

everyone := ruleIndex(rules, "BRIDGE_INTERCEPT -p udp --dport 53 -j REDIRECT --to-ports 53")
require.NotEqual(t, -1, everyone)
assert.Less(t, own, everyone, "bridge's rule must come first or the general redirect wins")
}

func TestIptablesRules_NoGroupRuleWithoutABypassServerOrGroup(t *testing.T) {
for name, p := range map[string]*ProxyComponent{
"root group": {port: 15001, dnsPort: 53, excludeGID: 0, bypassDNSPort: 40123},
"no bypass server": {port: 15001, dnsPort: 53, excludeGID: 999, bypassDNSPort: 0},
} {
t.Run(name, func(t *testing.T) {
assert.Equal(t, -1, ruleIndex(p.iptablesRules(), "--gid-owner"))
})
}
}

func TestIptablesRules_NoDNSRulesWithoutDNS(t *testing.T) {
p := &ProxyComponent{port: 15001, excludeGID: 999, bypassDNSPort: 40123}
assert.Equal(t, -1, ruleIndex(p.iptablesRules(), "--dport 53"))
}
Loading
Loading