Skip to content

Commit da61d86

Browse files
authored
transport: do not re-attach bearer token after cross-host redirect (#2349)
PR #2337 made bearerTransport.RoundTrip set the Authorization header unconditionally on the post-401 retry, bypassing the matchesHost guard. That guard exists to stop the credential being forwarded across an http.Client-level redirect to a different host. With it bypassed, a malicious or compromised registry can 302 a manifest/blob fetch to an attacker-controlled host, answer the follow-up request with a Bearer challenge, and harvest the operator's registry token: the client refreshes the token from the trusted realm and then sends it to the redirected host. Gate the re-attach on matchesHost so the refreshed token is only applied when the request is still talking to the registry we authenticated against; for a cross-host request fall back to sendRequest(), which omits the credential. This preserves the #2333 fix for same-host 401 retries (e.g. mid-session token expiry) while closing the credential leak. Add a regression test for the same-host retry and a test asserting the token is not leaked to a cross-host challenger.
1 parent 09fe1e5 commit da61d86

2 files changed

Lines changed: 80 additions & 26 deletions

File tree

‎pkg/v1/remote/transport/bearer.go‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -247,11 +247,18 @@ func (bt *bearerTransport) RoundTrip(in *http.Request) (*http.Response, error) {
247247
if err = bt.refresh(in.Context()); err != nil {
248248
return nil, err
249249
}
250-
// Apply the freshly fetched token directly rather than calling
251-
// sendRequest(), which only sets Authorization when in.URL.Host
252-
// matches bt.registry. When the request followed a cross-host
253-
// redirect the hosts differ and sendRequest() would omit the
254-
// header, causing an unnecessary second 401.
250+
// Re-attach the freshly fetched token, but only when the request is
251+
// still talking to the registry we authenticated against. matchesHost
252+
// guards against forwarding the Authorization header across an
253+
// http.Client-level redirect to a different host: a malicious or
254+
// compromised registry can 302 the request to an attacker-controlled
255+
// host, answer the follow-up with a Bearer challenge, and harvest the
256+
// token if we re-attach it unconditionally. For a cross-host request
257+
// fall back to sendRequest(), which omits the credential, rather than
258+
// leaking it to a host we never logged in to.
259+
if !matchesHost(bt.registry.RegistryStr(), in, bt.scheme) {
260+
return sendRequest()
261+
}
255262
bt.mx.RLock()
256263
tok := bt.bearer.RegistryToken
257264
bt.mx.RUnlock()

‎pkg/v1/remote/transport/bearer_test.go‎

Lines changed: 68 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -698,41 +698,36 @@ func TestValidateRealmURLSameHost(t *testing.T) {
698698
}
699699
}
700700

701-
// TestBearerTokenAppliedAfterCrossHostRedirect is a regression test for
702-
// https://github.com/google/go-containerregistry/issues/2333.
703-
//
704-
// When an HTTP redirect sends the request to a host that differs from
705-
// bt.registry, the sendRequest() closure omits the Authorization header
706-
// (its matchesHost guard returns false). Previously, the post-401 retry
707-
// also went through sendRequest(), so the freshly refreshed token was
708-
// never applied and the request failed with a second 401.
709-
//
710-
// The fix skips sendRequest() after a successful refresh and sets the
711-
// Authorization header directly before retrying.
712-
func TestBearerTokenAppliedAfterCrossHostRedirect(t *testing.T) {
701+
// TestBearerTokenReappliedOnSameHostChallenge is the regression test for
702+
// https://github.com/google/go-containerregistry/issues/2333: when the
703+
// registry we authenticated against answers with a 401 Bearer challenge
704+
// (e.g. token expiry mid-session), the freshly refreshed token must be
705+
// applied to the retry so it succeeds rather than failing with a second 401.
706+
func TestBearerTokenReappliedOnSameHostChallenge(t *testing.T) {
713707
const (
714708
staleToken = "stale-token"
715709
freshToken = "fresh-token"
716710
)
717711

718712
attempts := 0
719-
// registryServer simulates a registry reachable after a cross-host redirect.
720-
// Its host intentionally differs from bt.registry ("registry.example.com").
721713
registryServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
722714
attempts++
723715
if r.Header.Get("Authorization") == "Bearer "+freshToken {
724716
w.WriteHeader(http.StatusOK)
725717
return
726718
}
727-
w.Header().Set("WWW-Authenticate", `Bearer realm="https://token.example.com/token",service="registry.example.com"`)
719+
w.Header().Set("WWW-Authenticate", `Bearer realm="https://token.example.com/token",service="registry"`)
728720
w.WriteHeader(http.StatusUnauthorized)
729721
}))
730722
defer registryServer.Close()
731723

