Skip to content

transport: validate Bearer realm URL to prevent SSRF - #2243

Merged
Subserial merged 3 commits into
google:mainfrom
evilgensec:fix/ssrf-bearer-realm-validation
Mar 31, 2026
Merged

Subserial merged 3 commits into
google:mainfrom
evilgensec:fix/ssrf-bearer-realm-validation

Conversation

@evilgensec

@evilgensec evilgensec commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

fromChallenge() stored the realm value from a WWW-Authenticate: Bearer header verbatim, with no validation of scheme or destination host. When the client subsequently fetched a token, it made an HTTP request to whatever URL the registry supplied — including private/link-local addresses and non-HTTP schemes.

Root cause:

realm, ok := pr.Parameters["realm"]  // from attacker-controlled header
// ... stored directly, no validation
return &bearerTransport{realm: realm, ...}

Attack scenario: An attacker-controlled registry (or MITM on an HTTP registry connection) returns:

WWW-Authenticate: Bearer realm="http://169.254.169.254/latest/meta-data/iam/security-credentials/my-role",service="x"

The client sends a GET to the AWS/GCP instance metadata endpoint, leaking IAM credentials. The basic credentials sent with the token request are also leaked to the attacker-controlled realm.

This affects all tools using go-containerregistry for pulls: crane, ko, Kubernetes admission controllers, and CI/CD pipelines.

Fix

Add validateRealmURL() called from fromChallenge() before storing realm:

  • Scheme: only https for secure registries; http additionally allowed for insecure registries
  • IP literals: loopback, link-local unicast/multicast, and private-range addresses are rejected (blocks direct SSRF to RFC 1918 and cloud IMDS endpoints)

Related security report: https://issuetracker.google.com/issues/495960898

fromChallenge() stored the realm value from a WWW-Authenticate header
verbatim without validation. A malicious or MITM'd registry could supply
a realm pointing at a private/link-local address (e.g. 169.254.169.254)
or use a non-HTTP scheme, causing the client to make token-fetch requests
to internal services when pulling images.

Add validateRealmURL() which enforces:
- Scheme allowlist: only https is accepted for secure registries; http
  is additionally accepted when the registry is marked insecure.
- IP literal blocklist: loopback, link-local unicast/multicast, and
  private-range addresses are rejected. This blocks direct SSRF to cloud
  instance metadata services and RFC 1918 networks. DNS-based SSRF is
  out of scope and should be handled at the network layer.
@Subserial

Subserial commented Mar 26, 2026 •

Copy link
Copy Markdown

The security report URL seems to be incorrect. The referenced issue seems unrelated.

@evilgensec

Copy link
Copy Markdown
Contributor Author

Dear @Subserial,

I have updated the report url: https://issuetracker.google.com/issues/495960898

As the security tab of the program instructs to report vulnerabilities through google bug hunter, I have done so. If anything else is needed please let me know.

@evilgensec

Copy link
Copy Markdown
Contributor Author

@Subserial Hope you are doing well. Is there any update on the issue?

@codecov-commenter

codecov-commenter commented Mar 31, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 33.33333% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 52.96%. Comparing base (8b3c303) to head (f014b61).
⚠️ Report is 82 commits behind head on main.

Files with missing lines Patch % Lines
pkg/v1/remote/transport/bearer.go 33.33% 8 Missing and 4 partials ⚠️

❗ There is a different number of reports uploaded between BASE (8b3c303) and HEAD (f014b61). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (8b3c303) HEAD (f014b61)
2 1
Additional details and impacted files
@@             Coverage Diff             @@
##             main    #2243       +/-   ##
===========================================
- Coverage   71.67%   52.96%   -18.72%     
===========================================
  Files         123      165       +42     
  Lines        9935    11215     +1280     
===========================================
- Hits         7121     5940     -1181     
- Misses       2115     4561     +2446     
- Partials      699      714       +15     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Subserial
Subserial merged commit a2f47d4 into google:main Mar 31, 2026
17 checks passed
Subserial pushed a commit that referenced this pull request May 15, 2026
…2295)

* remote: block SSRF via private-IP Location headers in blob uploads

nextLocation() extracts the Location header from registry responses
during blob upload (POST→PATCH→PUT sequence) and uses it verbatim as
the target for subsequent requests. A malicious or compromised registry
can return a Location pointing at a private or link-local IP address
(e.g. 169.254.169.254 for cloud IMDS, 10.x.x.x for internal services),
causing the client to send HTTP PATCH and PUT requests—including the
full layer blob as the body—to internal network endpoints that are
not directly reachable by the attacker.

Add an IP-literal blocklist to nextLocation() that rejects cross-host
redirects targeting loopback, link-local, private, and unspecified
addresses. Same-host redirects (different path on the same registry)
are always allowed so that test servers using 127.0.0.1 and self-
referential registries are unaffected.

