| author | Alberto Bertogli
<albertito@blitiri.com.ar> 2026-11-28 21:38:58 UTC |
| committer | Alberto Bertogli
<albertito@blitiri.com.ar> 2026-11-28 21:42:13 UTC |
| parent | dd363cbf3fad0ebe5a66d822853c5c905c763e62 |
| kxd/key_config.go | +51 | -18 |
| kxd/key_config_test.go | +152 | -0 |
| kxd/kxd.go | +1 | -1 |
diff --git a/kxd/key_config.go b/kxd/key_config.go index f87e666..ca344ad 100644 --- a/kxd/key_config.go +++ b/kxd/key_config.go @@ -1,14 +1,16 @@ package main import ( + "context" "crypto/x509" "errors" "fmt" "io/fs" "net" + "net/netip" "os" - "slices" "strings" + "time" ) func isDir(path string) (bool, error) { @@ -98,7 +100,8 @@ func (kc *KeyConfig) LoadClientCerts() error { return nil } -// LoadAllowedHosts loads the hosts allowed for this key. +// LoadAllowedHosts loads the hosts allowed for this key. Hostnames are not +// resolved here, but on demand by IsHostAllowed. func (kc *KeyConfig) LoadAllowedHosts() error { contents, err := os.ReadFile(kc.allowedHostsPath) if errors.Is(err, fs.ErrNotExist) { @@ -116,16 +119,7 @@ func (kc *KeyConfig) LoadAllowedHosts() error { if line == "" { continue } - - if net.ParseIP(line) != nil { - kc.allowedHosts = append(kc.allowedHosts, line) - } else { - names, err := net.LookupHost(line) - if err != nil { - continue - } - kc.allowedHosts = append(kc.allowedHosts, names...) - } + kc.allowedHosts = append(kc.allowedHosts, line) } return nil @@ -157,22 +151,61 @@ func (kc *KeyConfig) VerifyClientCert( return certs[0].Verify(opts) } -// IsHostAllowed checks if the given host is allowed to access this key. -func (kc *KeyConfig) IsHostAllowed(addr string) error { +// Maximum time for each DNS lookup of the hostnames in allowed_hosts. +const hostLookupTimeout = 5 * time.Second + +// Function used to resolve hostnames in allowed_hosts. It is a variable so +// tests can override it. +var lookupHost = net.DefaultResolver.LookupHost + +// IsHostAllowed checks if the request's remote host is allowed to access this +// key. +// +// IP addresses in allowed_hosts are checked first, so if one matches, no DNS +// lookups are needed. Then, hostnames are resolved in order, until one of +// them matches. Lookup failures are logged, and the entry is skipped. +// +// Addresses are compared parsed, not as strings, so different ways of +// writing the same address match (e.g. "2001:DB8:0::1" and "2001:db8::1"). +// IPv4-mapped IPv6 addresses match their IPv4 equivalents. +func (kc *KeyConfig) IsHostAllowed(req *Request) error { if kc.allowedHosts == nil { return nil } - host, _, err := net.SplitHostPort(addr) + remote, err := netip.ParseAddrPort(req.RemoteAddr) if err != nil { return err } + host := remote.Addr().Unmap() - if slices.Contains(kc.allowedHosts, host) { - return nil + var hostnames []string + for _, entry := range kc.allowedHosts { + addr, err := netip.ParseAddr(entry) + if err != nil { + hostnames = append(hostnames, entry) + } else if addr.Unmap() == host { + return nil + } + } + + for _, hostname := range hostnames { + ctx, cancel := context.WithTimeout(req.Context(), hostLookupTimeout) + addrs, err := lookupHost(ctx, hostname) + cancel() + if err != nil { + req.Printf("Error resolving allowed host %q: %v", hostname, err) + continue + } + for _, a := range addrs { + addr, err := netip.ParseAddr(a) + if err == nil && addr.Unmap() == host { + return nil + } + } } - return fmt.Errorf("host %q not allowed", host) + return fmt.Errorf("host %q not allowed", host.String()) } // Key returns the private key. diff --git a/kxd/key_config_test.go b/kxd/key_config_test.go index 63ea0ea..f5416c5 100644 --- a/kxd/key_config_test.go +++ b/kxd/key_config_test.go @@ -1,13 +1,21 @@ package main import ( + "bytes" + "context" "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "crypto/x509/pkix" + "log" "math/big" + "net" + "net/http/httptest" + "os" + "slices" + "strings" "testing" "time" ) @@ -129,3 +137,147 @@ func TestVerifyClientCert(t *testing.T) { }) } } + +func TestIsHostAllowed(t *testing.T) { + // Fake resolver, so we don't depend on the network. + // "slow.example" simulates a lookup that times out. + dns := map[string][]string{ + "one.example": {"192.0.2.1"}, + "nine.example": {"192.0.2.9", "2001:db8::9"}, + "mapped.example": {"::ffff:192.0.2.1"}, + } + var lookups []string + origLookupHost := lookupHost + t.Cleanup(func() { lookupHost = origLookupHost }) + lookupHost = func(ctx context.Context, name string) ([]string, error) { + lookups = append(lookups, name) + deadline, ok := ctx.Deadline() + if !ok || time.Until(deadline) > hostLookupTimeout { + t.Errorf("lookup of %q without the expected deadline", name) + } + if name == "slow.example" { + return nil, context.DeadlineExceeded + } + if addrs, ok := dns[name]; ok { + return addrs, nil + } + return nil, &net.DNSError{ + Err: "no such host", Name: name, IsNotFound: true} + } + + // Capture the logs, to check lookup errors are logged. + var logBuf bytes.Buffer + origLogging := logging + t.Cleanup(func() { logging = origLogging }) + logging = log.New(&logBuf, "", 0) + + const absent = "<absent>" + cases := []struct { + name string + hosts string + remote string + allowed bool + lookups []string + logs []string + }{ + {"no allowed_hosts", absent, "192.0.2.1", true, nil, nil}, + {"empty allowed_hosts", "", "192.0.2.1", false, nil, nil}, + {"blank lines only", "\n \n", "192.0.2.1", false, nil, nil}, + + {"IP match", "192.0.2.1", "192.0.2.1", true, nil, nil}, + {"IP mismatch", "192.0.2.9", "192.0.2.1", false, nil, nil}, + {"IP with whitespace", " 192.0.2.1 \n", "192.0.2.1", true, + nil, nil}, + {"IPv6 match", "2001:db8::1", "2001:db8::1", true, nil, nil}, + + // Different ways of writing the same address match. + {"IPv6 with zeros", "2001:0db8:0000::0001", "2001:db8::1", true, + nil, nil}, + {"IPv6 uppercase", "2001:DB8::1", "2001:db8::1", true, nil, nil}, + {"IPv4-mapped entry", "::ffff:192.0.2.1", "192.0.2.1", true, + nil, nil}, + {"IPv4-mapped remote", "192.0.2.1", "::ffff:192.0.2.1", true, + nil, nil}, + {"IPv4-mapped lookup", "mapped.example", "192.0.2.1", true, + []string{"mapped.example"}, nil}, + + // Zones must match too. + {"zone match", "fe80::1%eth0", "fe80::1%eth0", true, nil, nil}, + {"zone mismatch", "fe80::1", "fe80::1%eth0", false, nil, nil}, + + // IPv4 with leading zeros is ambiguous (octal?), and is rejected + // as an address, so it is treated (and fails) as a hostname. + {"IPv4 leading zeros", "192.000.002.001", "192.0.2.1", false, + []string{"192.000.002.001"}, []string{`"192.000.002.001"`}}, + + // IPs are checked before resolving any hostname. + {"IP after hostname", "nine.example\n192.0.2.1", "192.0.2.1", + true, nil, nil}, + + {"hostname match", "one.example", "192.0.2.1", true, + []string{"one.example"}, nil}, + {"hostname IPv6 match", "nine.example", "2001:db8::9", true, + []string{"nine.example"}, nil}, + {"hostname mismatch", "nine.example", "192.0.2.1", false, + []string{"nine.example"}, nil}, + + // Stop resolving once there is a match. + {"first hostname matches", "one.example\nnine.example", + "192.0.2.1", true, []string{"one.example"}, nil}, + {"second hostname matches", "nine.example\none.example", + "192.0.2.1", true, []string{"nine.example", "one.example"}, nil}, + + // Lookup errors are logged, and the entry skipped. + {"unknown hostname", "missing.example", "192.0.2.1", false, + []string{"missing.example"}, []string{`"missing.example"`}}, + {"unknown, then match", "missing.example\none.example", + "192.0.2.1", true, []string{"missing.example", "one.example"}, + []string{`"missing.example"`}}, + {"timeout, then match", "slow.example\none.example", + "192.0.2.1", true, []string{"slow.example", "one.example"}, + []string{`"slow.example"`, "deadline exceeded"}}, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + lookups = nil + logBuf.Reset() + + dir := t.TempDir() + if c.hosts != absent { + err := os.WriteFile( + dir+"/allowed_hosts", []byte(c.hosts), 0o600) + if err != nil { + t.Fatal(err) + } + } + kc := NewKeyConfig(dir) + if err := kc.LoadAllowedHosts(); err != nil { + t.Fatal(err) + } + + httpreq := httptest.NewRequest("GET", "/v1/key", nil) + httpreq.RemoteAddr = net.JoinHostPort(c.remote, "1234") + err := kc.IsHostAllowed(&Request{httpreq}) + + if c.allowed && err != nil { + t.Errorf("expected allowed, got error: %v", err) + } + if !c.allowed && err == nil { + t.Errorf("expected not allowed, but it was") + } + if !slices.Equal(lookups, c.lookups) { + t.Errorf("lookups = %q, want %q", lookups, c.lookups) + } + for _, l := range c.logs { + if !strings.Contains(logBuf.String(), l) { + t.Errorf("log does not contain %q: %q", + l, logBuf.String()) + } + } + if c.logs == nil && logBuf.Len() > 0 { + t.Errorf("unexpected log: %q", logBuf.String()) + } + }) + } +} diff --git a/kxd/kxd.go b/kxd/kxd.go index 06bd965..a2f9a7b 100644 --- a/kxd/kxd.go +++ b/kxd/kxd.go @@ -163,7 +163,7 @@ func HandlerV1(w http.ResponseWriter, httpreq *http.Request) { return } - err = keyConf.IsHostAllowed(req.RemoteAddr) + err = keyConf.IsHostAllowed(&req) if err != nil { req.Printf("Host not allowed: %s", err) http.Error(w, "Host not allowed", http.StatusForbidden)