Skip to content
Open
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
70 changes: 51 additions & 19 deletions pkg/distribution/oci/remote/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -421,10 +421,39 @@ type resolverComponents struct {
plainHTTP bool
}

// perHostAuthorizers wraps a containerd hosts function so every host it returns
// — including configured mirrors — carries an authorizer whose guarded auth
// client trusts that host's own authority. The realm in a 401 challenge is
// attacker-controlled, so trusting only ref.Context().Registry would misjudge
// every mirror: an internal Docker Hub mirror on 127.0.0.1 or an RFC1918 address
// would have its own same-authority realm rejected because it was compared
// against docker.io. Binding the trust domain to the host actually contacted
// keeps those mirrors working while still blocking a realm that points
// anywhere else, including another service on the same host but a different
// port.
func perHostAuthorizers(base docker.RegistryHosts, creds func(string) (string, string, error), transport http.RoundTripper) docker.RegistryHosts {
if base == nil {
return nil
}
return func(host string) ([]docker.RegistryHost, error) {
hosts, err := base(host)
if err != nil {
return nil, err
}
for i := range hosts {
hosts[i].Authorizer = docker.NewDockerAuthorizer(
docker.WithAuthCreds(creds),
docker.WithAuthClient(newGuardedAuthClient(transport, hosts[i].Host)))
}
return hosts, nil
}
}