This is analogous to the validateRealmURL() fix introduced in #2243
for WWW-Authenticate realm SSRF, extended to cover the upload location
code path.

* remote: block SSRF via private-IP redirects in blob/manifest downloads

makeFetcher() created an http.Client with no CheckRedirect policy,
so http.Client.Do() would silently follow 302 redirects issued by a
malicious registry to private or link-local IP addresses during any
pull operation (manifest fetch, blob download).

Add checkRedirectSSRF() as the CheckRedirect handler on the fetcher
client. It rejects cross-host redirects whose destination hostname
is a private or link-local IP literal (loopback, RFC 1918,
link-local unicast/multicast, unspecified), mirroring the check
already applied to blob upload Location headers in the previous
commit. Same-host redirects are always permitted.

This is the download-path counterpart to the upload-path fix
introduced in the previous commit for nextLocation().

* remote: add TestCheckRedirectSSRF to cover fetcher SSRF protection

Add unit tests for checkRedirectSSRF in fetcher.go:
- Cross-host redirects to private/link-local/loopback IPs are rejected
- Same-host redirects (including loopback for local test registries) are allowed
- Public IP and DNS hostname redirects are allowed
- Early-exit paths (empty via, nil Response) are covered

* remote: fix goimports formatting in fetcher.go and fetcher_test.go

* remote: fix goimports formatting in write_test.go
Subserial pushed a commit to Subserial/go-containerregistry that referenced this pull request May 15, 2026
…oogle#2295)

* remote: block SSRF via private-IP Location headers in blob uploads

nextLocation() extracts the Location header from registry responses
during blob upload (POST→PATCH→PUT sequence) and uses it verbatim as
the target for subsequent requests. A malicious or compromised registry
can return a Location pointing at a private or link-local IP address
(e.g. 169.254.169.254 for cloud IMDS, 10.x.x.x for internal services),
causing the client to send HTTP PATCH and PUT requests—including the
full layer blob as the body—to internal network endpoints that are
not directly reachable by the attacker.

Add an IP-literal blocklist to nextLocation() that rejects cross-host
redirects targeting loopback, link-local, private, and unspecified
addresses. Same-host redirects (different path on the same registry)
are always allowed so that test servers using 127.0.0.1 and self-
referential registries are unaffected.

This is analogous to the validateRealmURL() fix introduced in google#2243
for WWW-Authenticate realm SSRF, extended to cover the upload location
code path.

* remote: block SSRF via private-IP redirects in blob/manifest downloads

makeFetcher() created an http.Client with no CheckRedirect policy,
so http.Client.Do() would silently follow 302 redirects issued by a
malicious registry to private or link-local IP addresses during any
pull operation (manifest fetch, blob download).

Add checkRedirectSSRF() as the CheckRedirect handler on the fetcher
client. It rejects cross-host redirects whose destination hostname
is a private or link-local IP literal (loopback, RFC 1918,
link-local unicast/multicast, unspecified), mirroring the check
already applied to blob upload Location headers in the previous
commit. Same-host redirects are always permitted.

This is the download-path counterpart to the upload-path fix
introduced in the previous commit for nextLocation().

* remote: add TestCheckRedirectSSRF to cover fetcher SSRF protection

Add unit tests for checkRedirectSSRF in fetcher.go:
- Cross-host redirects to private/link-local/loopback IPs are rejected
- Same-host redirects (including loopback for local test registries) are allowed
- Public IP and DNS hostname redirects are allowed
- Early-exit paths (empty via, nil Response) are covered

* remote: fix goimports formatting in fetcher.go and fetcher_test.go

* remote: fix goimports formatting in write_test.go
iahsanGill added a commit to iahsanGill/go-containerregistry that referenced this pull request May 18, 2026
Fixes google#2258.

The realm-URL validation introduced in google#2243 rejects realms whose host
resolves to a private, loopback, or link-local IP. This is the right
default for the cross-host SSRF case (a malicious registry pointing
the token endpoint at 169.254.169.254 or a sister internal service),
but it breaks legitimate setups where a user explicitly targets a
private/loopback registry that returns a same-host token endpoint —
e.g. test suites that run an authenticated registry on 127.0.0.1, or
on-prem deployments that colocate the registry and its token server.

Add a same-host:port exception: if the realm URL host:port equals the
registry host:port the user is already talking to, skip the private/
link-local check. The realm is not crossing a trust boundary the user
did not already trust by passing the reference.

The match is strict (host AND port) so that "different port on the
same loopback host" attacks — e.g. a realm pointed at a local
database or metadata-service port — remain blocked.

Mirrors the same-host exception pattern already used by the blob
upload Location-header check in pkg/v1/remote/write.go.

Signed-off-by: iahsanGill <[email protected]>
Subserial pushed a commit that referenced this pull request May 18, 2026
Fixes #2258.

