Skip to content

Fix token realm SSRF guard to allow registries on the same host - #1053

Open
okhowang wants to merge 1 commit into
docker:mainfrom
okhowang:fix/ssrf-allow-same-host-internal-registry
Open

okhowang wants to merge 1 commit into
docker:mainfrom
okhowang:fix/ssrf-allow-same-host-internal-registry

Conversation

@okhowang

@okhowang okhowang commented Sep 1, 2026 •

Copy link
Copy Markdown

Description

PR #1038 blocks token-exchange realms (WWW-Authenticate: Bearer realm=...) resolving to private/loopback/link-local addresses. That blocklist is too broad: it also rejects internal/corporate registries whose token endpoint lives on an RFC1918 network (or on localhost), because their realm resolves to a private IP, so pulls fail with realm URL rejected.

This PR replaces the blanket private-IP block with trust-domain validation.

Contract

A realm is exempt from the blocklist only when its full authority equals the authority of the host actually being contacted:

  • Host AND port must match (case-insensitive). The same host on a different port is a different service and stays blocked — this is deliberate and prevents a registry from pivoting the client to another local service.
  • The effective scheme of the contacted host determines the default port. An HTTPS registry never implicitly trusts an HTTP (port 80) endpoint on the same hostname.
  • The host is the one actually contacted, so configured mirrors on private networks trust their own authority rather than the reference's registry. Bracketed IPv6 literals are normalized so they match the dialer's form.

Everything else keeps the full blocklist, including DNS resolution and IP pinning: the cloud metadata service, other internal hosts, and other services on the same host remain blocked.

Changes

  • normalizeAuthority / isTrustedAuthority / isSameAuthorityRealm: canonical comparison against a single trusted authority.
  • newGuardedAuthClient and validateTokenEndpointURL take the contacted host and its effective scheme, instead of probing both https and http default ports.
  • perHostAuthorizers: builds an authorizer per registry host (including mirrors), bound to that host's own authority.
  • resolveHost: same-authority realms are still resolved and pinned to the resolved IP.

Tests

  • TestNormalizeAuthority — authority normalization, including bracketed/bare IPv6 forms.
  • TestIsSameAuthorityRealm — trusted vs distrusted cases: cross-scheme port, same-host different port, different host, and empty registry host.
  • TestExchangeAllowsInternalRealmOnSameHost — an internal same-authority realm is allowed.
  • TestPullSSRF_RealmNotFollowedToInternalService — a same-IP different-port pivot is rejected, asserted to receive zero requests.
  • Existing loopback/link-local, proxy, and Docker Hub token tests unchanged.

Manual verification

Built dmr from this branch and from origin/main, each pulling oci.cnb.cool/coldenchen/test with proxies disabled and the registry resolving to an internal 169.254.x.x address:

  • origin/main: fails with realm URL resolves to a disallowed address 169.254.1.49
  • this branch: Model pulled successfully (88.21 MB, model present in the store)

Known limitation

Same-authority realms skip the private-address blocklist by design. resolveHost pins the resolved IP, which protects the resolution-to-connection window, but it does not re-apply isDisallowedIP to that IP, and the proxied path performs no destination resolution at all. A hostname that is re-bound between the registry request and the token request could therefore reach an internal address. Closing this properly requires binding the exception to the already-validated registry connection / allowed addresses rather than to the hostname alone; happy to follow up on that if the maintainers want it in this PR.

Related

Created with: CodeBuddy

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="pkg/distribution/oci/remote/remote.go" line_range="428" />
<code_context>
 func createResolver(o *options, ref reference.Reference) resolverComponents {
 	authorizer := docker.NewDockerAuthorizer(
 		docker.WithAuthCreds(credentialsFunc(o, ref)),
-		docker.WithAuthClient(newGuardedAuthClient(o.transport)))
+		docker.WithAuthClient(newGuardedAuthClient(o.transport, ref.Context().Registry.RegistryStr())))

</code_context>
<issue_to_address>
**issue (broader_impact):** The resolver's guarded auth client compares a token realm against the original reference registry, even when the resolver is contacting a configured mirror. A mirror at `localhost`, `127.0.0.1`, or an RFC1918 host therefore has its same-host realm rejected because it is compared with `docker.io`/`registry-1.docker.io`, so authentication through internal Docker Hub mirrors fails.

**Triggers:** When `WithRegistryMirrors` is configured and the mirror's token endpoint is on the mirror host.

**Suggested fix:** Pass the actual `RegistryHost.Host` being contacted into the guarded auth client, or construct the auth client/guard with the host per resolver host rather than once from `ref.Context().Registry`.
</issue_to_address>

### Comment 2
<location path="pkg/distribution/oci/remote/transport.go" line_range="199-202" />
<code_context>
 // address — commonly a private or loopback IP — rather than the realm's, and
 // would reject the proxy itself.
