transfer: support proxies on registry redirect targets (#19065)

Behind a proxy, defer redirect-target DNS to the proxy; without one, keep the resolve-and-pin path. Trust default-registry/CDN hostnames with no local DNS. Fix a nil CancelFunc crash in blobDownload.release.
This commit is contained in:
Patrick Devine authored and GitHub committed 2026-10-16 15:00:17 -07:00
1 parent d9b86018cb
commit 4d2e250164
5 files changed
+667 -88

No files matched your search

+40 -17
View File
@@ -240,21 +240,7 @@ func (b *blobDownload) run(ctx context.Context, requestURL *url.URL, opts *regis
newOpts := new(registryOptions)
*newOpts = *opts
newOpts.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) > 10 {
return errMaxRedirectsExceeded
}
// if the hostname is the same, allow the redirect
if req.URL.Hostname() == requestURL.Hostname() {
return nil
}
// stop at the first redirect that is not
// the same hostname as the original
// request.
return http.ErrUseLastResponse
}
newOpts.CheckRedirect = downloadDiscoveryRedirect(requestURL)
resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, nil, nil, newOpts)
if err != nil {
@@ -265,7 +251,10 @@ func (b *blobDownload) run(ctx context.Context, requestURL *url.URL, opts *regis
continue
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusTemporaryRedirect && resp.StatusCode != http.StatusOK {
switch resp.StatusCode {
case http.StatusOK, http.StatusMovedPermanently, http.StatusFound,
http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
default:
return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
}
loc, err := resp.Location()
@@ -341,6 +330,40 @@ func (b *blobDownload) run(ctx context.Context, requestURL *url.URL, opts *regis
return nil
}
// downloadDiscoveryRedirect follows only redirects within the original
// registry origin. A new scheme, host, or port must first pass the redirect
// target policy before the blob downloader makes another request.
func downloadDiscoveryRedirect(base *url.URL) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
if len(via) > 10 {
return errMaxRedirectsExceeded
}
if err := transfer.ValidateRedirectScheme(req.URL, base.String()); err != nil {
return err
}
if sameRegistryOrigin(req.URL, base) {
return nil
}
return http.ErrUseLastResponse
}
}
func sameRegistryOrigin(a, b *url.URL) bool {
if a == nil || b == nil || a.Scheme != b.Scheme || !strings.EqualFold(a.Hostname(), b.Hostname()) {
return false
}
port := func(u *url.URL) string {
if p := u.Port(); p != "" {
return p
}
if u.Scheme == "https" {
return "443"
}
return "80"
}
return port(a) == port(b)
}
func (b *blobDownload) downloadChunk(ctx context.Context, client *http.Client, requestURL *url.URL, w io.Writer, part *blobDownloadPart) error {
g, ctx := errgroup.WithContext(ctx)
attemptStarted := time.Now()
@@ -449,7 +472,7 @@ func (b *blobDownload) acquire() {
}
func (b *blobDownload) release() {
if b.references.Add(-1) == 0 {
if b.references.Add(-1) == 0 && b.CancelFunc != nil {
b.CancelFunc()
}
}
+79 -7
View File
@@ -28,12 +28,12 @@ func TestDownloadChunkRedirects(t *testing.T) {
wantErr string
wantHits int32
}{
{name: "public", location: "https://203.0.113.2/data", wantHits: 2},
{name: "public", location: "https://8.8.8.8/data", wantHits: 2},
{name: "private", location: "https://127.0.0.1/data", wantErr: "not allowed", wantHits: 1},
{name: "downgrade", location: "http://203.0.113.2/data", wantErr: "not allowed", wantHits: 1},
{name: "downgrade", location: "http://8.8.8.8/data", wantErr: "not allowed", wantHits: 1},
{name: "lookup", wantErr: "not allowed"},
{name: "insecure", insecure: true, wantHits: 2},
{name: "loop", location: "https://203.0.113.1/start", wantErr: "stopped after 10 redirects", wantHits: 10},
{name: "loop", location: "https://8.8.4.4/start", wantErr: "stopped after 10 redirects", wantHits: 10},
} {
t.Run(tc.name, func(t *testing.T) {
var hits atomic.Int32
@@ -53,18 +53,23 @@ func TestDownloadChunkRedirects(t *testing.T) {
}
client := transfer.NewRedirectClient("https://registry.example", tc.insecure)
t.Cleanup(client.CloseIdleConnections)
tr := client.Transport.(*http.Transport)
tr.TLSClientConfig = server.Client().Transport.(*http.Transport).TLSClientConfig.Clone()
tr := server.Client().Transport.(*http.Transport).Clone()
client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) {
if err := transfer.ValidateRedirectTarget(req.Context(), req.URL, "https://registry.example", tc.insecure); err != nil {
return nil, err
}
return tr.RoundTrip(req)
})
tr.TLSClientConfig.ServerName = "127.0.0.1"
dial := tr.DialContext
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// Route only the public fixture addresses to the test server.
if addr == "203.0.113.1:443" || addr == "203.0.113.2:443" || addr == "203.0.113.2:80" {
if addr == "8.8.4.4:443" || addr == "8.8.8.8:443" || addr == "8.8.8.8:80" {
return new(net.Dialer).DialContext(ctx, network, server.Listener.Addr().String())
}
return dial(ctx, network, addr)
}
requestURL, _ := url.Parse("https://203.0.113.1/start")
requestURL, _ := url.Parse("https://8.8.4.4/start")
if tc.name == "lookup" {
requestURL, _ = url.Parse(strings.Replace(server.URL, "127.0.0.1", "localhost", 1) + "/data")
}
@@ -88,6 +93,73 @@ func TestDownloadChunkRedirects(t *testing.T) {
}
}
func TestDownloadDiscoveryRedirectOrigin(t *testing.T) {
t.Run("same origin", func(t *testing.T) {
var hits atomic.Int32
registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
if r.URL.Path == "/start" {
http.Redirect(w, r, "/data", http.StatusTemporaryRedirect)
return
}
fmt.Fprint(w, "ok")
}))
defer registry.Close()
base, _ := url.Parse(registry.URL)
client := &http.Client{CheckRedirect: downloadDiscoveryRedirect(base)}
resp, err := client.Get(registry.URL + "/start")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK || hits.Load() != 2 {
t.Fatalf("same-origin redirect: status %d, hits %d", resp.StatusCode, hits.Load())
}
})
t.Run("different port", func(t *testing.T) {
var targetHits atomic.Int32
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
targetHits.Add(1)
}))
defer target.Close()
registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL+"/private", http.StatusFound)
}))
defer registry.Close()
base, _ := url.Parse(registry.URL)
client := &http.Client{CheckRedirect: downloadDiscoveryRedirect(base)}
resp, err := client.Get(registry.URL + "/start")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusFound || targetHits.Load() != 0 {
t.Fatalf("different-port redirect: status %d, target hits %d", resp.StatusCode, targetHits.Load())
}
})
t.Run("https downgrade", func(t *testing.T) {
var registryURL string
registry := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
loc := strings.Replace(registryURL, "https://", "http://", 1) + "/data"
http.Redirect(w, r, loc, http.StatusTemporaryRedirect)
}))
defer registry.Close()
registryURL = registry.URL
base, _ := url.Parse(registry.URL)
client := registry.Client()
client.CheckRedirect = downloadDiscoveryRedirect(base)
resp, err := client.Get(registry.URL + "/start")
if err == nil {
resp.Body.Close()
}
if err == nil || !strings.Contains(err.Error(), "not allowed") {
t.Fatalf("HTTPS downgrade was followed: %v", err)
}
})
}
func TestDownloadRedirect(t *testing.T) {
var hits atomic.Int32
cdn := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+242 -51
View File
@@ -8,18 +8,68 @@ import (
"net/http"
"net/url"
"strings"
"sync"
"time"
)
var errRedirectNotAllowed = errors.New("redirect target not allowed")
// blockedIPv4Nets are globally-unicast-but-not-public IPv4 ranges that
// net.IP's helpers don't classify: CGNAT (RFC 6598), which carries real
// internal services like Alibaba Cloud metadata (100.100.2.148), and the
// benchmarking block (RFC 2544).
var blockedIPv4Nets = []*net.IPNet{parseIPv4Net("100.64.0.0/10"), parseIPv4Net("198.18.0.0/15")}
const maxProxyTransports = 128
func parseIPv4Net(s string) *net.IPNet {
// lookupRedirectIPs is replaceable by tests to exercise proxy-only DNS.
var lookupRedirectIPs = net.DefaultResolver.LookupIP
func publicRedirectIPs(ctx context.Context, host string) ([]net.IP, error) {
if ip := net.ParseIP(host); ip != nil {
if !isPublicIP(ip) {
return nil, fmt.Errorf("%w: %s is not a public address", errRedirectNotAllowed, ip)
}
return []net.IP{ip}, nil
}
ips, err := lookupRedirectIPs(ctx, "ip", host)
if err != nil {
return nil, fmt.Errorf("%w: resolving %s: %w", errRedirectNotAllowed, host, err)
}
if len(ips) == 0 {
return nil, fmt.Errorf("%w: %s has no addresses", errRedirectNotAllowed, host)
}
for _, ip := range ips {
if !isPublicIP(ip) {
return nil, fmt.Errorf("%w: %s resolves to non-public %s", errRedirectNotAllowed, host, ip)
}
}
return ips, nil
}
// net.IP.IsGlobalUnicast includes special-use addresses that are not
// globally reachable. Keep the redirect allowlist conservative. See the
// IANA IPv4/IPv6 special-purpose registries.
var blockedIPv4Nets = []*net.IPNet{
parseIPNet("0.0.0.0/8"),
parseIPNet("100.64.0.0/10"), // shared address space, including cloud metadata
parseIPNet("192.0.0.0/24"), // protocol assignments
parseIPNet("192.0.2.0/24"), // documentation
parseIPNet("192.88.99.0/24"), // deprecated 6to4 relay
parseIPNet("198.18.0.0/15"), // benchmarking
parseIPNet("198.51.100.0/24"), // documentation
parseIPNet("203.0.113.0/24"), // documentation
parseIPNet("240.0.0.0/4"), // reserved
}
// Current IPv6 global unicast allocations are within 2000::/3. Deny the
// special-purpose ranges in that block too, including transition prefixes.
var (
publicIPv6Net = parseIPNet("2000::/3")
blockedIPv6Nets = []*net.IPNet{
parseIPNet("2001::/23"),
parseIPNet("2001:db8::/32"),
parseIPNet("2002::/16"),
parseIPNet("3ffe::/16"),
parseIPNet("3fff::/20"),
}
)
func parseIPNet(s string) *net.IPNet {
_, n, err := net.ParseCIDR(s)
if err != nil {
panic(err)
@@ -37,13 +87,23 @@ func isPublicIP(ip net.IP) bool {
ip.IsUnspecified() {
return false
}
// To4() unwraps 4-in-6 mapped addresses so mapped CGNAT is blocked too.
// To4() unwraps 4-in-6 mapped addresses so mapped special-use ranges
// are blocked too.
if v4 := ip.To4(); v4 != nil {
for _, n := range blockedIPv4Nets {
if n.Contains(v4) {
return false
}
}
return true
}
if !publicIPv6Net.Contains(ip) {
return false
}
for _, n := range blockedIPv6Nets {
if n.Contains(ip) {
return false
}
}
return true
}
@@ -69,44 +129,71 @@ func ValidateRedirectScheme(loc *url.URL, baseURL string) error {
return nil
}
// ValidateRedirectTarget rejects redirect targets that aren't public HTTPS
// endpoints, unless allowPrivate is set.
// allowedRedirectHosts are the hosts the default registry and our CDN
// actually redirect blobs to. A hostname redirect target matching one of
// these is trusted without a local DNS lookup, so proxied hosts with no
// external resolver still pull. Any other hostname still resolves locally
// and must be public.
var allowedRedirectHosts = []string{
"ollama.com",
"ollama.ai",
"hf.co",
"huggingface.co",
"cloudflarestorage.com",
}
func isAllowedRedirectHost(host string) bool {
for _, h := range allowedRedirectHosts {
if strings.EqualFold(host, h) || strings.HasSuffix(strings.ToLower(host), "."+h) {
return true
}
}
return false
}
// ValidateRedirectTarget checks a registry-supplied target. When a proxy
// carries the request, or the target is a default-registry host we redirect
// to anyway, name resolution is deferred — the proxy enforces its own access
// rules and no local DNS is needed. Otherwise the target must resolve
// locally to public addresses. Explicit private IP literals are always
// rejected unless allowPrivate is set.
func ValidateRedirectTarget(ctx context.Context, loc *url.URL, baseURL string, allowPrivate bool) error {
if loc == nil {
return fmt.Errorf("%w: missing Location", errRedirectNotAllowed)
}
if allowPrivate {
return nil
}
if err := ValidateRedirectScheme(loc, baseURL); err != nil {
return err
}
host := loc.Hostname()
if ip := net.ParseIP(host); ip != nil {
if !isPublicIP(ip) {
return fmt.Errorf("%w: %s is not a public address", errRedirectNotAllowed, ip)
}
if allowPrivate {
return nil
}
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
if err != nil {
return fmt.Errorf("%w: resolving %s: %w", errRedirectNotAllowed, host, err)
host := loc.Hostname()
if host == "" {
return fmt.Errorf("%w: missing host", errRedirectNotAllowed)
}
if len(ips) == 0 {
return fmt.Errorf("%w: %s has no addresses", errRedirectNotAllowed, host)
// An IP literal needs no resolution; check it directly.
if net.ParseIP(host) != nil {
_, err := publicRedirectIPs(ctx, host)
return err
}
for _, ip := range ips {
if !isPublicIP(ip) {
return fmt.Errorf("%w: %s resolves to non-public %s", errRedirectNotAllowed, host, ip)
}
// A hostname the default registry redirects to needs no local DNS.
if isAllowedRedirectHost(host) {
return nil
}
return nil
// Behind a proxy, the proxy resolves the name; defer to its rules.
if u, err := proxyFromEnvironment(&http.Request{URL: loc}); err != nil {
return err
} else if u != nil {
return nil
}
_, err := publicRedirectIPs(ctx, host)
return err
}
// checkedDialer resolves, validates, and dials a pinned IP so DNS rebinding
// checkedDialer resolves, validates, and dials a fixed IP so DNS rebinding
// can't swap a private address in after validation.
func checkedDialer(d *net.Dialer, allowPrivate bool) func(ctx context.Context, network, addr string) (net.Conn, error) {
dial := d.DialContext
return func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
@@ -132,7 +219,7 @@ func checkedDialer(d *net.Dialer, allowPrivate bool) func(ctx context.Context, n
return nil, fmt.Errorf("%w: %s is not a public address", errRedirectNotAllowed, ip)
}
conn, err := d.DialContext(ctx, network, net.JoinHostPort(dialHost, port))
conn, err := dial(ctx, network, net.JoinHostPort(dialHost, port))
if err != nil {
return nil, err
}
@@ -144,10 +231,13 @@ func checkedDialer(d *net.Dialer, allowPrivate bool) func(ctx context.Context, n
}
}
// proxyFromEnvironment is http.ProxyFromEnvironment; tests replace it.
var proxyFromEnvironment = http.ProxyFromEnvironment
// NewRedirectClient returns a client for download URLs supplied by a registry.
func NewRedirectClient(baseURL string, allowPrivate bool) *http.Client {
// Redirect destinations do not get the registry host's exemption.
client := checkedClient("", allowPrivate)
client := newCheckedClient(baseURL, allowPrivate, false)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
@@ -160,31 +250,132 @@ func NewRedirectClient(baseURL string, allowPrivate bool) *http.Client {
return client
}
// checkedClient returns an HTTP client using checkedDialer; the registry
// base host is exempt since the caller explicitly directed traffic at it.
// checkedClient exempts the exact registry origin selected by the caller.
func checkedClient(baseURL string, allowPrivate bool) *http.Client {
var baseHostname string
if b, err := url.Parse(baseURL); err == nil {
baseHostname = b.Hostname()
return newCheckedClient(baseURL, allowPrivate, true)
}
func newCheckedClient(baseURL string, allowPrivate, exemptBase bool) *http.Client {
var base *url.URL
if exemptBase {
base, _ = url.Parse(baseURL)
}
dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 3 * time.Minute}
rt := &checkedTransport{
baseURL: baseURL, base: base, allowPrivate: allowPrivate,
proxyTransports: make(map[proxyTransportKey]*http.Transport),
}
rt.direct = newTransferTransport(nil, func(ctx context.Context, network, addr string) (net.Conn, error) {
if base != nil && sameOriginAddr(base, addr) {
return dialer.DialContext(ctx, network, addr)
}
return checkedDialer(dialer, allowPrivate)(ctx, network, addr)
})
return &http.Client{
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
// Custom DialContext disables HTTP/2 auto-configuration;
// ForceAttemptHTTP2 opts back in.
ForceAttemptHTTP2: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
host, _, err := net.SplitHostPort(addr)
if err == nil && baseHostname != "" && strings.EqualFold(host, baseHostname) {
return new(net.Dialer).DialContext(ctx, network, addr)
}
return checkedDialer(&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 3 * time.Minute}, allowPrivate)(ctx, network, addr)
},
},
Transport: rt,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
func sameOriginAddr(base *url.URL, addr string) bool {
host, port, err := net.SplitHostPort(addr)
if err != nil || !strings.EqualFold(host, base.Hostname()) {
return false
}
basePort := base.Port()
if basePort == "" {
if base.Scheme == "https" {
basePort = "443"
} else {
basePort = "80"
}
}
return port == basePort
}
func sameOrigin(a, b *url.URL) bool {
if a == nil || b == nil || a.Scheme != b.Scheme {
return false
}
port := func(u *url.URL) string {
if p := u.Port(); p != "" {
return p
}
if u.Scheme == "https" {
return "443"
}
return "80"
}
return strings.EqualFold(a.Hostname(), b.Hostname()) && port(a) == port(b)
}
func newTransferTransport(proxy *url.URL, dial func(context.Context, string, string) (net.Conn, error)) *http.Transport {
return &http.Transport{
Proxy: http.ProxyURL(proxy), DialContext: dial,
MaxIdleConns: 100, MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second, ForceAttemptHTTP2: true,
}
}
// checkedTransport binds proxy selection and its dialer to one request. A
// shared mutable proxy address is unsafe when direct and proxied requests
// run concurrently.
type checkedTransport struct {
baseURL string
base *url.URL
allowPrivate bool
direct *http.Transport
mu sync.Mutex
proxyTransports map[proxyTransportKey]*http.Transport
}
type proxyTransportKey struct {
proxy string
}
func (t *checkedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if !sameOrigin(req.URL, t.base) {
if err := ValidateRedirectTarget(req.Context(), req.URL, t.baseURL, t.allowPrivate); err != nil {
return nil, err
}
}
proxy, err := proxyFromEnvironment(req)
if err != nil {
return nil, err
}
if proxy == nil {
return t.direct.RoundTrip(req)
}
key := proxyTransportKey{proxy: proxy.String()}
return t.proxyTransport(key, proxy).RoundTrip(req)
}
func (t *checkedTransport) proxyTransport(key proxyTransportKey, proxy *url.URL) *http.Transport {
t.mu.Lock()
defer t.mu.Unlock()
if tr := t.proxyTransports[key]; tr != nil {
return tr
}
if len(t.proxyTransports) >= maxProxyTransports {
for oldKey, old := range t.proxyTransports {
old.CloseIdleConnections()
delete(t.proxyTransports, oldKey)
break
}
}
d := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 3 * time.Minute}
tr := newTransferTransport(proxy, d.DialContext)
t.proxyTransports[key] = tr
return tr
}
func (t *checkedTransport) CloseIdleConnections() {
t.direct.CloseIdleConnections()
t.mu.Lock()
defer t.mu.Unlock()
for _, tr := range t.proxyTransports {
tr.CloseIdleConnections()
}
}
+292 -12
View File
@@ -2,8 +2,11 @@ package transfer
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
@@ -16,10 +19,10 @@ import (
"time"
)
// SSRF regression tests for CVE-2026-85180: a registry can answer a blob
// request with a redirect to an internal address. By default the transfer
// package must refuse to fetch it; AllowPrivateHosts opts out for trusted
// LAN/local registries.
// SSRF regression tests: a registry can answer a blob request with a
// redirect to an internal address. By default the transfer package must
// refuse to fetch it; AllowPrivateHosts opts out for trusted LAN/local
// registries.
func TestDownloadRedirectToPrivateHostDenied(t *testing.T) {
blob, _ := createTestBlob(t, t.TempDir(), 1024)
@@ -213,9 +216,9 @@ func TestCheckedClientExemptsBaseHost(t *testing.T) {
// otherwise a private registry without AllowPrivateHosts breaks on
// default ports (regression: dial addr carries ":443", baseHost didn't).
for _, addr := range []string{"127.0.0.1:443", "localhost:443"} {
tr := checkedClient("https://127.0.0.1", false).Transport.(*http.Transport)
tr := checkedClient("https://127.0.0.1", false).Transport.(*checkedTransport).direct
if addr == "localhost:443" {
tr = checkedClient("https://localhost", false).Transport.(*http.Transport)
tr = checkedClient("https://localhost", false).Transport.(*checkedTransport).direct
}
_, err := tr.DialContext(t.Context(), "tcp", addr)
if strings.Contains(fmt.Sprint(err), "not allowed") {
@@ -228,7 +231,7 @@ func TestCheckedClientExemptsBaseHost(t *testing.T) {
func TestValidateRedirectTarget(t *testing.T) {
ctx := context.Background()
okPublic, _ := url.Parse("https://203.0.113.10/blob")
okPublic, _ := url.Parse("https://8.8.8.8/blob")
httpsBase := "https://registry.example.com"
httpBase := "http://192.168.1.10:5000"
@@ -239,7 +242,7 @@ func TestValidateRedirectTarget(t *testing.T) {
allowPrivate bool
wantErr bool
}{
{"public https allowed", "https://203.0.113.10/blob", httpsBase, false, false},
{"public https allowed", "https://8.8.8.8/blob", httpsBase, false, false},
{"metadata denied", "http://169.254.169.254/latest/meta-data", httpsBase, false, true},
{"loopback denied", "http://127.0.0.1:11434/api/tags", httpsBase, false, true},
{"rfc1918 denied", "http://10.0.0.5/internal", httpsBase, false, true},
@@ -250,11 +253,11 @@ func TestValidateRedirectTarget(t *testing.T) {
{"ipv6 link-local denied", "http://[fe80::1]/x", httpsBase, false, true},
{"localhost hostname denied", "http://localhost/x", httpsBase, false, true},
{"bad scheme denied", "file:///etc/passwd", httpsBase, false, true},
{"https registry downgrade to http denied", "http://203.0.113.10/blob", httpsBase, false, true},
{"https registry downgrade to http denied", "http://8.8.8.8/blob", httpsBase, false, true},
{"unresolvable name fails closed", "https://no-such-host.invalid/blob", httpsBase, false, true},
{"http registry may redirect to public http", "http://203.0.113.10/blob", httpBase, false, false},
{"private allowed with opt-in", "http://192.168.1.20/cdn/blob", httpsBase, true, false},
{"metadata allowed with opt-in", "http://169.254.169.254/latest", httpsBase, true, false},
{"http registry may redirect to public http", "http://8.8.8.8/blob", httpBase, false, false},
{"private allowed with opt-in", "http://192.168.1.20/cdn/blob", httpBase, true, false},
{"metadata allowed with opt-in", "http://169.254.169.254/latest", httpBase, true, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -275,6 +278,35 @@ func TestValidateRedirectTarget(t *testing.T) {
}
}
func TestIsPublicIPRejectsSpecialUseRanges(t *testing.T) {
for _, tc := range []struct {
address string
public bool
}{
{"8.8.8.8", true},
{"2606:4700:4700::1111", true},
{"0.0.0.1", false},
{"192.0.0.8", false},
{"192.0.2.1", false},
{"198.51.100.1", false},
{"203.0.113.1", false},
{"240.0.0.1", false},
{"::ffff:0.0.0.1", false},
{"64:ff9b::a9fe:a9fe", false}, // NAT64 can translate to link-local IPv4
{"100::1", false},
{"2001::1", false},
{"2001:db8::1", false},
{"2002::1", false},
{"3fff::1", false},
} {
t.Run(tc.address, func(t *testing.T) {
if got := isPublicIP(net.ParseIP(tc.address)); got != tc.public {
t.Errorf("isPublicIP(%s) = %t, want %t", tc.address, got, tc.public)
}
})
}
}
// Same-host HTTPS→HTTP redirects must be rejected even though the host is
// unchanged — otherwise a registry can strip TLS and rebinding DNS steers
// the cleartext request at an internal address.
@@ -368,3 +400,251 @@ func TestValidateRedirectScheme(t *testing.T) {
})
}
}
// withProxy points proxyFromEnvironment at proxy for the duration of the test.
func withProxy(t *testing.T, proxy *url.URL) {
t.Helper()
orig := proxyFromEnvironment
proxyFromEnvironment = func(*http.Request) (*url.URL, error) { return proxy, nil }
t.Cleanup(func() { proxyFromEnvironment = orig })
}
func TestRedirectClientUsesProxy(t *testing.T) {
// Behind a proxy the CDN host is unreachable directly; the request
// must be handed to the proxy instead of dialed. .invalid never
// resolves locally, so success proves the request went via the proxy.
var gotHost atomic.Value
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotHost.Store(r.URL.Host)
fmt.Fprint(w, "blob")
}))
defer proxy.Close()
proxyURL, _ := url.Parse(proxy.URL)
withProxy(t, proxyURL)
client := NewRedirectClient("http://registry.example", false)
resp, err := client.Get("http://blobs.example.invalid/sha256-abc")
if err != nil {
t.Fatalf("download through proxy failed: %v", err)
}
defer resp.Body.Close()
if got := gotHost.Load(); got != "blobs.example.invalid" {
t.Errorf("proxy saw host %v, want blobs.example.invalid", got)
}
}
func TestConcurrentProxyAndDirectRequests(t *testing.T) {
var hits atomic.Int32
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
fmt.Fprint(w, "ok")
}))
defer proxy.Close()
proxyURL, _ := url.Parse(proxy.URL)
original := proxyFromEnvironment
proxyFromEnvironment = func(req *http.Request) (*url.URL, error) {
if req.URL.Hostname() == "cdn.example.invalid" {
return proxyURL, nil
}
return nil, nil
}
t.Cleanup(func() { proxyFromEnvironment = original })
client := checkedClient("http://registry.example", false)
defer client.CloseIdleConnections()
const requests = 32
errCh := make(chan error, requests*2)
for range requests {
go func() {
resp, err := client.Get("http://cdn.example.invalid/blob")
if err == nil {
resp.Body.Close()
}
errCh <- err
}()
go func() {
resp, err := client.Get(proxy.URL + "/private")
if resp != nil {
resp.Body.Close()
}
if !errors.Is(err, errRedirectNotAllowed) {
errCh <- fmt.Errorf("direct request to private proxy address: %v", err)
return
}
errCh <- nil
}()
}
for range requests * 2 {
if err := <-errCh; err != nil {
t.Fatal(err)
}
}
if got := hits.Load(); got != requests {
t.Fatalf("proxy received %d requests, want %d", got, requests)
}
}
func TestValidateRedirectTargetBehindProxy(t *testing.T) {
// When the proxy will carry the request, redirect validation must not
// consult local DNS at all: resolution outcomes are registry-influenced
// and must not be usable as a validation oracle. Targets that will be
// dialed directly keep the local resolution requirement.
unresolvable, _ := url.Parse("https://blobs.example.invalid/x")
private, _ := url.Parse("https://localhost/x")
// No proxy: unresolvable fails closed, private is rejected.
if err := ValidateRedirectTarget(t.Context(), unresolvable, "https://registry.example", false); err == nil {
t.Error("unresolvable target allowed without a proxy")
}
if err := ValidateRedirectTarget(t.Context(), private, "https://registry.example", false); err == nil {
t.Error("private target allowed without a proxy")
}
proxyURL, _ := url.Parse("http://127.0.0.1:3128")
withProxy(t, proxyURL)
// Proxy configured: an unresolvable name is deferred to the proxy, and
// an explicit private IP literal is still rejected — it needs no
// resolution, so the proxy changes nothing.
if err := ValidateRedirectTarget(t.Context(), unresolvable, "https://registry.example", false); err != nil {
t.Errorf("proxy-routed target rejected: %v", err)
}
privateIP, _ := url.Parse("https://169.254.169.254/latest/meta-data")
if err := ValidateRedirectTarget(t.Context(), privateIP, "https://registry.example", false); err == nil {
t.Error("private IP literal allowed behind a proxy")
}
}
func TestValidateRedirectTargetDefaultRegistryHostsSkipLocalDNS(t *testing.T) {
// The default registry and its CDN hostnames are trusted without a
// local DNS lookup, so a proxied (or DNS-less) host still pulls. This
// must not relax checks for any other hostname, nor for IP literals.
for _, raw := range []string{
"https://dd20bb891979d25aebc8bec07b2b3bbc.r2.cloudflarestorage.com/x",
"https://registry.ollama.com/x",
"https://ollama.com/x",
"https://cas-bridge.xethub.hf.co/x",
} {
u, _ := url.Parse(raw)
if err := ValidateRedirectTarget(t.Context(), u, "https://registry.ollama.com", false); err != nil {
t.Errorf("%s: unexpected rejection: %v", raw, err)
}
}
// A lookalike host that merely ends in the same string is not allowed.
lookalike, _ := url.Parse("https://evilregistryollama.com/x")
if err := ValidateRedirectTarget(t.Context(), lookalike, "https://registry.ollama.com", false); err == nil {
t.Error("lookalike host allowed without DNS resolution")
}
// An unrecognized hostname still fails closed with no local DNS answer.
other, _ := url.Parse("https://no-such-host.invalid/x")
if err := ValidateRedirectTarget(t.Context(), other, "https://registry.ollama.com", false); err == nil {
t.Error("unrecognized host allowed without DNS resolution")
}
}
// TestDownloadThroughProxyCONNECT verifies that behind a proxy, a registry
// 307 to an https CDN URL that cannot resolve locally still completes the
// pull: discovery redirect and blob bytes both traverse the proxy via CONNECT.
func TestDownloadThroughProxyCONNECT(t *testing.T) {
blob, data := createTestBlob(t, t.TempDir(), 1024)
cdn := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}))
defer cdn.Close()
// CONNECT proxy: tunnel to the real CDN listener, record what was asked;
// serve the http registry hop as a plain forward proxy.
var connectHost atomic.Value
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodConnect {
resp, err := http.DefaultTransport.RoundTrip(r)
if err != nil {
w.WriteHeader(http.StatusBadGateway)
return
}
defer resp.Body.Close()
for k := range resp.Header {
w.Header()[k] = resp.Header[k]
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
return
}
connectHost.Store(r.Host)
client, _, err := w.(http.Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
upstream, err := net.Dial("tcp", cdn.Listener.Addr().String())
if err != nil {
client.Close()
t.Error(err)
return
}
fmt.Fprint(client, "HTTP/1.1 200 Connection Established\r\n\r\n")
go func() { io.Copy(upstream, client); upstream.Close() }()
go func() { io.Copy(client, upstream); client.Close() }()
}))
defer proxy.Close()
proxyURL, _ := url.Parse(proxy.URL)
withProxy(t, proxyURL)
registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://cdn.example.com/"+digestToPath(blob.Digest), http.StatusTemporaryRedirect)
}))
defer registry.Close()
client := checkedClient(registry.URL, false)
defer client.CloseIdleConnections()
// Trust the CDN test cert on the cached proxy transport.
pool := x509.NewCertPool()
pool.AddCert(cdn.Certificate())
tr := client.Transport.(*checkedTransport).proxyTransport(proxyTransportKey{proxy: proxyURL.String()}, proxyURL)
tr.TLSClientConfig = &tls.Config{RootCAs: pool}
dest := t.TempDir()
if err := Download(t.Context(), DownloadOptions{Blobs: []Blob{blob}, BaseURL: registry.URL, DestDir: dest, Client: client}); err != nil {
t.Fatalf("Download through proxy: %v", err)
}
verifyBlob(t, dest, blob, data)
if connectHost.Load() != "cdn.example.com:443" {
t.Errorf("CONNECT = %v, want cdn.example.com:443", connectHost.Load())
}
}
func TestUploadPatchContinuationRejectsPrivateHost(t *testing.T) {
var privateHits atomic.Int32
private := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
privateHits.Add(1)
}))
defer private.Close()
registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Docker-Upload-Location", private.URL+"/next")
w.WriteHeader(http.StatusAccepted)
}))
defer registry.Close()
f, err := os.CreateTemp(t.TempDir(), "blob")
if err != nil {
t.Fatal(err)
}
defer f.Close()
if _, err := f.WriteString("blob"); err != nil {
t.Fatal(err)
}
session, _ := url.Parse(registry.URL + "/upload")
u := &uploader{
client: checkedClient(registry.URL, false), baseURL: registry.URL,
progress: newProgressTracker(4, nil), token: "secret",
}
defer u.client.CloseIdleConnections()
_, _, _, err = u.uploadOnePart(t.Context(), session, &uploadPart{size: 4}, f)
if !errors.Is(err, errRedirectNotAllowed) {
t.Fatalf("private continuation allowed: %v", err)
}
if privateHits.Load() != 0 {
t.Fatal("private endpoint received an upload request")
}
}
+14 -1
View File
@@ -661,10 +661,23 @@ func (u *uploader) uploadOnePart(ctx context.Context, sessionURL *url.URL, part
}
var next *url.URL
if loc != "" {
next, _ = url.Parse(loc)
var parseErr error
next, parseErr = url.Parse(loc)
if parseErr != nil {
return nil, nil, pr.bytes(), fmt.Errorf("patch part %d: invalid next URL: %w", part.n, parseErr)
}
if next != nil && !next.IsAbs() {
next = sessionURL.ResolveReference(next)
}
if err := ValidateRedirectScheme(next, u.baseURL); err != nil {
return nil, nil, pr.bytes(), err
}
base, _ := url.Parse(u.baseURL)
if !sameOrigin(next, base) {
if err := ValidateRedirectTarget(ctx, next, u.baseURL, u.allowPrivate); err != nil {
return nil, nil, pr.bytes(), err
}
}
}
switch {