package outbound
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"sync/atomic"
"testing"
"time"
)
// answers is a resolver with a fixed table; a name missing from it does
// not resolve.
func answers(table map[string][]string) func(context.Context, string) ([]net.IPAddr, error) {
return func(_ context.Context, host string) ([]net.IPAddr, error) {
var out []net.IPAddr
for _, s := range table[host] {
out = append(out, net.IPAddr{IP: net.ParseIP(s)})
}
if len(out) == 0 {
return nil, errors.New("no such host")
}
return out, nil
}
}
func done(t *testing.T) {
t.Helper()
if !t.Failed() {
t.Log("ok")
}
}
// An address an operator configured keeps today's rule: https anywhere,
// http to this machine (#225).
func TestOperatorCheckAllowsLoopbackHTTP(t *testing.T) {
for _, tc := range []struct {
raw string
ok bool
}{
{"https://hooks.example/x", true},
{"http://127.0.0.1:8950/r/quarry", true},
{"http://localhost:9000", true},
{"http://[::1]:9000", true},
{"http://hooks.example/x", false},
{"http://127.evil.example/x", false},
{"http://10.0.0.5/x", false},
{"ftp://files.example/x", false},
{"https:///nohost", false},
{"not a url", false},
} {
if _, err := CheckOperator(tc.raw); (err == nil) != tc.ok {
t.Errorf("FAIL: %q accepted=%v, want %v", tc.raw, err == nil, tc.ok)
}
}
done(t)
}
// Every refused class is refused by address, in both families and in
// the mapped, compatible and embedded spellings.
func TestReservedClasses(t *testing.T) {
for _, tc := range []struct {
ip string
bad bool
}{
{"127.0.0.1", true}, {"127.255.255.254", true}, {"::1", true}, {"::", true},
{"10.1.2.3", true}, {"172.16.0.1", true}, {"172.31.255.255", true}, {"192.168.1.1", true},
{"fc00::1", true}, {"fd12:3456::1", true},
{"169.254.169.254", true}, {"169.254.0.1", true}, {"fe80::1", true},
{"100.64.0.1", true}, {"100.127.255.255", true},
{"0.0.0.0", true}, {"0.1.2.3", true},
{"224.0.0.1", true}, {"239.255.255.255", true}, {"ff02::1", true},
{"255.255.255.255", true}, {"240.0.0.1", true},
{"::ffff:127.0.0.1", true}, {"::ffff:10.0.0.1", true}, {"::ffff:169.254.169.254", true},
{"::127.0.0.1", true}, {"::10.0.0.1", true},
{"64:ff9b::7f00:1", true}, {"2002:7f00:1::1", true},
{"fe80::1%lo0", true}, {"fe80::1%25eth0", true}, {"::1%lo0", true}, {"10.0.0.1%x", true},
{"::ffff:0:a00:1", true}, {"2001:0:4136:e378:8000:63bf:3fff:fdd2", true}, {"100::1", true},
{"2001:10::1", true}, {"2001:20::1", true}, {"2001:db8::1", true}, {"2001:db8:ffff::1", true},
{"192.0.2.1", true}, {"198.51.100.200", true}, {"203.0.113.7", true},
{"172.15.255.255", false}, {"172.32.0.1", false}, {"100.63.255.255", false}, {"100.128.0.1", false},
{"8.8.4.4", false}, {"8.8.8.8", false}, {"::ffff:8.8.8.8", false},
{"2606:4700::1111", false}, {"64:ff9b::808:808", false},
} {
a, err := netip.ParseAddr(tc.ip)
if err != nil && strings.Contains(tc.ip, "%") {
// A zone's spelling varies; judge the address a zone qualifies.
a, err = netip.ParseAddr(tc.ip[:strings.Index(tc.ip, "%")])
a = a.WithZone("lo0")
}
if err != nil {
t.Fatalf("bad fixture %q", tc.ip)
}
if got := Reserved(a); got != tc.bad {
t.Errorf("FAIL: %s reserved=%v, want %v", tc.ip, got, tc.bad)
}
}
done(t)
}
func TestUserCheck(t *testing.T) {
p := &Policy{Resolve: answers(map[string][]string{
"public.test": {"8.8.4.4"},
"inward.test": {"10.0.0.9"},
"loop.test": {"127.0.0.1"},
"meta.test": {"169.254.169.254"},
"mixed.test": {"8.8.4.4", "10.0.0.9"},
"mixed6.test": {"8.8.4.4", "fd00::1"},
"v6public.test": {"2606:4700::1111"},
})}
for _, tc := range []struct {
raw string
ok bool
}{
{"https://public.test/hook", true},
{"https://8.8.4.4/hook", true},
{"https://[2606:4700::1111]/hook", true},
{"https://v6public.test/hook", true},
{"http://public.test/hook", false},
{"http://8.8.4.4/hook", false},
{"https://inward.test/", false},
{"https://loop.test/", false},
{"https://meta.test/", false},
{"https://mixed.test/", false},
{"https://mixed6.test/", false},
{"http://localhost/", false},
{"http://127.0.0.1:8950/", false},
{"https://127.0.0.1/", false},
{"https://[::1]/", false},
{"https://[::ffff:127.0.0.1]/", false},
{"https://169.254.169.254/latest/meta-data", false},
{"https://100.64.0.1/", false},
{"https://0.0.0.0/", false},
{"https://224.0.0.1/", false},
{"https://255.255.255.255/", false},
{"https://[fe80::1]/", false},
{"https://[fe80::1%25eth0]/", false},
{"https://[fd00::1]/", false},
// Spellings a system resolver or a child process may read as 127.0.0.1.
{"http://2130706433/", false},
{"http://0x7f.1/", false},
{"http://127.1/", false},
{"http://0177.0.0.1/", false},
{"http://0x7f000001/", false},
{"https://2130706433/", false},
{"https://134744072/", false}, // 8.8.8.8, still an unusual spelling
// Not a destination at all.
{"https://user:[email protected]/", false},
{"https://[email protected]/", false},
{"ftp://public.test/", false},
{"ssh://public.test/", false},
{"https:///nohost", false},
{"nothing.test", false},
{"https://unknown.test/", false},
} {
_, err := p.CheckUser(tc.raw)
if (err == nil) != tc.ok {
t.Errorf("FAIL: %q accepted=%v, want %v", tc.raw, err == nil, tc.ok)
}
}
done(t)
}
// An error names the scheme and host at most, never the whole URL, which
// may hold a token in its query.
func TestUserCheckErrorsDoNotEchoTheURL(t *testing.T) {
p := &Policy{Resolve: answers(map[string][]string{"inward.test": {"10.0.0.9"}})}
for _, raw := range []string{
"https://inward.test/path?token=SECRETVALUE",
"https://user:[email protected]/",
"https://8.8.4.4:99999/x?token=SECRETVALUE",
"ftp://inward.test/x?token=SECRETVALUE",
} {
_, err := p.CheckUser(raw)
if err == nil {
t.Errorf("FAIL: %q accepted", raw)
continue
}
if containsAny(err.Error(), "SECRETVALUE", "/path") {
t.Errorf("FAIL: the error for %q carries part of the url", raw)
}
}
done(t)
}
func containsAny(s string, subs ...string) bool {
for _, x := range subs {
if strings.Contains(s, x) {
return true
}
}
return false
}
func TestErrTextNamesSchemeAndHostOnly(t *testing.T) {
c := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return nil, errors.New("boom")
})}
_, err := c.Get("https://hooks.test/path?token=SECRETVALUE")
if err == nil {
t.Fatal("FAIL: no error")
}
if got := ErrText(err); containsAny(got, "SECRETVALUE", "/path") || !containsAny(got, "https://hooks.test") {
t.Errorf("FAIL: ErrText did not reduce the url to scheme and host")
}
done(t)
}
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
// The operator's list admits exactly what it names, and nothing else in
// the refused classes.
func TestAllowanceAdmitsExactlyWhatItNames(t *testing.T) {
p := &Policy{Resolve: answers(map[string][]string{
"sibling.test": {"10.1.2.3"},
"other.test": {"10.9.9.9"},
})}
list, err := ParseAllowance(context.Background(), "10.1.2.3, 192.168.0.0/16, sibling.test, fd00::/8", p.Resolve)
if err != nil {
t.Fatalf("FAIL: parse: %v", err)
}
p.Allow(list)
for _, tc := range []struct {
raw string
ok bool
}{
{"https://10.1.2.3/", true},
{"https://sibling.test/", true},
{"https://192.168.5.5/", true},
{"https://[fd00::7]/", true},
{"https://10.1.2.4/", false},
{"https://other.test/", false},
{"https://172.17.0.1/", false},
{"https://127.0.0.1/", false},
{"https://169.254.169.254/", false},
{"https://[fe80::1]/", false},
// http stays loopback-only even to an allowed private host.
{"http://10.1.2.3/", false},
} {
if _, err := p.CheckUser(tc.raw); (err == nil) != tc.ok {
t.Errorf("FAIL: %q accepted=%v, want %v", tc.raw, err == nil, tc.ok)
}
}
// A name that does not resolve cannot be listed.
if _, err := ParseAllowance(context.Background(), "gone.test", p.Resolve); err == nil {
t.Errorf("FAIL: an unresolvable allowed host was accepted")
}
// Loopback allowed, http to it follows.
p.Allow(mustPrefixes("127.0.0.0/8"))
if _, err := p.CheckUser("http://127.0.0.1:9000/"); err != nil {
t.Errorf("FAIL: http to an allowed loopback address refused")
}
p.Allow(nil)
if _, err := p.CheckUser("http://127.0.0.1:9000/"); err == nil {
t.Errorf("FAIL: an emptied allowance still admitted loopback")
}
done(t)
}
// Bridges widens only itself: the blanket switch is not a way to let
// webhooks reach the inside.
func TestBridgesBlanketDoesNotWidenDefault(t *testing.T) {
d := &Policy{}
b := &Policy{base: d}
b.AllowAllPrivate(true)
if _, err := b.CheckUser("https://10.0.0.1/"); err != nil {
t.Errorf("FAIL: bridges refused a private address with the switch on")
}
if _, err := d.CheckUser("https://10.0.0.1/"); err == nil {
t.Errorf("FAIL: the default policy followed the bridges switch")
}
d.Allow(mustPrefixes("10.0.0.0/8"))
b.AllowAllPrivate(false)
if _, err := b.CheckUser("https://10.0.0.1/"); err != nil {
t.Errorf("FAIL: bridges ignored the default's allowance")
}
done(t)
}
// Validation passed, then the name answers inward: the dial refuses it,
// and the server behind it is never reached.
func TestDialRefusesWhatValidationPassed(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hits.Add(1) }))
defer srv.Close()
_, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
var calls atomic.Int32
p := &Policy{Resolve: func(context.Context, string) ([]net.IPAddr, error) {
if calls.Add(1) == 1 {
return []net.IPAddr{{IP: net.ParseIP("8.8.4.4")}}, nil
}
return []net.IPAddr{{IP: net.ParseIP("127.0.0.1")}}, nil
}}
target := "https://rebind.test:" + port + "/"
if _, err := p.CheckUser(target); err != nil {
t.Fatalf("FAIL: validation should pass on the first answer: %v", err)
}
c := p.NewClient(5 * time.Second)
_, err := c.Get(target)
var ref *Refusal
if !errors.As(err, &ref) {
t.Errorf("FAIL: the dial was not refused by the guard: %v", err)
}
if hits.Load() != 0 {
t.Errorf("FAIL: the server behind the rebound name was reached")
}
done(t)
}
// The Control hook is the backstop on the address actually dialled.
func TestControlHookJudgesTheDialledAddress(t *testing.T) {
p := &Policy{}
for addr, bad := range map[string]bool{
"127.0.0.1:80": true, "[::1]:80": true, "10.0.0.1:443": true, "169.254.169.254:80": true,
"[::ffff:10.0.0.1]:80": true, "8.8.4.4:443": false, "[2606:4700::1111]:443": false,
"not-an-address": true,
} {
if err := p.control("tcp", addr, nil); (err != nil) != bad {
t.Errorf("FAIL: control(%s) refused=%v, want %v", addr, err != nil, bad)
}
}
p.Allow(mustPrefixes("10.0.0.1/32"))
if err := p.control("tcp", "10.0.0.1:443", nil); err != nil {
t.Errorf("FAIL: control refused an allowed address")
}
if err := p.control("tcp", "10.0.0.2:443", nil); err == nil {
t.Errorf("FAIL: control admitted an address that was not named")
}
done(t)
}
// A redirect is not followed by default (the 3xx comes back as the
// answer), and a client that did follow would still be stopped by the
// dial guard, which judges every hop.
func TestRedirectToLoopbackIsRefused(t *testing.T) {
var inner atomic.Int32
innerSrv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { inner.Add(1) }))
defer innerSrv.Close()
outerSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, innerSrv.URL, http.StatusFound)
}))
defer outerSrv.Close()
_, outerPort, _ := net.SplitHostPort(outerSrv.Listener.Addr().String())
// "public.test" stands for a public host; the test servers are on
// loopback, which is let through for the outer name only by pointing
// the name at a public-looking address the dial map reaches.
p := &Policy{Resolve: answers(map[string][]string{"public.test": {"127.0.0.1"}})}
p.Allow(mustPrefixes("127.0.0.1/32"))
c := p.NewClient(5 * time.Second)
resp, err := c.Get("http://public.test:" + outerPort + "/")
if err != nil {
t.Fatalf("FAIL: the first hop: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusFound || inner.Load() != 0 {
t.Errorf("FAIL: status=%d inner hits=%d, want a 302 and no second request", resp.StatusCode, inner.Load())
}
// Following redirects, with only the outer name allowed: the second
// hop's address is not, and is refused at the dial.
q := &Policy{Resolve: answers(map[string][]string{"public.test": {"127.0.0.1"}})}
q.Allow(mustPrefixes("127.0.0.1/32"))
follow := q.NewClient(5 * time.Second)
follow.CheckRedirect = nil
q.Allow(nil)
q.Resolve = answers(map[string][]string{"public.test": {"127.0.0.1"}})
if _, err := follow.Get("http://public.test:" + outerPort + "/"); err == nil {
t.Errorf("FAIL: a following client reached a loopback server with no allowance")
}
if inner.Load() != 0 {
t.Errorf("FAIL: the redirect target was reached")
}
done(t)
}
// The operator's allowance is what lets a test server on loopback be
// called, and it is a list, not a switch.
func TestGuardedClientReachesAnAllowedLoopbackServer(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }))
defer srv.Close()
p := &Policy{}
if _, err := p.NewClient(5 * time.Second).Get(srv.URL); err == nil {
t.Errorf("FAIL: loopback reached with no allowance")
}
p.Allow(mustPrefixes("127.0.0.0/8"))
resp, err := p.NewClient(5 * time.Second).Get(srv.URL)
if err != nil {
t.Fatalf("FAIL: allowed loopback refused: %v", err)
}
resp.Body.Close()
if resp.StatusCode != 204 {
t.Errorf("FAIL: status %d", resp.StatusCode)
}
done(t)
}
// "Does not resolve" and "resolves to an address the forge will not
// call" are told apart by Kind, and the text never carries the address a
// name resolved to, which would let a caller map internal DNS.
func TestRefusalKindsAndNoResolvedAddressInText(t *testing.T) {
p := &Policy{Resolve: answers(map[string][]string{"inward.test": {"10.77.66.55"}})}
for raw, kind := range map[string]string{
"https://inward.test/": KindAddress,
"https://gone.test/": KindUnresolved,
"https://10.77.66.55/": KindAddress,
"http://2130706433/": KindForm,
"https://[fe80::1%25x]": KindForm,
} {
_, err := p.CheckUser(raw)
var ref *Refusal
if !errors.As(err, &ref) {
t.Errorf("FAIL: %q: not a refusal: %v", raw, err)
continue
}
if ref.Kind != kind || !strings.HasPrefix(err.Error(), kind) {
t.Errorf("FAIL: %q: kind %q, want %q", raw, ref.Kind, kind)
}
if strings.Contains(err.Error(), "10.77.66.55") && raw == "https://inward.test/" {
t.Errorf("FAIL: the text names the resolved address")
}
}
done(t)
}