-func newGuardedAuthClient(base http.RoundTripper) *http.Client {
+func newGuardedAuthClient(base http.RoundTripper, registryHost string) *http.Client {
 	var proxied *http.Transport
 	if t, ok := base.(*http.Transport); ok {
</code_context>
<issue_to_address>
**nitpick:** The function comment still says every token request is validated against the internal-hostname and private-address blocklists, but the new same-host path deliberately bypasses both checks. The documentation is false for realms matching `registryHost`, obscuring that `localhost` and private addresses are now explicitly permitted.

**Triggers:** When callers or security reviewers rely on the function comment to understand the SSRF guarantees.

**Suggested fix:** Update the comment to state that validation is skipped for realms whose host matches `registryHost`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread pkg/distribution/oci/remote/remote.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Critical DNS-rebinding and moderate registry-host and pull-test issues remain unresolved.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 High severity · 2 Medium severity

Open (3)
What changed in this PR

This PR narrows token-realm SSRF protection to allow same-host internal registries while continuing to block cross-host internal destinations.

Changes:

  • Adds same-host realm validation and guarded-client plumbing.
  • Threads registry host information through exchange and resolver paths.
  • Updates same-host and cross-host SSRF tests.
File Summary
pkg/​distribution/​oci/​remote/​transport.go Adds same-host handling; critical concern: bypasses DNS pinning, permitting same-host rebinding.
pkg/​distribution/​oci/​remote/​transport_test.go Adds same-host internal realm coverage.
pkg/​distribution/​oci/​remote/​ssrf_pull_test.go Updates cross-host SSRF coverage; moderate concern: does not verify zero requests were sent.
pkg/​distribution/​oci/​remote/​remote.go Passes registry hosts into clients; moderate concerns affect mirrors and missing pull-path success coverage.
pkg/​distribution/​oci/​remote/​guard_internal_test.go Updates guarded-client test construction.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +216 to +219
if sameHost(host, registryHost) {
// Realm is the registry's own host: dial directly without the
// internal-address blocklist (see validateTokenEndpointURL).
return (&net.Dialer{}).DialContext(ctx, network, addr)
Comment thread pkg/distribution/oci/remote/remote.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

Address registry mirror handling, pull-path coverage, observable SSRF blocking assertions, and DNS-rebinding protection.

Review effort: Lite
Findings: 1 High severity · 2 Medium severity

Open (3)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

Unresolved mirror-host handling, SSRF test coverage, and IPv6 same-host normalization issues remain.

Review effort: Lite
Findings: 1 High severity · 2 Medium severity

Open (3)

@ericcurtin

Copy link
Copy Markdown
Contributor

sameHost() strips ports before comparing, so a malicious registry on the same IP but a different port is now treated as trusted, this reopens the SSRF the guard was meant to close (see the failing TestCreateModelSSRF_RealmNotFollowedToInternalService). Also lint is failing (gofmt alignment, unnecessary Sprintf). Please fix both. Also, model-runner is being deprecated in favor of llmman, please open future PRs there instead. Marking as draft, please mark ready for review once addressed.

@ericcurtin
ericcurtin marked this pull request as draft September 26, 2026 14:20
@okhowang
okhowang force-pushed the fix/ssrf-allow-same-host-internal-registry branch from ab42645 to 02468f8 Compare September 28, 2026 07:49
@ericcurtin

Copy link
Copy Markdown
Contributor

@okhowang PTAL when you get a chance. Thanks for the authority-based fix. It now conflicts with main, so it needs a rebase. Please mark ready for review once done.

@okhowang
okhowang force-pushed the fix/ssrf-allow-same-host-internal-registry branch from 02468f8 to 4a758bd Compare November 24, 2026 06:14
@okhowang
okhowang marked this pull request as ready for review November 24, 2026 06:23
@ericcurtin
ericcurtin requested a lite review from Copilot November 24, 2026 08:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The implementation has unresolved authority-matching and IPv6 normalization bugs, plus critical scheme/port confusion and DNS-rebinding exposure that can bypass the intended SSRF protections.

5 open issues
2 resolved since last review

Review effort: Lite

Comment on lines 195 to 197
func validateTokenEndpointURL(u *url.URL, registryHost string) error {
if isTrustedDockerTokenEndpoint(u, registryHost) {
if isTrustedDockerTokenEndpoint(u, registryHost) || isSameAuthorityRealm(u, registryHost) {
return nil
Comment on lines +155 to +156
func isSameAuthorityRealm(u *url.URL, registryHost string) bool {
return isTrustedAuthority(normalizeAuthority(u.Host, u.Scheme), registryHost)
PR docker#1038 blocked token-exchange realms (WWW-Authenticate: Bearer realm=...)
resolving to private/loopback/link-local addresses. That blocklist is too broad:
it also rejects internal/corporate registries whose token endpoint lives on an
RFC1918 network or on localhost, because their realm resolves to a private IP.

Replace the blanket private-IP block with trust-domain validation: a realm is
trusted only when its full authority (host AND port) equals the authority of
the host actually being contacted. The same host on a different port is a
different service and stays blocked, and the effective scheme of the contacted
host decides the default port, so an HTTPS registry never implicitly trusts an
HTTP endpoint on the same hostname.

- normalizeAuthority / isTrustedAuthority / isSameAuthorityRealm: compare one
  canonical authority; strip brackets from IPv6 literals so they are not
  double-bracketed and always match the dialer's form.
- newGuardedAuthClient and validateTokenEndpointURL take the contacted host and
  its effective scheme instead of guessing both https and http.
- perHostAuthorizers: build the authorizer per registry host (including
  mirrors) bound to that host's own authority.
- resolveHost: same-authority realms are still resolved and pinned.

Tests: authority normalization (including IPv6), trusted vs distrusted realms
(cross-scheme port, same-host different port, different host, empty host), plus
the existing pull-path and endpoint-level SSRF regressions.

Created with: CodeBuddy
@okhowang
okhowang force-pushed the fix/ssrf-allow-same-host-internal-registry branch from 4a758bd to c63860f Compare November 24, 2026 12:03
@sourcery-ai

sourcery-ai Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit c63860f

#1050 SSRF fix in PR #1038 blocks all private/loopback/link-local realm addresses, breaking internal/corporate registries · 0 of 3 met

# Requirement Status Notes
1 Allow realms on the registry authority or its configured auth hosts, while blocking unrelated pivots. 🟡 Partly met The change trusts the exact authority of the host contacted, including mirrors, but does not allow a separately configured auth host such as auth.corp.internal.
2 Keep a narrow safety net that blocks cloud-metadata addresses. 🟡 Partly met The existing blocklist still blocks metadata addresses for other authorities, but the same-authority exemption can bypass it for a metadata address.
3 Retain DNS-rebinding protection by rechecking at dial time and dialing the resolved IP. 🟡 Partly met Direct same-authority requests pin a fresh resolution, but do not recheck it against the blocklist; proxied requests do not resolve or pin the destination.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New gaps against the linked issues

// 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, registryScheme string) error {
if isTrustedDockerTokenEndpoint(u, registryHost) || isSameAuthorityRealm(u, registryHost, registryScheme) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Always block metadata endpoints

This condition skips all endpoint validation for same-authority realms, including metadata-address checks. The issue asks for metadata destinations to remain blocked even when applying the trust-domain exception.

Prompt for AI agents
In `pkg/distribution/oci/remote/transport.go` at line 195:

**Always block metadata endpoints**

This condition skips all endpoint validation for same-authority realms, including metadata-address checks. The issue asks for metadata destinations to remain blocked even when applying the trust-domain exception.

From #1050:

Keep a narrow safety net that blocks cloud-metadata addresses.

Comment on lines +290 to +294
dialAddr, err := resolveHost(host, port)
if err != nil {
return nil, err
}
return (&net.Dialer{}).DialContext(ctx, network, dialAddr)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Revalidate same-host resolutions

The direct same-authority path pins a fresh token-time resolution but does not revalidate that address against the blocklist, so a hostname rebound between the registry request and token request can reach an internal or metadata address. The proxied path also does not pin the destination.

Prompt for AI agents
In `pkg/distribution/oci/remote/transport.go` at lines 290-294:

**Revalidate same-host resolutions**

The direct same-authority path pins a fresh token-time resolution but does not revalidate that address against the blocklist, so a hostname rebound between the registry request and token request can reach an internal or metadata address. The proxied path also does not pin the destination.

From #1050:

Retain DNS-rebinding protection by rechecking at dial time and dialing the resolved IP.

Comment on lines +444 to +447
hosts[i].Authorizer = docker.NewDockerAuthorizer(
docker.WithAuthCreds(creds),
docker.WithAuthClient(newGuardedAuthClient(transport, hosts[i].Host, hosts[i].Scheme)))
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Allow configured auth hosts

The authorizer is bound only to each contacted registry host's authority. A registry whose configured token service uses a separate allowed host, such as auth.corp.internal, still fails the private-address guard.

Prompt for AI agents
In `pkg/distribution/oci/remote/remote.go` at lines 444-447:

**Allow configured auth hosts**

The authorizer is bound only to each contacted registry host's authority. A registry whose configured token service uses a separate allowed host, such as auth.corp.internal, still fails the private-address guard.

From #1050:

Allow realms on the registry authority or its configured auth hosts, while blocking unrelated pivots.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A critical SSRF guard bypass remains in the token-request exception because it is not bound to the registry connection’s validated destination address, including when a proxy is used.

3 open issues
2 resolved since last review

Review effort: Lite

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A critical active finding remains: the realm exception can allow DNS rebinding or proxy resolution to route token requests to private or loopback services because the resolved address is pinned without being rejected or tied to the validated registry endpoint.

4 open issues

Review effort: Lite

Comment on lines +195 to 196
if isTrustedDockerTokenEndpoint(u, registryHost) || isSameAuthorityRealm(u, registryHost, registryScheme) {
return nil

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SSRF fix in PR #1038 blocks all private/loopback/link-local realm addresses, breaking internal/corporate registries

3 participants