732-
// bt.registry is "registry.example.com", which does NOT match registryServer's host.
733-
// This replicates what bearerTransport sees after an http.Client-level redirect:
734-
// in.URL.Host is the redirected host, not bt.registry.
735-
registry, err := name.NewRegistry("registry.example.com", name.WeakValidation)
724+
// bt.registry IS the server's host, so matchesHost is true: this is the
725+
// registry we authenticated against, and re-attaching the token is safe.
726+
u, err := url.Parse(registryServer.URL)
727+
if err != nil {
728+
t.Fatal(err)
729+
}
730+
registry, err := name.NewRegistry(u.Host, name.WeakValidation)
736731
if err != nil {
737732
t.Fatal(err)
738733
}
@@ -746,7 +741,7 @@ func TestBearerTokenAppliedAfterCrossHostRedirect(t *testing.T) {
746741
registry: registry,
747742
realm: "https://token.example.com/token",
748743
scopes: []string{"repo:example/image:pull"},
749-
service: "registry.example.com",
744+
service: "registry",
750745
scheme: "http",
751746
}
752747

@@ -757,7 +752,7 @@ func TestBearerTokenAppliedAfterCrossHostRedirect(t *testing.T) {
757752
defer res.Body.Close()
758753

759754
if res.StatusCode != http.StatusOK {
760-
t.Errorf("got status %d, want %d: fresh bearer token was not applied on cross-host retry", res.StatusCode, http.StatusOK)
755+
t.Errorf("got status %d, want %d: fresh bearer token was not applied on same-host retry", res.StatusCode, http.StatusOK)
761756
}
762757
if got := bt.bearer.RegistryToken; got != freshToken {
763758
t.Errorf("bearer.RegistryToken = %q, want %q", got, freshToken)
@@ -766,3 +761,55 @@ func TestBearerTokenAppliedAfterCrossHostRedirect(t *testing.T) {
766761
t.Errorf("registry received %d request(s), want 2 (401 then 200)", attempts)
767762
}
768763
}
764+
765+
// TestBearerTokenNotLeakedOnCrossHostChallenge verifies that when a request
766+
// has been redirected to a host that differs from the registry we logged in
767+
// to, the refreshed token is NOT re-attached. A malicious or compromised
768+
// registry must not be able to 302 the request to an attacker host, answer
769+
// with a Bearer challenge, and harvest the operator's registry credential.
770+
func TestBearerTokenNotLeakedOnCrossHostChallenge(t *testing.T) {
771+
const (
772+
staleToken = "stale-token"
773+
freshToken = "fresh-token"
774+
)
775+
776+
var gotAuth string
777+
// attackerServer is NOT bt.registry. It issues a Bearer challenge and
778+
// records any Authorization header it receives.
779+
attackerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
780+
if a := r.Header.Get("Authorization"); a != "" {
781+
gotAuth = a
782+
w.WriteHeader(http.StatusOK)
783+
return
784+
}
785+
w.Header().Set("WWW-Authenticate", `Bearer realm="https://token.example.com/token",service="attacker"`)
786+
w.WriteHeader(http.StatusUnauthorized)
787+
}))
788+
defer attackerServer.Close()
789+
790+
registry, err := name.NewRegistry("registry.example.com", name.WeakValidation)
791+
if err != nil {
792+
t.Fatal(err)
793+
}
794+
795+
bt := &bearerTransport{
796+
inner: http.DefaultTransport,
797+
bearer: authn.AuthConfig{RegistryToken: staleToken},
798+
basic: &authn.Bearer{Token: freshToken},
799+
registry: registry, // does NOT match attackerServer's host
800+
realm: "https://token.example.com/token",
801+
scopes: []string{"repo:example/image:pull"},
802+
service: "registry.example.com",
803+
scheme: "http",
804+
}
805+
806+
res, err := (&http.Client{Transport: bt}).Get(attackerServer.URL + "/v2/example/image/manifests/latest")
807+
if err != nil {
808+
t.Fatalf("unexpected error: %v", err)
809+
}
810+
defer res.Body.Close()
811+
812+
if gotAuth != "" {
813+
t.Fatalf("credential leaked to cross-host challenger: Authorization=%q", gotAuth)
814+
}
815+
}

0 commit comments

Comments
 (0)