diff --git a/destination/address.go b/destination/address.go new file mode 100644 index 0000000..ccc6e34 --- /dev/null +++ b/destination/address.go @@ -0,0 +1,81 @@ +// Package destination decides which network destinations a client may connect +// to, for services that connect outbound to addresses an untrusted party can +// influence (webhook delivery, reverse proxies, SOCKS gateways). +// +// The decision is made at the socket, after name resolution and before the +// connection is made, so it covers redirects, DNS rebinding and a hostname +// that resolves to several addresses. A check at configuration time is a +// convenience only. +package destination + +import ( + "net/netip" + "slices" +) + +// nonPublicPrefixes are the special-purpose ranges, beyond those netip.Addr +// classifies itself, that are never reachable as public internet hosts. +var nonPublicPrefixes = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), // "this network" + netip.MustParsePrefix("100.64.0.0/10"), // carrier-grade NAT, also used by overlay networks + netip.MustParsePrefix("192.0.0.0/24"), // IETF protocol assignments + netip.MustParsePrefix("192.0.2.0/24"), // documentation + netip.MustParsePrefix("198.18.0.0/15"), // benchmarking + netip.MustParsePrefix("198.51.100.0/24"), // documentation + netip.MustParsePrefix("203.0.113.0/24"), // documentation + netip.MustParsePrefix("240.0.0.0/4"), // reserved, and broadcast + netip.MustParsePrefix("64:ff9b:1::/48"), // local-use IPv4/IPv6 translation + netip.MustParsePrefix("100::/64"), // discard-only + netip.MustParsePrefix("2001::/23"), // IETF protocol assignments, including Teredo + netip.MustParsePrefix("2001:db8::/32"), // documentation +} + +// cloudMetadataPrefixes are the addresses cloud providers serve instance +// metadata and credentials from. +var cloudMetadataPrefixes = []netip.Prefix{ + netip.MustParsePrefix("169.254.0.0/16"), // link-local, used by AWS, Azure, GCP and others + netip.MustParsePrefix("fd00:ec2::/32"), // AWS IPv6 metadata endpoint +} + +// nat64Prefix embeds an IPv4 address in its last 32 bits, so an address in it +// is only as public as the IPv4 address it carries. +var nat64Prefix = netip.MustParsePrefix("64:ff9b::/96") + +// canonical returns the address a destination is judged by: IPv4-mapped IPv6 +// and NAT64 addresses are replaced by the IPv4 address they carry, and a zone +// is dropped. +func canonical(addr netip.Addr) netip.Addr { + addr = addr.Unmap().WithZone("") + if nat64Prefix.Contains(addr) { + b := addr.As16() + + return netip.AddrFrom4([4]byte(b[12:])) + } + + return addr +} + +// IsPublicAddress reports whether addr is a public internet address: not +// loopback, private (including IPv6 unique local addresses, and so Fly.io's +// private network), link-local (including cloud metadata), multicast, +// unspecified or in a special-use range. IPv4-mapped and NAT64 addresses are +// judged by the IPv4 address they carry. +func IsPublicAddress(addr netip.Addr) bool { + addr = canonical(addr) + if !addr.IsValid() || !addr.IsGlobalUnicast() || addr.IsPrivate() { + return false + } + + return !containsAddr(nonPublicPrefixes, addr) +} + +// IsCloudMetadataAddress reports whether addr is where a cloud provider serves +// instance metadata. IPv4-mapped and NAT64 addresses are judged by the IPv4 +// address they carry. +func IsCloudMetadataAddress(addr netip.Addr) bool { + return containsAddr(cloudMetadataPrefixes, canonical(addr)) +} + +func containsAddr(prefixes []netip.Prefix, addr netip.Addr) bool { + return slices.ContainsFunc(prefixes, func(p netip.Prefix) bool { return p.Contains(addr) }) +} diff --git a/destination/address_test.go b/destination/address_test.go new file mode 100644 index 0000000..3eea5ab --- /dev/null +++ b/destination/address_test.go @@ -0,0 +1,84 @@ +package destination + +import ( + "net/netip" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_IsPublicAddress(t *testing.T) { + tests := []struct { + name string + addr string + want bool + }{ + {"public IPv4", "8.8.8.8", true}, + {"public IPv4 next to private", "172.32.0.1", true}, + {"public IPv6", "2606:4700:4700::1111", true}, + {"loopback IPv4", "127.0.0.1", false}, + {"loopback IPv6", "::1", false}, + {"RFC 1918 10/8", "10.1.2.3", false}, + {"RFC 1918 172.16/12", "172.16.0.1", false}, + {"RFC 1918 192.168/16", "192.168.1.1", false}, + {"CGNAT", "100.64.0.1", false}, + {"link-local IPv4", "169.254.1.1", false}, + {"cloud metadata", "169.254.169.254", false}, + {"IPv6 ULA", "fd12:3456:789a::1", false}, + {"IPv6 link-local", "fe80::1", false}, + {"IPv4 multicast", "224.0.0.1", false}, + {"IPv6 multicast", "ff02::1", false}, + {"IPv4 unspecified", "0.0.0.0", false}, + {"IPv6 unspecified", "::", false}, + {"this network", "0.1.2.3", false}, + {"IETF protocol assignments", "192.0.0.8", false}, + {"documentation TEST-NET-1", "192.0.2.1", false}, + {"benchmarking", "198.18.0.1", false}, + {"documentation TEST-NET-2", "198.51.100.1", false}, + {"documentation TEST-NET-3", "203.0.113.1", false}, + {"reserved", "240.0.0.1", false}, + {"broadcast", "255.255.255.255", false}, + {"local-use translation", "64:ff9b:1::1", false}, + {"discard-only", "100::1", false}, + {"Teredo", "2001:0:4136:e378:8000:63bf:3fff:fdd2", false}, + {"IPv6 documentation", "2001:db8::1", false}, + {"IPv4-mapped public", "::ffff:8.8.8.8", true}, + {"IPv4-mapped loopback", "::ffff:127.0.0.1", false}, + {"IPv4-mapped private", "::ffff:10.0.0.1", false}, + {"NAT64 public", "64:ff9b::808:808", true}, + {"NAT64 private", "64:ff9b::a00:1", false}, + {"NAT64 metadata", "64:ff9b::a9fe:a9fe", false}, + {"zoned link-local", "fe80::1%eth0", false}, + {"zero value", "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var addr netip.Addr + if tt.addr != "" { + addr = netip.MustParseAddr(tt.addr) + } + + assert.Equal(t, tt.want, IsPublicAddress(addr)) + }) + } +} + +func Test_IsCloudMetadataAddress(t *testing.T) { + tests := []struct { + addr string + want bool + }{ + {"169.254.169.254", true}, + {"169.254.0.1", true}, + {"::ffff:169.254.169.254", true}, + {"64:ff9b::a9fe:a9fe", true}, + {"fd00:ec2::254", true}, + {"10.0.0.1", false}, + {"8.8.8.8", false}, + } + for _, tt := range tests { + t.Run(tt.addr, func(t *testing.T) { + assert.Equal(t, tt.want, IsCloudMetadataAddress(netip.MustParseAddr(tt.addr))) + }) + } +} diff --git a/destination/config.go b/destination/config.go new file mode 100644 index 0000000..a669409 --- /dev/null +++ b/destination/config.go @@ -0,0 +1,80 @@ +package destination + +import ( + "net/netip" + + "github.com/dioad/config/configcheck" +) + +// Config is a Policy in the form services take it in their configuration. +type Config struct { + // AllowPrefixes are CIDR ranges allowed in addition to public addresses. + AllowPrefixes []string `desc:"CIDR ranges allowed in addition to public addresses" mapstructure:"allow"` + + // OnlyPrefixes are the only CIDR ranges allowed; public addresses are not + // allowed unless listed. + OnlyPrefixes []string `desc:"the only CIDR ranges allowed, replacing the public-address default" mapstructure:"only"` + + // AllowedPorts restricts destination ports when set. + AllowedPorts []int `desc:"destination ports allowed, any when empty" mapstructure:"allowed-ports"` + + // AllowCloudMetadata permits cloud metadata endpoints. + AllowCloudMetadata bool `desc:"allow cloud metadata endpoints" mapstructure:"allow-cloud-metadata"` +} + +// Check reports to c a range that is not a CIDR prefix, a port out of range, +// and allow ranges given together with only, which would be ignored. c is +// positioned at the config's own block. +func (cfg Config) Check(c *configcheck.Collector) { + checkPrefixes(c.Field("allow"), cfg.AllowPrefixes) + checkPrefixes(c.Field("only"), cfg.OnlyPrefixes) + if len(cfg.AllowPrefixes) > 0 && len(cfg.OnlyPrefixes) > 0 { + c.Field("allow").Errorf("has no effect with only set, remove one") + } + for i, port := range cfg.AllowedPorts { + if port < 1 || port > 65535 { + c.Field("allowed-ports").Index(i).Errorf("%d is not a port", port) + } + } +} + +func checkPrefixes(c *configcheck.Collector, prefixes []string) { + for i, p := range prefixes { + if _, err := netip.ParsePrefix(p); err != nil { + c.Index(i).Errorf("%q is not a CIDR range: %v", p, err) + } + } +} + +// Policy returns the Policy for cfg. It returns an error for a range that is +// not a CIDR prefix; Check reports the same. +func (cfg Config) Policy() (Policy, error) { + allow, err := parsePrefixes(cfg.AllowPrefixes) + if err != nil { + return Policy{}, err + } + only, err := parsePrefixes(cfg.OnlyPrefixes) + if err != nil { + return Policy{}, err + } + + return Policy{ + AllowPrefixes: allow, + OnlyPrefixes: only, + AllowedPorts: cfg.AllowedPorts, + AllowCloudMetadata: cfg.AllowCloudMetadata, + }, nil +} + +func parsePrefixes(values []string) ([]netip.Prefix, error) { + prefixes := make([]netip.Prefix, 0, len(values)) + for _, v := range values { + prefix, err := netip.ParsePrefix(v) + if err != nil { + return nil, err + } + prefixes = append(prefixes, prefix) + } + + return prefixes, nil +} diff --git a/destination/config_test.go b/destination/config_test.go new file mode 100644 index 0000000..a26fef7 --- /dev/null +++ b/destination/config_test.go @@ -0,0 +1,55 @@ +package destination + +import ( + "net/netip" + "testing" + + "github.com/dioad/config/configcheck" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_Config_Check(t *testing.T) { + tests := []struct { + name string + cfg Config + wantErr bool + }{ + {"empty", Config{}, false}, + {"valid", Config{AllowPrefixes: []string{"10.0.0.0/8", "fd00::/8"}, AllowedPorts: []int{80, 443}}, false}, + {"bad allow prefix", Config{AllowPrefixes: []string{"10.0.0.1"}}, true}, + {"bad only prefix", Config{OnlyPrefixes: []string{"nope"}}, true}, + {"allow with only", Config{AllowPrefixes: []string{"10.0.0.0/8"}, OnlyPrefixes: []string{"10.0.0.0/8"}}, true}, + {"port zero", Config{AllowedPorts: []int{0}}, true}, + {"port too high", Config{AllowedPorts: []int{65536}}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := configcheck.NewCollector() + tt.cfg.Check(c) + + if tt.wantErr { + require.Error(t, c.Err()) + } else { + require.NoError(t, c.Err()) + } + }) + } +} + +func Test_Config_Policy(t *testing.T) { + policy, err := Config{ + AllowPrefixes: []string{"10.0.0.0/8"}, + AllowedPorts: []int{443}, + AllowCloudMetadata: true, + }.Policy() + + require.NoError(t, err) + assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}, policy.AllowPrefixes) + assert.Empty(t, policy.OnlyPrefixes) + assert.Equal(t, []int{443}, policy.AllowedPorts) + assert.True(t, policy.AllowCloudMetadata) + + _, err = Config{OnlyPrefixes: []string{"nope"}}.Policy() + require.Error(t, err) +} diff --git a/destination/dial_test.go b/destination/dial_test.go new file mode 100644 index 0000000..4b03394 --- /dev/null +++ b/destination/dial_test.go @@ -0,0 +1,130 @@ +package destination + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func newServer(t *testing.T, handler http.Handler) *httptest.Server { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + + return srv +} + +// get returns the status code of the final response. +func get(t *testing.T, client *http.Client, target string) (int, error) { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, target, nil) + require.NoError(t, err) + + resp, err := client.Do(req) + if err != nil { + return 0, err + } + defer func() { _ = resp.Body.Close() }() + + return resp.StatusCode, nil +} + +func ok() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }) +} + +func Test_Policy_Client_LoopbackDestination(t *testing.T) { + srv := newServer(t, ok()) + + t.Run("refused by default", func(t *testing.T) { + _, err := get(t, Policy{}.Client(0), srv.URL) + + require.ErrorIs(t, err, ErrDenied) + }) + + t.Run("permitted when allow-listed", func(t *testing.T) { + policy := Policy{AllowPrefixes: prefixes("127.0.0.0/8")} + + status, err := get(t, policy.Client(0), srv.URL) + + require.NoError(t, err) + assert.Equal(t, http.StatusNoContent, status) + }) +} + +func Test_Policy_Client_RedirectToDeniedAddress(t *testing.T) { + denied := newServer(t, ok()) + deniedURL, err := url.Parse(denied.URL) + require.NoError(t, err) + // 127.0.0.2 is not in the allow-list below, so the redirect target is + // refused before the socket connects, whether or not anything listens. + target := "http://127.0.0.2:" + deniedURL.Port() + + redirector := newServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target, http.StatusFound) + })) + policy := Policy{AllowPrefixes: prefixes("127.0.0.1/32")} + + _, err = get(t, policy.Client(5), redirector.URL) + + require.ErrorIs(t, err, ErrDenied) +} + +func Test_Policy_Client_Redirects(t *testing.T) { + policy := Policy{AllowPrefixes: prefixes("127.0.0.0/8")} + srv := newServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/loop", http.StatusFound) + })) + + t.Run("zero follows none", func(t *testing.T) { + status, err := get(t, policy.Client(0), srv.URL+"/loop") + + require.NoError(t, err) + assert.Equal(t, http.StatusFound, status) + }) + + t.Run("limit stops a loop", func(t *testing.T) { + _, err := get(t, policy.Client(3), srv.URL+"/loop") + + require.ErrorContains(t, err, "stopped after 3 redirects") + }) +} + +func Test_Policy_Client_Scheme(t *testing.T) { + _, err := get(t, Policy{}.Client(0), "file:///etc/passwd") + + require.ErrorIs(t, err, ErrDenied) +} + +func Test_Policy_Dialer_ResolvedHostname(t *testing.T) { + srv := newServer(t, ok()) + srvURL, err := url.Parse(srv.URL) + require.NoError(t, err) + address := net.JoinHostPort("internal.test", srvURL.Port()) + resolver := fakeResolver(t, "127.0.0.1") + + t.Run("hostname resolving to a denied address is refused", func(t *testing.T) { + dialer := Policy{}.Dialer() + dialer.Resolver = resolver + + _, err := dialer.DialContext(context.Background(), "tcp4", address) + + require.ErrorIs(t, err, ErrDenied) + }) + + t.Run("hostname resolving to an allow-listed address connects", func(t *testing.T) { + dialer := Policy{AllowPrefixes: prefixes("127.0.0.0/8")}.Dialer() + dialer.Resolver = resolver + + conn, err := dialer.DialContext(context.Background(), "tcp4", address) + + require.NoError(t, err) + require.NoError(t, conn.Close()) + }) +} diff --git a/destination/fake_resolver_test.go b/destination/fake_resolver_test.go new file mode 100644 index 0000000..4749d83 --- /dev/null +++ b/destination/fake_resolver_test.go @@ -0,0 +1,67 @@ +package destination + +import ( + "context" + "net" + "testing" + + "github.com/stretchr/testify/require" +) + +// fakeResolver returns a resolver that answers every A query with ip, and +// every other query with no records, from a local UDP server. +func fakeResolver(t *testing.T, ip string) *net.Resolver { + t.Helper() + answer := net.ParseIP(ip).To4() + require.NotNil(t, answer) + + conn, err := (&net.ListenConfig{}).ListenPacket(t.Context(), "udp4", "127.0.0.1:0") + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + + go func() { + buf := make([]byte, 512) + for { + n, from, err := conn.ReadFrom(buf) + if err != nil { + return + } + _, _ = conn.WriteTo(dnsReply(buf[:n], answer), from) + } + }() + + return &net.Resolver{ + PreferGo: true, + Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, "udp4", conn.LocalAddr().String()) + }, + } +} + +// dnsReply builds a response to query with a single A record when the +// question is for type A. +func dnsReply(query []byte, ip net.IP) []byte { + if len(query) < 12 { + return nil + } + end := 12 + for end < len(query) && query[end] != 0 { + end += int(query[end]) + 1 + } + end += 5 // root label, QTYPE and QCLASS + if end > len(query) { + return nil + } + + reply := append([]byte{}, query[:end]...) + reply[2], reply[3] = 0x81, 0x80 // response, recursion available + reply[6], reply[7] = 0, 0 // answers, set below + reply[8], reply[9], reply[10], reply[11] = 0, 0, 0, 0 + if qtype := uint16(query[end-4])<<8 | uint16(query[end-3]); qtype == 1 { + reply[7] = 1 + reply = append(reply, 0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4) + reply = append(reply, ip...) + } + + return reply +} diff --git a/destination/http.go b/destination/http.go new file mode 100644 index 0000000..0d0f326 --- /dev/null +++ b/destination/http.go @@ -0,0 +1,56 @@ +package destination + +import ( + "errors" + "fmt" + "net/http" +) + +// Transport returns an http.RoundTripper that enforces the policy on every +// connection it makes, and refuses any scheme other than http and https. It +// does not use a proxy from the environment: a proxy would be the address +// dialled, and the destination behind it would escape the policy. +// +// A kept-alive connection is not re-checked per request. A live connection +// cannot rebind to another peer, so the check made when it was opened still +// holds; a new connection resolves and checks afresh. +func (p Policy) Transport() http.RoundTripper { + transport := http.DefaultTransport.(*http.Transport).Clone() //nolint:forcetypeassert // the default is documented to be a *http.Transport + transport.Proxy = nil + transport.DialContext = p.Dialer().DialContext + + return schemeCheck{next: transport} +} + +// Client returns an http.Client using Transport that follows at most +// maxRedirects redirects. With zero it follows none and returns the redirect +// response itself. A redirect to a denied address is refused at the dial. +func (p Policy) Client(maxRedirects int) *http.Client { + return &http.Client{ + Transport: p.Transport(), + CheckRedirect: func(_ *http.Request, via []*http.Request) error { + if len(via) > maxRedirects { + if maxRedirects == 0 { + return http.ErrUseLastResponse + } + + return fmt.Errorf("stopped after %d redirects", maxRedirects) + } + + return nil + }, + } +} + +type schemeCheck struct { + next http.RoundTripper +} + +func (s schemeCheck) RoundTrip(req *http.Request) (*http.Response, error) { + switch req.URL.Scheme { + case "http", "https": + return s.next.RoundTrip(req) + default: + return nil, errors.Join(ErrDenied, fmt.Errorf("scheme %q is not http or https", req.URL.Scheme)) + } +} diff --git a/destination/policy.go b/destination/policy.go new file mode 100644 index 0000000..2c6ffa7 --- /dev/null +++ b/destination/policy.go @@ -0,0 +1,94 @@ +package destination + +import ( + "errors" + "fmt" + "net" + "net/netip" + "slices" + "syscall" +) + +// ErrDenied is returned, wrapped, when a policy does not allow a destination. +// Callers can map it to a validation error or a refused request with +// errors.Is. +var ErrDenied = errors.New("destination not allowed") + +// Policy decides which destinations a client may connect to. The zero value +// allows only public addresses on any port. +// +// Cloud metadata endpoints are denied unless AllowCloudMetadata is set, +// whatever the prefixes say, so a broad allow-list cannot expose them by +// accident. +type Policy struct { + // AllowPrefixes are exceptions to the default deny of non-public + // addresses, for example the private network of a deployment. + AllowPrefixes []netip.Prefix + + // OnlyPrefixes, when set, allows only these ranges and replaces the + // public-address default. AllowPrefixes has no effect with it. + OnlyPrefixes []netip.Prefix + + // AllowedPorts, when set, restricts destination ports. + AllowedPorts []int + + // AllowCloudMetadata permits cloud metadata endpoints, which are denied + // otherwise. + AllowCloudMetadata bool +} + +// Check returns an error wrapping ErrDenied when the policy does not allow +// connecting to dest. IPv4-mapped and NAT64 addresses are judged by the IPv4 +// address they carry. +func (p Policy) Check(dest netip.AddrPort) error { + if len(p.AllowedPorts) > 0 && !slices.Contains(p.AllowedPorts, int(dest.Port())) { + return fmt.Errorf("%w: port %d is not an allowed port", ErrDenied, dest.Port()) + } + + addr := canonical(dest.Addr()) + if !addr.IsValid() { + return fmt.Errorf("%w: %q is not an address", ErrDenied, dest.Addr()) + } + + return p.checkAddr(addr) +} + +// checkAddr applies the address rules to a canonical, valid addr. +func (p Policy) checkAddr(addr netip.Addr) error { + metadata := IsCloudMetadataAddress(addr) + if metadata && !p.AllowCloudMetadata { + return fmt.Errorf("%w: %s is a cloud metadata endpoint", ErrDenied, addr) + } + + if len(p.OnlyPrefixes) > 0 { + if !containsAddr(p.OnlyPrefixes, addr) { + return fmt.Errorf("%w: %s is not in an allowed range", ErrDenied, addr) + } + + return nil + } + if metadata || containsAddr(p.AllowPrefixes, addr) || IsPublicAddress(addr) { + return nil + } + + return fmt.Errorf("%w: %s is not a public address", ErrDenied, addr) +} + +// Control is a net.Dialer.Control hook. It checks the numeric address a dial +// is about to connect to, after name resolution and before the socket +// connects, so no path to a denied address remains however the dial was +// reached. +func (p Policy) Control(_, address string, _ syscall.RawConn) error { + dest, err := netip.ParseAddrPort(address) + if err != nil { + return fmt.Errorf("%w: %w", ErrDenied, err) + } + + return p.Check(dest) +} + +// Dialer returns a net.Dialer that enforces the policy on every address it +// connects to. +func (p Policy) Dialer() *net.Dialer { + return &net.Dialer{Control: p.Control} +} diff --git a/destination/policy_test.go b/destination/policy_test.go new file mode 100644 index 0000000..dec5ab5 --- /dev/null +++ b/destination/policy_test.go @@ -0,0 +1,83 @@ +package destination + +import ( + "net/netip" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func prefixes(values ...string) []netip.Prefix { + out := make([]netip.Prefix, 0, len(values)) + for _, v := range values { + out = append(out, netip.MustParsePrefix(v)) + } + + return out +} + +func Test_Policy_Check(t *testing.T) { + tests := []struct { + name string + policy Policy + dest string + denied bool + }{ + {"zero value allows public", Policy{}, "8.8.8.8:443", false}, + {"zero value denies loopback", Policy{}, "127.0.0.1:80", true}, + {"zero value denies private", Policy{}, "10.0.0.1:80", true}, + {"zero value denies metadata", Policy{}, "169.254.169.254:80", true}, + {"zero value denies mapped loopback", Policy{}, "[::ffff:127.0.0.1]:80", true}, + {"allow prefix permits private", Policy{AllowPrefixes: prefixes("10.0.0.0/8")}, "10.1.1.1:80", false}, + {"allow prefix does not permit other private", Policy{AllowPrefixes: prefixes("10.0.0.0/8")}, "192.168.1.1:80", true}, + {"allow prefix permits mapped form", Policy{AllowPrefixes: prefixes("10.0.0.0/8")}, "[::ffff:10.1.1.1]:80", false}, + {"allow prefix permits NAT64 form", Policy{AllowPrefixes: prefixes("10.0.0.0/8")}, "[64:ff9b::a01:101]:80", false}, + {"allow prefix still permits public", Policy{AllowPrefixes: prefixes("10.0.0.0/8")}, "8.8.8.8:80", false}, + {"broad allow prefix does not expose metadata", Policy{AllowPrefixes: prefixes("169.254.0.0/16")}, "169.254.169.254:80", true}, + {"allow prefix with flag exposes metadata", Policy{AllowPrefixes: prefixes("169.254.0.0/16"), AllowCloudMetadata: true}, "169.254.169.254:80", false}, + {"flag alone exposes metadata", Policy{AllowCloudMetadata: true}, "169.254.169.254:80", false}, + {"flag does not expose other link-local", Policy{AllowCloudMetadata: true}, "[fe80::1]:80", true}, + {"only denies public", Policy{OnlyPrefixes: prefixes("10.0.0.0/8")}, "8.8.8.8:80", true}, + {"only permits listed", Policy{OnlyPrefixes: prefixes("10.0.0.0/8")}, "10.0.0.1:80", false}, + {"only ignores allow", Policy{OnlyPrefixes: prefixes("10.0.0.0/8"), AllowPrefixes: prefixes("192.168.0.0/16")}, "192.168.0.1:80", true}, + {"only denies metadata", Policy{OnlyPrefixes: prefixes("169.254.0.0/16")}, "169.254.169.254:80", true}, + {"only with flag permits metadata", Policy{OnlyPrefixes: prefixes("169.254.0.0/16"), AllowCloudMetadata: true}, "169.254.169.254:80", false}, + {"allowed port", Policy{AllowedPorts: []int{443}}, "8.8.8.8:443", false}, + {"other port", Policy{AllowedPorts: []int{443}}, "8.8.8.8:80", true}, + {"port checked with only", Policy{OnlyPrefixes: prefixes("10.0.0.0/8"), AllowedPorts: []int{443}}, "10.0.0.1:80", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.policy.Check(netip.MustParseAddrPort(tt.dest)) + + if tt.denied { + require.ErrorIs(t, err, ErrDenied) + } else { + require.NoError(t, err) + } + }) + } +} + +func Test_Policy_Check_ZeroAddr(t *testing.T) { + require.ErrorIs(t, Policy{}.Check(netip.AddrPort{}), ErrDenied) +} + +func Test_Policy_Control(t *testing.T) { + t.Run("denied address", func(t *testing.T) { + require.ErrorIs(t, Policy{}.Control("tcp4", "127.0.0.1:80", nil), ErrDenied) + }) + t.Run("allowed address", func(t *testing.T) { + require.NoError(t, Policy{}.Control("tcp4", "8.8.8.8:80", nil)) + }) + t.Run("zoned address", func(t *testing.T) { + require.ErrorIs(t, Policy{}.Control("tcp6", "[fe80::1%en0]:80", nil), ErrDenied) + }) + t.Run("not a numeric address", func(t *testing.T) { + err := Policy{}.Control("tcp", "example.com:80", nil) + + require.ErrorIs(t, err, ErrDenied) + assert.Error(t, err) + }) +}