diff --git a/api/v1alpha/domain_types.go b/api/v1alpha/domain_types.go index 4e9bfe17..37b16225 100644 --- a/api/v1alpha/domain_types.go +++ b/api/v1alpha/domain_types.go @@ -102,6 +102,11 @@ const ( // was encountered during verification. DomainReasonVerificationInternalError = "InternalError" + // DomainReasonAddressNotPublic indicates that the HTTP token URL, or a + // redirect it returned, led to a non-public address, which verification + // refuses to connect to. + DomainReasonAddressNotPublic = "AddressNotPublic" + // DomainReasonVerified indicates domain ownership has been successfully // verified DomainReasonVerified = "Verified" diff --git a/docs/agent/skills/domain-verification.md b/docs/agent/skills/domain-verification.md index 553f79d1..7aed4d06 100644 --- a/docs/agent/skills/domain-verification.md +++ b/docs/agent/skills/domain-verification.md @@ -27,6 +27,7 @@ do not reformat them, and do not add quotes. | `RecordNotFound` | Datum looked and found nothing | Check the exact name, and that it is publicly visible | | `VerificationRecordContentMismatch` | The record is there, the value is wrong | Replace the value exactly. Remove any older record from a previous attempt | | `UnexpectedResponse` | Something answered, but not as expected | Check the domain resolves at all and nothing is answering in front of it | +| `AddressNotPublic` | The HTTP token URL, or a redirect from it, leads to a non-public address | Serve the token from a public address, or prove ownership with the DNS record | | `InternalError` | Datum's own fault | Say so, say to raise it, and do not suggest changes to their DNS | | `InvalidApex` | Not a registrable domain | They gave a public suffix like `com` or `co.uk`. Use the domain they registered | diff --git a/docs/architecture/domain-verification-by-delegation.md b/docs/architecture/domain-verification-by-delegation.md index 6266b2f3..8b832002 100644 --- a/docs/architecture/domain-verification-by-delegation.md +++ b/docs/architecture/domain-verification-by-delegation.md @@ -59,7 +59,7 @@ status, so neither waits on its own output. | Domain reconciler | `internal/controller/domain_controller.go` | Watches `Domain` and `DNSZone`. Runs the zone check, then TXT and HTTP. | | Zone verdict | `attemptDNSZoneVerification` | Decides `VerifiedDNSZone` from served zones and the delegation. | | Delegation resolver | `internal/delegation` | Reads delegations from the parent zone's servers, with an RDAP fallback. | -| TXT and HTTP checks | `attemptDNSVerification`, `attemptHTTPVerification` | Verify a `Domain` from a TXT record or an HTTP token. | +| TXT and HTTP checks | `attemptDNSVerification`, `attemptHTTPVerification` | Verify a `Domain` from a TXT record or an HTTP token. The HTTP check connects only to public addresses, on every redirect. | | Registration client | `internal/registrydata` | Registration data, RDAP nameservers for the fallback, and IP registrant enrichment. | | Hostname gate | `wildcard_ownership.go`, `gateway_controller.go`, and its copy in `internal/cmd/alb/spec/verification.go` | Admits a hostname on a verified `Domain`, and a wildcard on `VerifiedDNS` or `VerifiedDNSZone`. | | Gateway DNS | `gateway_dns_controller.go` | Writes records when the zone has DNS authority, from `status.nameservers`. | diff --git a/internal/agent/catalog.go b/internal/agent/catalog.go index 424f0ce0..e7cf04ec 100644 --- a/internal/agent/catalog.go +++ b/internal/agent/catalog.go @@ -720,6 +720,17 @@ var domainCatalog = []ReasonInfo{ "and no trailing spaces. If you have an older record from a previous attempt, remove it.", Skill: SkillDomainVerification, }, + { + Reason: networkingv1alpha.DomainReasonAddressNotPublic, + ConditionType: networkingv1alpha.DomainConditionVerified, + Actionability: ActionabilityUser, + Scope: ScopeOneHostname, + Explanation: "Datum did not fetch the HTTP token, because the token URL, or a redirect it " + + "returned, leads to a private or other non-public address.", + Remediation: "Serve the token from a public address, and keep any redirect from it on public " + + "addresses. If the site is reachable only privately, verify with the DNS record instead.", + Skill: SkillDomainVerification, + }, { Reason: networkingv1alpha.DomainReasonVerificationUnexpectedResponse, ConditionType: networkingv1alpha.DomainConditionVerified, diff --git a/internal/controller/domain_controller.go b/internal/controller/domain_controller.go index 6b915601..59e8a6fa 100644 --- a/internal/controller/domain_controller.go +++ b/internal/controller/domain_controller.go @@ -6,7 +6,6 @@ import ( "context" "errors" "fmt" - "io" "net" "net/http" "slices" @@ -556,7 +555,13 @@ func (r *DomainReconciler) attemptHTTPVerification( logger.Info("looking for HTTP token", "url", domainStatus.Verification.HTTPToken.URL) responseBody, httpResponse, err := r.httpGet(ctx, domainStatus.Verification.HTTPToken.URL) if err != nil { - if strings.Contains(err.Error(), "no such host") || strings.Contains(err.Error(), "connection refused") { + if errors.Is(err, errVerificationAddressNotPublic) { + logger.Info("refused to fetch the HTTP token from a non-public address", "error", err.Error()) + verifiedHTTPCondition.Reason = networkingv1alpha.DomainReasonAddressNotPublic + verifiedHTTPCondition.Message = "The HTTP token URL, or a redirect it returned, leads to a non-public address, " + + "and verification connects only to public addresses. " + + "Serve the token from a public address, or verify with the TXT record." + } else if strings.Contains(err.Error(), "no such host") || strings.Contains(err.Error(), "connection refused") { verifiedHTTPCondition.Reason = networkingv1alpha.DomainReasonPendingVerification verifiedHTTPCondition.Message = "unable to establish connection with HTTP token endpoint" } else if strings.Contains(err.Error(), "timeout") || strings.Contains(err.Error(), "deadline exceeded") { @@ -575,13 +580,20 @@ func (r *DomainReconciler) attemptHTTPVerification( expectedContent := domainStatus.Verification.HTTPToken.Body actualContent := strings.TrimSpace(string(responseBody)) - if actualContent == expectedContent { + switch { + case actualContent == expectedContent: verifiedHTTPCondition.Status = metav1.ConditionTrue verifiedHTTPCondition.Reason = networkingv1alpha.DomainReasonVerified verifiedHTTPCondition.Message = "HTTP token verification successful" - } else { + case strings.Contains(actualContent, expectedContent): + verifiedHTTPCondition.Reason = networkingv1alpha.DomainReasonVerificationRecordContentMismatch + verifiedHTTPCondition.Message = fmt.Sprintf( + "HTTP token content mismatch. The response body contains %q with other content around it; serve only the token.", + expectedContent) + default: verifiedHTTPCondition.Reason = networkingv1alpha.DomainReasonVerificationRecordContentMismatch - verifiedHTTPCondition.Message = fmt.Sprintf("HTTP token content mismatch. Expected %q, got %q", expectedContent, actualContent) + verifiedHTTPCondition.Message = fmt.Sprintf( + "HTTP token content mismatch. Expected the response body to be %q.", expectedContent) } logger.Info(verifiedHTTPCondition.Message) } else { @@ -590,40 +602,6 @@ func (r *DomainReconciler) attemptHTTPVerification( } } -// defaultHTTPGet is the default HTTP GET implementation for verification -func defaultHTTPGet(ctx context.Context, url string) ([]byte, *http.Response, error) { - client := &http.Client{ - Timeout: 10 * time.Second, - } - - req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) - if err != nil { - return nil, nil, fmt.Errorf("creating request: %w", err) - } - - resp, err := client.Do(req) - if err != nil { - return nil, nil, fmt.Errorf("executing request: %w", err) - } - defer func() { - // Avoid linter violation and exception - _ = resp.Body.Close() - }() - - if resp.StatusCode != http.StatusOK { - return nil, resp, nil - } - - // Limit response body to 1KB to prevent malicious responses - limitedReader := io.LimitReader(resp.Body, 1024) - body, err := io.ReadAll(limitedReader) - if err != nil { - return nil, resp, fmt.Errorf("reading response body: %w", err) - } - - return body, resp, nil -} - // reconcileRegistration keeps Status.Registration fresh and schedules independent timers. // Returns the next registration refresh time (zero if none). func (r *DomainReconciler) reconcileRegistration(ctx context.Context, d *networkingv1alpha.Domain, apex string) time.Time { @@ -733,7 +711,7 @@ func (r *DomainReconciler) SetupWithManager(mgr mcmanager.Manager) error { r.mgr = mgr r.timeNow = time.Now - r.httpGet = defaultHTTPGet + r.httpGet = newPublicHTTPVerificationGet() r.lookupTXT = net.DefaultResolver.LookupTXT registryCfg := r.Config.DomainRegistration.RegistryData diff --git a/internal/controller/domain_http_verification.go b/internal/controller/domain_http_verification.go new file mode 100644 index 00000000..22018f43 --- /dev/null +++ b/internal/controller/domain_http_verification.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package controller + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "syscall" + "time" + + "go.datum.net/network-services-operator/internal/validation" +) + +const ( + httpVerificationTimeout = 10 * time.Second + httpVerificationBodyLimit = 1024 +) + +var errVerificationAddressNotPublic = errors.New("verification address is not public") + +func refuseNonPublicAddress(address netip.AddrPort) error { + if r, ok := validation.NonPublicAddressRange(address.Addr().String()); ok { + return fmt.Errorf("%w: %s is in the %s range %s", errVerificationAddressNotPublic, address, r.Name, r.Prefix) + } + return nil +} + +func newPublicHTTPVerificationGet() func(ctx context.Context, url string) ([]byte, *http.Response, error) { + return newHTTPVerificationGet(refuseNonPublicAddress) +} + +func newHTTPVerificationGet( + refuse func(netip.AddrPort) error, +) func(ctx context.Context, url string) ([]byte, *http.Response, error) { + dialer := &net.Dialer{ + Timeout: httpVerificationTimeout, + ControlContext: func(_ context.Context, _, address string, _ syscall.RawConn) error { + addrPort, err := netip.ParseAddrPort(address) + if err != nil { + return fmt.Errorf("%w: cannot parse %q", errVerificationAddressNotPublic, address) + } + return refuse(addrPort) + }, + } + client := &http.Client{ + Timeout: httpVerificationTimeout, + Transport: &http.Transport{ + Proxy: nil, + DialContext: dialer.DialContext, + TLSHandshakeTimeout: httpVerificationTimeout, + DisableKeepAlives: true, + }, + } + + return func(ctx context.Context, url string) ([]byte, *http.Response, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, nil, fmt.Errorf("creating request: %w", err) + } + + resp, err := client.Do(req) + if err != nil { + return nil, nil, fmt.Errorf("executing request: %w", err) + } + defer func() { + _ = resp.Body.Close() + }() + + if resp.StatusCode != http.StatusOK { + return nil, resp, nil + } + + body, err := io.ReadAll(io.LimitReader(resp.Body, httpVerificationBodyLimit)) + if err != nil { + return nil, resp, fmt.Errorf("reading response body: %w", err) + } + + return body, resp, nil + } +} diff --git a/internal/controller/domain_http_verification_test.go b/internal/controller/domain_http_verification_test.go new file mode 100644 index 00000000..202b6216 --- /dev/null +++ b/internal/controller/domain_http_verification_test.go @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package controller + +import ( + "context" + "fmt" + "net" + "net/http" + "net/http/httptest" + "net/netip" + "net/url" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" +) + +func TestRefuseNonPublicAddress(t *testing.T) { + t.Parallel() + + refused := []string{ + "127.0.0.1:80", + "10.0.0.1:80", + "172.16.0.1:80", + "192.168.1.1:80", + "100.64.0.1:80", + "169.254.169.254:80", + "0.0.0.0:80", + "0.1.2.3:80", + "[::1]:80", + "[::]:80", + "[fc00::1]:443", + "[fd12:3456::1]:443", + "[fe80::1]:80", + "[fe80::1%en0]:80", + "[::ffff:127.0.0.1]:80", + "[::ffff:10.0.0.1]:80", + "[::ffff:169.254.169.254]:80", + "[64:ff9b::a00:1]:80", + } + for _, address := range refused { + t.Run(address, func(t *testing.T) { + t.Parallel() + assert.ErrorIs(t, refuseNonPublicAddress(netip.MustParseAddrPort(address)), errVerificationAddressNotPublic) + }) + } + + allowed := []string{ + "8.8.8.8:80", + "1.1.1.1:443", + "[2001:4860:4860::8888]:443", + "[::ffff:8.8.8.8]:80", + } + for _, address := range allowed { + t.Run(address, func(t *testing.T) { + t.Parallel() + assert.NoError(t, refuseNonPublicAddress(netip.MustParseAddrPort(address))) + }) + } +} + +type countingServer struct { + *httptest.Server + conns atomic.Int32 +} + +func newCountingServer(t *testing.T, handler http.Handler) *countingServer { + t.Helper() + s := &countingServer{Server: httptest.NewUnstartedServer(handler)} + s.Config.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateNew { + s.conns.Add(1) + } + } + s.Start() + t.Cleanup(s.Close) + return s +} + +func (s *countingServer) addrPort(t *testing.T) netip.AddrPort { + t.Helper() + u, err := url.Parse(s.URL) + require.NoError(t, err) + ap, err := netip.ParseAddrPort(u.Host) + require.NoError(t, err) + return ap +} + +func (s *countingServer) port(t *testing.T) uint16 { + return s.addrPort(t).Port() +} + +func TestHTTPVerificationGet(t *testing.T) { + t.Parallel() + + internal := newCountingServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = fmt.Fprint(w, "internal-secret") + })) + + public := newCountingServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/token": + _, _ = fmt.Fprint(w, "verification-token") + case "/to-internal": + http.Redirect(w, r, internal.URL+"/", http.StatusFound) + case "/to-internal-name": + http.Redirect(w, r, fmt.Sprintf("http://localhost:%d/", internal.port(t)), http.StatusFound) + case "/to-public": + http.Redirect(w, r, "/token", http.StatusMovedPermanently) + default: + http.NotFound(w, r) + } + })) + publicAddr := public.addrPort(t) + + httpGet := newHTTPVerificationGet(func(address netip.AddrPort) error { + if address == publicAddr { + return nil + } + return refuseNonPublicAddress(address) + }) + + refusedCases := []struct { + name string + url string + }{ + {name: "internal address", url: internal.URL + "/"}, + {name: "internal name", url: fmt.Sprintf("http://localhost:%d/", internal.port(t))}, + {name: "IPv4-mapped IPv6 internal address", url: fmt.Sprintf("http://[::ffff:127.0.0.1]:%d/", internal.port(t))}, + {name: "public URL redirecting to an internal address", url: public.URL + "/to-internal"}, + {name: "public URL redirecting to an internal name", url: public.URL + "/to-internal-name"}, + } + for _, tc := range refusedCases { + t.Run(tc.name, func(t *testing.T) { + body, resp, err := httpGet(context.Background(), tc.url) + assert.ErrorIs(t, err, errVerificationAddressNotPublic) + assert.Nil(t, body) + assert.Nil(t, resp) + }) + } + assert.Zero(t, internal.conns.Load(), "the guard must refuse before any connection reaches the internal server") + + t.Run("production guard refuses the server the test guard allows", func(t *testing.T) { + before := public.conns.Load() + _, _, err := newPublicHTTPVerificationGet()(context.Background(), public.URL+"/token") + assert.ErrorIs(t, err, errVerificationAddressNotPublic) + assert.Equal(t, before, public.conns.Load()) + }) + + t.Run("public URL", func(t *testing.T) { + body, resp, err := httpGet(context.Background(), public.URL+"/token") + require.NoError(t, err) + assert.Equal(t, http.StatusOK, resp.StatusCode) + assert.Equal(t, "verification-token", string(body)) + }) + + t.Run("public URL redirecting to a public URL", func(t *testing.T) { + body, resp, err := httpGet(context.Background(), public.URL+"/to-public") + require.NoError(t, err) + assert.Equal(t, http.StatusOK, resp.StatusCode) + assert.Equal(t, "verification-token", string(body)) + }) +} + +func TestAttemptHTTPVerificationStatus(t *testing.T) { + t.Parallel() + + const token = "8b0e4c0e-5d6a-4f0b-9c39-2a1f7f3c6d11" + + internal := newCountingServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = fmt.Fprint(w, "internal-secret") + })) + + tests := []struct { + name string + url string + httpGet func(ctx context.Context, url string) ([]byte, *http.Response, error) + wantReason string + wantMessage string + forbiddenText []string + }{ + { + name: "non-public address", + url: fmt.Sprintf("http://localhost:%d/", internal.port(t)), + httpGet: newPublicHTTPVerificationGet(), + wantReason: networkingv1alpha.DomainReasonAddressNotPublic, + forbiddenText: []string{"127.0.0.1", "::1", "localhost", "loopback", "internal-secret"}, + }, + { + name: "body without the token", + url: "http://example.com/", + httpGet: func(context.Context, string) ([]byte, *http.Response, error) { + return []byte("internal-secret"), &http.Response{StatusCode: http.StatusOK}, nil + }, + wantReason: networkingv1alpha.DomainReasonVerificationRecordContentMismatch, + wantMessage: fmt.Sprintf("HTTP token content mismatch. Expected the response body to be %q.", token), + forbiddenText: []string{"internal-secret"}, + }, + { + name: "body wrapping the token", + url: "http://example.com/", + httpGet: func(context.Context, string) ([]byte, *http.Response, error) { + return []byte("" + token + " internal-secret"), &http.Response{StatusCode: http.StatusOK}, nil + }, + wantReason: networkingv1alpha.DomainReasonVerificationRecordContentMismatch, + wantMessage: fmt.Sprintf( + "HTTP token content mismatch. The response body contains %q with other content around it; serve only the token.", token), + forbiddenText: []string{"internal-secret", ""}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := &DomainReconciler{httpGet: tt.httpGet} + status := &networkingv1alpha.DomainStatus{ + Verification: &networkingv1alpha.DomainVerificationStatus{ + HTTPToken: networkingv1alpha.HTTPVerificationToken{URL: tt.url, Body: token}, + }, + } + condition := &metav1.Condition{Type: networkingv1alpha.DomainConditionVerifiedHTTP, Status: metav1.ConditionFalse} + + r.attemptHTTPVerification(context.Background(), status, condition) + + assert.Equal(t, metav1.ConditionFalse, condition.Status) + assert.Equal(t, tt.wantReason, condition.Reason) + if tt.wantMessage != "" { + assert.Equal(t, tt.wantMessage, condition.Message) + } + for _, text := range tt.forbiddenText { + assert.NotContains(t, condition.Message, text) + } + }) + } + assert.Zero(t, internal.conns.Load()) +}