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
81 changes: 81 additions & 0 deletions destination/address.go
Original file line number Diff line number Diff line change
@@ -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) })
}
84 changes: 84 additions & 0 deletions destination/address_test.go
Original file line number Diff line number Diff line change
@@ -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)))
})
}
}
80 changes: 80 additions & 0 deletions destination/config.go
Original file line number Diff line number Diff line change
@@ -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
}
55 changes: 55 additions & 0 deletions destination/config_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading
Loading