carlos / platform Public

edge: refuse link-local and IMDS addresses at upstream dial time

tcpProxy, multiProxy and the prober's transport fell back to a plain
net.Dialer in production (hold.dialer nil), so an upstream addr of
169.254.169.254, or a name resolving to it, had the edge connect to
instance metadata. They now fall back to upstreamDialer, whose Control
hook refuses 169.254.0.0/16, fe80::/10 and fd00:ec2::254 (unmapping
IPv4-in-IPv6) after resolution and before connect. Test dialers,
unix sockets, backhaul hops and tunnels are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a07691a322f31ec0d4858c67321a3ed446a1aa62 parent 89d69cf
5 files changed, +251 −17
  • internal/edge/cname_steering_test.go +13 −6
  • internal/edge/edge.go +8 −7
  • internal/edge/prober.go +10 −4
  • internal/edge/upstreamdial.go +54 −0
  • internal/edge/upstreamdial_test.go +166 −0
diff --git a/internal/edge/cname_steering_test.go b/internal/edge/cname_steering_test.go
index 959b3adbe..d7bce3afa 100644
--- a/internal/edge/cname_steering_test.go
+++ b/internal/edge/cname_steering_test.go
@@ -33,6 +33,18 @@ func TestCertWarmGateFollowsACNAMEToTheSteeringHost(t *testing.T) {
// the lookup under test is the production LookupHost, CNAME-following and
// all, with only the network swapped.
func cnameDNS(t *testing.T, chain []string, ips []string) func(string) ([]string, error) {
+ t.Helper()
+ r := cnameResolver(t, chain, ips)
+ return func(host string) ([]string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ return r.LookupHost(ctx, host)
+ }
+}
+
+// cnameResolver is cnameDNS's fake zone as the net.Resolver itself, for a
+// test that hands it to a net.Dialer.
+func cnameResolver(t *testing.T, chain []string, ips []string) *net.Resolver {
t.Helper()
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
@@ -92,13 +104,8 @@ func cnameDNS(t *testing.T, chain []string, ips []string) func(string) ([]string
_, _ = pc.WriteTo(msg, addr)
}
}()
- r := &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "udp", pc.LocalAddr().String())
}}
- return func(host string) ([]string, error) {
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
- defer cancel()
- return r.LookupHost(ctx, host)
- }
}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 4c211274f..6eeba4de1 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -4009,18 +4009,19 @@ func unixProxy(socketPath string) *httputil.ReverseProxy {
// A loopback upstream is this box's own process, so a refused dial there is
// a restart in progress: the dial is retried for hold.dial (one deadline
// fixed per dial) instead of 502ing at once. hold.dial <= 0, or a remote
-// addr, keeps the stock dialer (hold.dialer is nil in production).
+// addr, dials once. Either way the dial is upstreamDialer's (hold.dialer is
+// nil in production), which refuses link-local and IMDS addresses.
func tcpProxy(addr string, hold localHold) *httputil.ReverseProxy {
+ dial := hold.dialer
+ if dial == nil {
+ dial = upstreamDialer().DialContext
+ }
tr := &http.Transport{
MaxIdleConns: 32,
IdleConnTimeout: 90 * time.Second,
- DialContext: hold.dialer,
+ DialContext: dial,
}
if hold.dial > 0 && isLocalUpstream(addr) {
- dial := hold.dialer
- if dial == nil {
- dial = (&net.Dialer{}).DialContext
- }
tr.DialContext = func(ctx context.Context, network, a string) (net.Conn, error) {
return retryLocalDial(ctx, time.Now().Add(hold.dial), func(actx context.Context) (net.Conn, error) {
return dial(actx, network, a)
@@ -4115,7 +4116,7 @@ func multiProxy(host string, p *proberSet, hold localHold) *httputil.ReverseProx
var cursor atomic.Uint64
dial := hold.dialer
if dial == nil {
- dial = (&net.Dialer{}).DialContext
+ dial = upstreamDialer().DialContext // refuses link-local and IMDS
}
return &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) {
diff --git a/internal/edge/prober.go b/internal/edge/prober.go
index 3463a34fa..4dc10dd7e 100644
--- a/internal/edge/prober.go
+++ b/internal/edge/prober.go
@@ -128,13 +128,19 @@ type proberSet struct {
// newProberSet builds the set with hold.probe as the probe timeout (T in
// the readmission formula, spec §3), and hold.dialer, when set, as the
-// probes' dialer, so a test's instrumented dialer sees the probes too. A
-// non-positive probe falls back to probeTimeout: an unbounded probe would
-// stall every tick behind one black-holed upstream.
+// probes' dialer, so a test's instrumented dialer sees the probes too;
+// unset (production), the probes dial with upstreamDialer, which refuses
+// link-local and IMDS addresses. A non-positive probe falls back to
+// probeTimeout: an unbounded probe would stall every tick behind one
+// black-holed upstream.
func newProberSet(hold localHold) *proberSet {
if hold.probe <= 0 {
hold.probe = probeTimeout
}
+ dial := hold.dialer
+ if dial == nil {
+ dial = upstreamDialer().DialContext
+ }
return &proberSet{
hosts: make(map[string]*hostProber),
hold: hold,
@@ -153,7 +159,7 @@ func newProberSet(hold localHold) *proberSet {
MaxIdleConnsPerHost: 1,
IdleConnTimeout: 90 * time.Second,
ResponseHeaderTimeout: hold.probe,
- DialContext: hold.dialer, // nil: the default dialer
+ DialContext: dial,
},
},
}
diff --git a/internal/edge/upstreamdial.go b/internal/edge/upstreamdial.go
new file mode 100644
index 000000000..dd435928e
--- /dev/null
+++ b/internal/edge/upstreamdial.go
@@ -0,0 +1,54 @@
+package edge
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "net/netip"
+ "syscall"
+)
+
+// errLinkLocalUpstream is the dial error for an upstream whose address is
+// link-local or the AWS instance metadata service. A route's addr is
+// operator- or tenant-supplied, and a name can resolve anywhere, so without
+// this an upstream of 169.254.169.254 (or a name pointing at it) would have
+// the edge fetch the box's own instance credentials for whoever asked.
+var errLinkLocalUpstream = errors.New("edge: refusing a link-local upstream address")
+
+// linkLocalUpstreams are the destinations no upstream may have:
+// 169.254.0.0/16 and fe80::/10 (link-local, IMDS's IPv4 address among them)
+// and fd00:ec2::254, IMDS's IPv6 address, which is not link-local.
+var linkLocalUpstreams = []netip.Prefix{
+ netip.MustParsePrefix("169.254.0.0/16"),
+ netip.MustParsePrefix("fe80::/10"),
+ netip.MustParsePrefix("fd00:ec2::254/128"),
+}
+
+// refuseLinkLocalUpstream is a net.Dialer Control hook. The dialer calls it
+// with the address it has already resolved, after creating the socket and
+// before connecting it, so a refusal here means nothing was connected, and a
+// name is judged by what it resolved to rather than by how it is spelled.
+// IPv4-mapped IPv6 is unmapped first, so ::ffff:169.254.169.254 is refused
+// too. An address that does not parse as ip:port (not something a TCP dial
+// passes) is let through.
+func refuseLinkLocalUpstream(network, address string, _ syscall.RawConn) error {
+ ap, err := netip.ParseAddrPort(address)
+ if err != nil {
+ return nil
+ }
+ ip := ap.Addr().WithZone("").Unmap()
+ for _, p := range linkLocalUpstreams {
+ if p.Contains(ip) {
+ return fmt.Errorf("%w: %s %s", errLinkLocalUpstream, network, address)
+ }
+ }
+ return nil
+}
+
+// upstreamDialer is the dialer for a TCP upstream when no test dialer is set
+// (hold.dialer nil, as in production): the plain net.Dialer the transports
+// used before, plus the link-local refusal. tcpProxy, multiProxy and the
+// prober use it; unix sockets, backhaul hops and tunnels do not.
+func upstreamDialer() *net.Dialer {
+ return &net.Dialer{Control: refuseLinkLocalUpstream}
+}
diff --git a/internal/edge/upstreamdial_test.go b/internal/edge/upstreamdial_test.go
new file mode 100644
index 000000000..accf06d5c
--- /dev/null
+++ b/internal/edge/upstreamdial_test.go
@@ -0,0 +1,166 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestRefuseLinkLocalUpstream is the Control hook's table: link-local
+// (IPv4 and IPv6, mapped or not) and the AWS IMDS IPv6 address are refused;
+// loopback and private addresses, which real upstreams use, are not.
+func TestRefuseLinkLocalUpstream(t *testing.T) {
+ for _, tc := range []struct {
+ address string
+ refused bool
+ }{
+ {"169.254.169.254:80", true},
+ {"[::ffff:169.254.169.254]:80", true},
+ {"169.254.0.1:8080", true},
+ {"[fe80::1]:80", true},
+ {"[fe80::1%eth0]:80", true},
+ {"[fd00:ec2::254]:80", true},
+ {"127.0.0.1:80", false},
+ {"10.0.0.5:80", false},
+ {"[::1]:80", false},
+ {"[fd00:ec2::253]:80", false},
+ } {
+ err := refuseLinkLocalUpstream("tcp", tc.address, nil)
+ if got := errors.Is(err, errLinkLocalUpstream); got != tc.refused {
+ t.Errorf("refuseLinkLocalUpstream(%q) = %v, want refused=%v", tc.address, err, tc.refused)
+ }
+ }
+}
+
+// proxyErr serves one request through p and returns the status and the
+// error p's ErrorHandler was handed (nil if it was not called), keeping the
+// production ErrorHandler's answer.
+func proxyErr(t *testing.T, p *httputil.ReverseProxy) (int, error) {
+ t.Helper()
+ var got error
+ orig := p.ErrorHandler
+ p.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
+ got = err
+ orig(w, r, err)
+ }
+ rec := httptest.NewRecorder()
+ p.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil))
+ return rec.Code, got
+}
+
+// TestTCPProxyRefusesNameResolvingToIMDS: an upstream NAME is checked after
+// resolution, at the address the dialer is about to connect to. imds.test
+// resolves (through a fake DNS zone, cnameResolver) to 169.254.169.254; the
+// Control hook runs before connect, so nothing is connected and the request
+// answers 502 with the refusal as its cause.
+func TestTCPProxyRefusesNameResolvingToIMDS(t *testing.T) {
+ d := upstreamDialer()
+ d.Resolver = cnameResolver(t, []string{"imds.test"}, []string{"169.254.169.254"})
+ p := tcpProxy("imds.test:80", localHold{dialer: d.DialContext})
+ code, err := proxyErr(t, p)
+ if code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", code)
+ }
+ if !errors.Is(err, errLinkLocalUpstream) {
+ t.Fatalf("proxy error = %v, want one wrapping errLinkLocalUpstream", err)
+ }
+}
+
+// TestUpstreamDialSitesRefuseLinkLocal checks the production wiring: with
+// hold.dialer nil, as New leaves it, each of the three upstream dial sites
+// (tcpProxy, multiProxy, the prober's transport) dials through the guarded
+// dialer rather than the stdlib's default. Each nil check comes before any
+// dial, so a missing guard fails the test without connecting anywhere.
+func TestUpstreamDialSitesRefuseLinkLocal(t *testing.T) {
+ hold := defaultLocalHold()
+ if hold.dialer != nil {
+ t.Fatal("defaultLocalHold has a dialer; this test is about the nil (production) path")
+ }
+
+ t.Run("tcpProxy", func(t *testing.T) {
+ p := tcpProxy("169.254.169.254:80", hold)
+ tr, ok := p.Transport.(*http.Transport)
+ if !ok || tr.DialContext == nil {
+ t.Fatal("tcpProxy transport has no DialContext: it would dial with the stdlib's unguarded default")
+ }
+ code, err := proxyErr(t, p)
+ if code != http.StatusBadGateway || !errors.Is(err, errLinkLocalUpstream) {
+ t.Fatalf("status = %d, err = %v; want 502 wrapping errLinkLocalUpstream", code, err)
+ }
+ })
+
+ t.Run("prober", func(t *testing.T) {
+ ps := newProberSet(hold)
+ tr, ok := ps.client.Transport.(*http.Transport)
+ if !ok || tr.DialContext == nil {
+ t.Fatal("prober transport has no DialContext: it would dial with the stdlib's unguarded default")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ conn, err := tr.DialContext(ctx, "tcp", "169.254.169.254:80")
+ if conn != nil {
+ conn.Close()
+ }
+ if !errors.Is(err, errLinkLocalUpstream) {
+ t.Fatalf("probe dial err = %v, want errLinkLocalUpstream", err)
+ }
+ })
+
+ // multiProxy's fallback dialer is a closure variable the test cannot
+ // inspect, so its upstream is fe80::1 with no zone: unguarded, the kernel
+ // refuses that connect locally (no interface to send on); guarded, the
+ // Control hook refuses it first. Either way nothing leaves the box.
+ t.Run("multiProxy", func(t *testing.T) {
+ const host = "ha.example.com"
+ ps := newProberSet(hold)
+ defer ps.Stop()
+ ps.Sync(map[string]probeSpec{host: {Host: host, Addrs: []string{"[fe80::1]:80"}, Health: frozenHealth()}})
+ tr, ok := multiProxy(host, ps, hold).Transport.(*http.Transport)
+ if !ok {
+ t.Fatal("multiProxy transport is not an *http.Transport")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ conn, err := tr.DialContext(ctx, "tcp", multiDialHost)
+ if conn != nil {
+ conn.Close()
+ }
+ if !errors.Is(err, errNoLiveUpstream) || !strings.Contains(err.Error(), errLinkLocalUpstream.Error()) {
+ t.Fatalf("multi dial err = %v, want errNoLiveUpstream naming errLinkLocalUpstream", err)
+ }
+ })
+
+ // The guard must not cost a real upstream anything: loopback, through
+ // tcpProxy's local-hold path and through the prober.
+ t.Run("loopback allowed", func(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer backend.Close()
+ addr := backend.Listener.Addr().String()
+
+ p := tcpProxy(addr, hold)
+ code, err := proxyErr(t, p)
+ if code != http.StatusOK || err != nil {
+ t.Fatalf("tcpProxy to %s: status = %d, err = %v; want 200", addr, code, err)
+ }
+
+ ps := newProberSet(hold)
+ tr := ps.client.Transport.(*http.Transport)
+ if tr.DialContext == nil {
+ t.Fatal("prober transport has no DialContext")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ conn, err := tr.DialContext(ctx, "tcp", addr)
+ if err != nil {
+ t.Fatalf("probe dial %s: %v", addr, err)
+ }
+ conn.Close()
+ })
+}