The realm-URL validation introduced in #2243 rejects realms whose host
resolves to a private, loopback, or link-local IP. This is the right
default for the cross-host SSRF case (a malicious registry pointing
the token endpoint at 169.254.169.254 or a sister internal service),
but it breaks legitimate setups where a user explicitly targets a
private/loopback registry that returns a same-host token endpoint —
e.g. test suites that run an authenticated registry on 127.0.0.1, or
on-prem deployments that colocate the registry and its token server.

Add a same-host:port exception: if the realm URL host:port equals the
registry host:port the user is already talking to, skip the private/
link-local check. The realm is not crossing a trust boundary the user
did not already trust by passing the reference.

The match is strict (host AND port) so that "different port on the
same loopback host" attacks — e.g. a realm pointed at a local
database or metadata-service port — remain blocked.

Mirrors the same-host exception pattern already used by the blob
upload Location-header check in pkg/v1/remote/write.go.

Signed-off-by: iahsanGill <[email protected]>
jimmidyson added a commit to mesosphere/mindthegap that referenced this pull request May 19, 2026
…223) (#1046)

## Summary

- Bump `github.com/google/go-containerregistry` v0.21.5 → v0.21.6 to
pick up
[google/go-containerregistry#2302](google/go-containerregistry#2302)
— transport: allow bearer realm at same host:port as registry.
- Fixes [NCN-114223](https://jira.nutanix.com/browse/NCN-114223):
`mindthegap push bundle` (and downstream `nkp push bundle`) regression
against on-prem registries that colocate the registry and bearer-token
endpoint on the same private IP. e.g. for an internal Harbor at
`https://10.162.182.23:5000/library` the push aborted with `invalid
realm in www-authenticate: realm host "10.162.182.23" is a private or
link-local address`.
- Add regression test
`TestPushDockerArchive_BearerAuthSameHostLoopbackRealm` in
`cmd/mindthegap/push/imagearchive/push_test.go` that reproduces the
exact NCN-114223 error against v0.21.5 and passes against v0.21.6.

## Background

The realm-URL validation introduced in
[go-containerregistry#2243](google/go-containerregistry#2243)
(shipped in v0.21.5) rejects realms whose host resolves to a private,
loopback, or link-local IP. This is the right default for the cross-host
SSRF case (a malicious registry pointing the token endpoint at
`169.254.169.254` or a sister internal service), but it broke legitimate
on-prem deployments that serve their own token endpoint at the same
host:port as the registry.
[#2258](google/go-containerregistry#2258)
tracked the discussion;
[#2302](google/go-containerregistry#2302)
implements the agreed fix: keep the cross-host SSRF block, but skip the
private-IP check when the realm URL host AND port match the registry
host:port.

## Transitive dependency changes

Pulled in by `go-containerregistry` v0.21.6's `go.mod` via MVS
resolution:

- `docker/cli` v29.4.0 → v29.4.3
- `moby/moby/api` v1.54.1 → v1.54.2
- `moby/moby/client` v0.4.0 → v0.4.1
- `docker/go-connections` v0.6.0 → v0.7.0
- `klauspost/compress` v1.18.5 → v1.18.6
- `golang.org/x/{crypto,mod,net,sys,term,text,tools}` — minor bumps

Dropped (v0.21.6 removed estargz support in
[go-containerregistry#2288](google/go-containerregistry#2288)):

- `containerd/stargz-snapshotter/estargz` (indirect)
- `vbatts/tar-split` (indirect)

## Test fixture update

`images/manifest_test.go` is updated for the unrelated OCI-spec
compliance change in
[go-containerregistry#2269](google/go-containerregistry#2269):
`mutate.AppendManifests` now sets the index entry `ArtifactType` to the
image's `Config.MediaType` when the image manifest does not itself set
`artifactType`. For the Docker schema2 fixture in
`TestManifestListForImage_RemoteImage` this becomes
`"application/vnd.docker.container.image.v1+json"`
(`types.DockerConfigJSON`).

## Test plan

- [x] `go test -count=1 ./...` passes (155 tests).
- [x] New `TestPushDockerArchive_BearerAuthSameHostLoopbackRealm` fails
on v0.21.5 with the exact NCN-114223 error (`invalid realm in
www-authenticate: realm host "127.0.0.1" is a private or link-local
address`) and passes on v0.21.6 — bisected to confirm it is not a
tautology.
- [x] `go build ./...` passes.
- [x] `golangci-lint run ./...` clean.
- [ ] Manual verification against an on-prem Harbor with realm host ==
registry host on an RFC1918 IP (e.g. the reproducer environment in
NCN-114223).

## Out of scope

The two pre-existing govulncheck stdlib findings (`GO-2026-4982`,
`GO-2026-4980`, `GO-2026-4971`, `GO-2026-4918` — all `go1.25.x` fixed in
`go1.25.10`) are unrelated to this change.
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.

3 participants