// createResolver creates a docker resolver with the given options.
func createResolver(o *options, ref reference.Reference) resolverComponents {
creds := credentialsFunc(o, ref)
authorizer := docker.NewDockerAuthorizer(
docker.WithAuthCreds(credentialsFunc(o, ref)),
docker.WithAuthCreds(creds),
docker.WithAuthClient(newGuardedAuthClient(o.transport, ref.Context().Registry.RegistryStr())))

// Wrap transport with Range header support for resumable downloads
Expand All @@ -439,7 +468,7 @@ func createResolver(o *options, ref reference.Reference) resolverComponents {
if usePlainHTTP {
// For plain HTTP, use a custom hosts function
resolver = docker.NewResolver(docker.ResolverOptions{
Hosts: func(host string) ([]docker.RegistryHost, error) {
Hosts: perHostAuthorizers(func(host string) ([]docker.RegistryHost, error) {
return []docker.RegistryHost{
{
Host: host,
Expand All @@ -450,11 +479,11 @@ func createResolver(o *options, ref reference.Reference) resolverComponents {
Client: client,
},
}, nil
},
}, creds, o.transport),
})
} else {
resolver = docker.NewResolver(docker.ResolverOptions{
Hosts: registryutil.RegistryHosts(o.registryMirrors, authorizer, client),
Hosts: perHostAuthorizers(registryutil.RegistryHosts(o.registryMirrors, authorizer, client), creds, o.transport),
})
}

Expand Down Expand Up @@ -517,25 +546,28 @@ func createResolverWithPushScope(o *options, ref reference.Reference) (resolverC
// Create resolver with the pre-authorized token
// We keep the original auth available for re-challenges (e.g., token expiry, additional scope)
// The BearerTransport will handle the primary auth, but if challenged, we can re-exchange
creds := func(host string) (string, string, error) {
// Return original credentials to handle potential re-challenges
// (token refresh, additional scope requests)
cfg, err := auth.Authorization()
if err != nil {
return "", "", err
}
if cfg.RegistryToken != "" {
return "", cfg.RegistryToken, nil
}
return cfg.Username, cfg.Password, nil
}
authorizer := docker.NewDockerAuthorizer(
docker.WithAuthCreds(func(host string) (string, string, error) {
// Return original credentials to handle potential re-challenges
// (token refresh, additional scope requests)
cfg, err := auth.Authorization()
if err != nil {
return "", "", err
}
if cfg.RegistryToken != "" {
return "", cfg.RegistryToken, nil
}
return cfg.Username, cfg.Password, nil
}),
docker.WithAuthCreds(creds),
docker.WithAuthClient(newGuardedAuthClient(o.transport, ref.Context().Registry.RegistryStr())))

resolver := docker.NewResolver(docker.ResolverOptions{
Hosts: docker.ConfigureDefaultRegistries(
docker.WithAuthorizer(authorizer),
docker.WithClient(client)),
Hosts: perHostAuthorizers(
docker.ConfigureDefaultRegistries(
docker.WithAuthorizer(authorizer),
docker.WithClient(client)),
creds, o.transport),
})

return resolverComponents{
Expand Down
12 changes: 8 additions & 4 deletions pkg/distribution/oci/remote/ssrf_pull_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ import (
// end: a malicious registry answers every request with a 401 Bearer challenge
// whose realm points at a loopback "internal service". The token fetch that
// containerd's authorizer performs against that realm must be blocked, so the
// internal service is never contacted. This is the code path (remote.Image ->
// createResolver) that the original CVE-2026-33990 fix left unguarded.
// internal service is never contacted.
//
// The internal service sits on the same IP as the registry but a different
// port: trust is scoped to the exact authority (host and port) being contacted,
// so advertising another service on the same host must not be enough to have
// the token request followed there.
func TestPullSSRF_RealmNotFollowedToInternalService(t *testing.T) {
var internalHits atomic.Int32
internalService := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
Expand All @@ -29,7 +33,7 @@ func TestPullSSRF_RealmNotFollowedToInternalService(t *testing.T) {

maliciousRegistry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("WWW-Authenticate",
fmt.Sprintf(`Bearer realm="%s/token",service="evil-registry"`, internalService.URL))
`Bearer realm="`+internalService.URL+`/token",service="evil-registry"`)
w.WriteHeader(http.StatusUnauthorized)
}))
defer maliciousRegistry.Close()
Expand All @@ -42,7 +46,7 @@ func TestPullSSRF_RealmNotFollowedToInternalService(t *testing.T) {

_, err = remote.Image(ref, remote.WithContext(t.Context()), remote.WithPlainHTTP(true))
if err == nil {
t.Fatal("remote.Image should have failed: the token realm resolves to a loopback address and must be rejected")
t.Fatal("remote.Image should have failed: the token realm points at a different authority on the same host and must be rejected")
}
if hits := internalHits.Load(); hits != 0 {
t.Errorf("SSRF not blocked on the pull path: the internal service at %s was contacted %d time(s) via the token realm", internalService.URL, hits)
Expand Down
110 changes: 103 additions & 7 deletions pkg/distribution/oci/remote/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,96 @@ func isTrustedDockerTokenEndpoint(u *url.URL, registryHost string) bool {
u.EscapedPath() == "/token"
}

// normalizeAuthority returns host as a canonical "host:port" authority, filling
// in the scheme's default port when host carries none. The trust domain is the
// full authority, not the bare hostname: the same IP on a different port is a
// different service, so comparing hostnames alone would reopen the SSRF.
func normalizeAuthority(host, scheme string) string {
if host == "" {
return ""
}
h, port, err := net.SplitHostPort(host)
if err != nil {
// No port at all (or a bare IPv6 address): use the scheme default.
h, port = host, ""
}
Comment on lines +115 to +119
if port == "" {
switch scheme {
case "https":
port = "443"
case "http":
port = "80"
}
}
if port == "" {
return h
}
return net.JoinHostPort(h, port)
}

// isTrustedAuthority reports whether a normalized realm authority belongs to
// the registry being contacted. An empty registry host trusts nothing, so
// callers without a known registry host get the full blocklist.
func isTrustedAuthority(realmAuthority, registryHost string) bool {
if registryHost == "" {
return false
}
for _, scheme := range []string{"https", "http"} {
if strings.EqualFold(realmAuthority, normalizeAuthority(registryHost, scheme)) {
return true
Comment on lines +141 to +143
}
}
return false
}

// isSameAuthorityRealm reports whether the realm URL points at the exact same
// authority (host and port) as the registry being contacted. Such a token
// endpoint is inside the registry's own trust domain, so its private/loopback/
// link-local address is legitimate (internal and self-hosted registries). The
// scheme is taken from the realm URL, which matches the registry for the
// registries that advertise their own token endpoint.
func isSameAuthorityRealm(u *url.URL, registryHost string) bool {
return isTrustedAuthority(normalizeAuthority(u.Host, u.Scheme), registryHost)
Comment on lines +155 to +156
}

// lookupHostAddrs returns the addresses hostname resolves to, or hostname itself
// when it is already a literal IP.
func lookupHostAddrs(hostname string) ([]string, error) {
if ip := net.ParseIP(hostname); ip != nil {
return []string{hostname}, nil
}
ips, err := net.LookupHost(hostname)
if err != nil {
return nil, fmt.Errorf("resolving realm hostname %q: %w", hostname, err)
}
if len(ips) == 0 {
return nil, fmt.Errorf("realm hostname %q resolved to no addresses", hostname)
}
return ips, nil
}

// resolveHost resolves hostname to a pinned dial address (ip:port) without
// applying the blocklist. Used for realms inside the registry's own trust
// domain, where private/loopback/link-local addresses are legitimate. Pinning
// is still done: the caller dials the exact address that was resolved, so DNS
// rebinding cannot swap in a different host between resolution and connection.
func resolveHost(hostname, port string) (string, error) {
addrs, err := lookupHostAddrs(hostname)
if err != nil {
return "", err
}
return net.JoinHostPort(addrs[0], port), nil
}

// validateTokenEndpointURL validates untrusted token endpoints against the
// internal-hostname and private/loopback/link-local blocklists. Docker Hub's
// trusted HTTPS token endpoint does not require local DNS resolution: a proxy
// may resolve it on networks where public DNS is unavailable to the client.
// Direct connections still validate and pin the resolved IP in their dialer.
// internal-hostname and private/loopback/link-local blocklists. Two narrow
// exceptions skip local DNS resolution: Docker Hub's trusted HTTPS token
// endpoint (a proxy may resolve it where public DNS is unavailable), and a
// realm on the same authority as the registry being contacted (internal and
// self-hosted registries). Direct connections still validate and pin the
// resolved IP in their dialer for every other realm.
func validateTokenEndpointURL(u *url.URL, registryHost string) error {
if isTrustedDockerTokenEndpoint(u, registryHost) {
if isTrustedDockerTokenEndpoint(u, registryHost) || isSameAuthorityRealm(u, registryHost) {
return nil
Comment on lines 195 to 197
}
port := u.Port()
Expand Down Expand Up @@ -169,8 +252,11 @@ func resolveAndValidateHost(hostname, port string) (dialAddr string, err error)
// both by containerd's authorizer (via docker.WithAuthClient) and by the
// hand-rolled Exchange(). The realm URL in a registry's WWW-Authenticate
// challenge is attacker-controlled, so every request this client makes is
// validated before a connection is established, with a narrow exception for
// Docker Hub's trusted token endpoint when using a proxy.
// validated before a connection is established, with two narrow exceptions:
// Docker Hub's trusted token endpoint when using a proxy, and realms on the
// same authority as the registry being contacted (internal registries). The
// latter are still resolved and pinned to the resolved IP, so DNS rebinding
// cannot redirect them elsewhere.
//
// How the connection is guarded depends on whether a proxy applies to the
// request (see guardedAuthTransport). A dial-time-only guard would break every
Expand All @@ -194,6 +280,16 @@ func newGuardedAuthClient(base http.RoundTripper, registryHost string) *http.Cli
if err != nil {
return nil, fmt.Errorf("invalid token endpoint address %q: %w", addr, err)
}
if isTrustedAuthority(normalizeAuthority(addr, ""), registryHost) {
// Realm is the registry's own authority: skip the blocklist but
// still pin the resolved address, so DNS rebinding cannot redirect
// this connection (see validateTokenEndpointURL).
dialAddr, err := resolveHost(host, port)
if err != nil {
return nil, err
}
return (&net.Dialer{}).DialContext(ctx, network, dialAddr)
}
dialAddr, err := resolveAndValidateHost(host, port)
if err != nil {
return nil, err
Expand Down
38 changes: 38 additions & 0 deletions pkg/distribution/oci/remote/transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,44 @@ func TestExchangeSSRF_RequestSentToRealmURL(t *testing.T) {
}
}

// TestExchangeAllowsInternalRealmOnSameHost verifies that an internal/corporate
// registry whose token endpoint lives on the same host (e.g. an RFC1918 address
// or loopback) is NOT blocked by the SSRF guard. The realm is within the same
// trust domain as the registry being pulled, so private/loopback/link-local
// addresses must be permitted there.
func TestExchangeAllowsInternalRealmOnSameHost(t *testing.T) {
var hitCount atomic.Int32

// "Internal service" on 127.0.0.1 — without the same-host exception this
// would be rejected by the loopback blocklist.
internalService := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hitCount.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, `{"token":"internal-token"}`)
}))
defer internalService.Close()

// The realm is served by the registry's own authority — same host and same
// port — so it falls inside the trust domain even though the address is
// loopback. A different port on the same host is a different service and
// must stay blocked; see TestPullSSRF_RealmNotFollowedToInternalService.
ref, err := reference.ParseReference(strings.TrimPrefix(internalService.URL, "http://") + "/myimage")
if err != nil {
t.Fatalf("failed to parse reference: %v", err)
}

pr := pingResponseForRealm(internalService.URL + "/token")

_, err = remote.Exchange(t.Context(), ref.Context().Registry, nil, nil, []string{"repository:x:pull"}, pr)
if err != nil && strings.Contains(err.Error(), "realm URL rejected") {
t.Fatalf("internal same-host realm was wrongly rejected: %v", err)
}
if hitCount.Load() == 0 {
t.Errorf("expected the token request to reach the internal service at %s (same-host realms must be allowed)", internalService.URL)
}
}

// TestExchangeSSRF_SensitiveBodyNotReflectedInError verifies that Exchange()
// does NOT include a token-endpoint response body in the error it returns to
// the caller.
Expand Down
Loading