diff --git a/pkg/network/client.go b/pkg/network/client.go index 2044873..be4d24e 100644 --- a/pkg/network/client.go +++ b/pkg/network/client.go @@ -6,8 +6,11 @@ import ( "context" "fmt" "io" + "net" "net/http" + "net/url" "sync" + "syscall" "time" "github.com/lukaszraczylo/gohoarder/pkg/errors" @@ -19,6 +22,7 @@ import ( // Client is an HTTP client with resilience features type Client struct { client *http.Client + hopClient *http.Client rateLimiter *rate.Limiter circuitBreaker *CircuitBreaker retryConfig RetryConfig @@ -34,6 +38,9 @@ type Config struct { RateLimit float64 RateBurst int MaxConnsPerHost int + // AllowPrivateRedirects lets a redirect to another host reach private, loopback or + // link-local addresses. Off by default; it exists for tests and private mirrors. + AllowPrivateRedirects bool } // RetryConfig holds retry configuration @@ -105,8 +112,19 @@ func NewClient(config Config) *Client { } httpClient := &http.Client{ - Timeout: config.Timeout, - Transport: transport, + Timeout: config.Timeout, + Transport: transport, + CheckRedirect: noAutoRedirect, + } + + hopTransport := transport.Clone() + if !config.AllowPrivateRedirects { + hopTransport.DialContext = (&net.Dialer{Timeout: 30 * time.Second, Control: refusePrivateAddress}).DialContext + } + hopClient := &http.Client{ + Timeout: config.Timeout, + Transport: hopTransport, + CheckRedirect: noAutoRedirect, } var rateLimiter *rate.Limiter @@ -140,6 +158,7 @@ func NewClient(config Config) *Client { return &Client{ client: httpClient, + hopClient: hopClient, rateLimiter: rateLimiter, circuitBreaker: cb, retryConfig: RetryConfig{ @@ -154,8 +173,15 @@ func NewClient(config Config) *Client { } // Get performs a GET request with resilience features -func (c *Client) Get(ctx context.Context, url string, headers map[string]string) (io.ReadCloser, int, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) +func (c *Client) Get(ctx context.Context, rawURL string, headers map[string]string) (io.ReadCloser, int, error) { + return c.GetWithRedirectCheck(ctx, rawURL, headers, nil) +} + +// GetWithRedirectCheck is Get with a policy that every redirect target must pass. +// Redirects are always capped, limited to http(s), and refused when they reach a +// private address on another host; check adds an allowlist on top. +func (c *Client) GetWithRedirectCheck(ctx context.Context, rawURL string, headers map[string]string, check RedirectCheck) (io.ReadCloser, int, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) if err != nil { return nil, 0, errors.Wrap(err, errors.ErrCodeUpstreamError, "failed to create request") } @@ -164,7 +190,7 @@ func (c *Client) Get(ctx context.Context, url string, headers map[string]string) req.Header.Set(key, value) } - resp, err := c.do(ctx, req) + resp, err := c.do(ctx, req, check) if err != nil { return nil, 0, err } @@ -173,7 +199,7 @@ func (c *Client) Get(ctx context.Context, url string, headers map[string]string) } // do executes an HTTP request with retries and circuit breaker -func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, error) { +func (c *Client) do(ctx context.Context, req *http.Request, check RedirectCheck) (*http.Response, error) { // Check circuit breaker if c.circuitBreaker != nil { if !c.circuitBreaker.AllowRequest() { @@ -226,7 +252,7 @@ func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, err Msg("Retrying request") } - resp, err := c.client.Do(req) + resp, err := c.send(req, check) if err != nil { lastErr = err continue @@ -353,3 +379,84 @@ func (cb *CircuitBreaker) GetState() CircuitBreakerState { defer cb.mu.RUnlock() return cb.state } + +// MaxRedirects caps the hops one request may follow. +const MaxRedirects = 10 + +// RedirectCheck vets a redirect target before it is fetched. +type RedirectCheck func(*url.URL) error + +var errRedirectNotAllowed = errors.New(errors.ErrCodeUpstreamError, "redirect refused") + +func noAutoRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + +// send performs req and follows redirects itself, so each hop is vetted and, once the +// host changes, dialed through the guard that refuses private addresses. +func (c *Client) send(req *http.Request, check RedirectCheck) (*http.Response, error) { + origin := req.URL.Host + cur := req + httpClient := c.client + for hop := 0; ; hop++ { + resp, err := httpClient.Do(cur) + if err != nil { + return nil, err + } + loc := resp.Header.Get("Location") + if !isRedirectStatus(resp.StatusCode) || loc == "" { + return resp, nil + } + _ = resp.Body.Close() // #nosec G104 -- Cleanup, error not critical + if hop >= MaxRedirects { + return nil, errors.Wrap(errRedirectNotAllowed, errors.ErrCodeUpstreamError, "too many redirects") + } + next, err := cur.URL.Parse(loc) + if err != nil { + return nil, errors.Wrap(err, errors.ErrCodeUpstreamError, "invalid redirect location") + } + if next.Scheme != "http" && next.Scheme != "https" { + return nil, errors.Wrap(errRedirectNotAllowed, errors.ErrCodeUpstreamError, "redirect to non-http scheme") + } + if check != nil { + if err := check(next); err != nil { + return nil, errors.Wrap(err, errors.ErrCodeUpstreamError, "redirect target not allowed") + } + } + clone := cur.Clone(cur.Context()) + clone.URL = next + clone.Host = "" + if next.Host != cur.URL.Host { + clone.Header.Del("Authorization") + clone.Header.Del("Cookie") + } + cur = clone + if next.Host != origin { + httpClient = c.hopClient + } + } +} + +func isRedirectStatus(code int) bool { + switch code { + case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, + http.StatusTemporaryRedirect, http.StatusPermanentRedirect: + return true + } + return false +} + +// carrierGradeNAT is 100.64.0.0/10, which net.IP.IsPrivate does not cover. +var carrierGradeNAT = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)} + +// refusePrivateAddress runs after DNS resolution, so a name cannot rebind to an internal address. +func refusePrivateAddress(_, address string, _ syscall.RawConn) error { + host, _, err := net.SplitHostPort(address) + if err != nil { + return err + } + ip := net.ParseIP(host) + if ip == nil || ip.IsLoopback() || ip.IsPrivate() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() || + ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast() || ip.IsMulticast() || carrierGradeNAT.Contains(ip) { + return fmt.Errorf("refusing to connect to non-public address %s", host) + } + return nil +} diff --git a/pkg/network/redirect_test.go b/pkg/network/redirect_test.go new file mode 100644 index 0000000..1ee90d9 --- /dev/null +++ b/pkg/network/redirect_test.go @@ -0,0 +1,147 @@ +package network_test + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/lukaszraczylo/gohoarder/pkg/network" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func redirectClient(allowPrivate bool) *network.Client { + return network.NewClient(network.Config{ + Timeout: 5 * time.Second, + MaxRetries: 1, + AllowPrivateRedirects: allowPrivate, + }) +} + +// hostPolicy allows only the listed hostnames (port ignored). +func hostPolicy(hosts ...string) func(*url.URL) error { + return func(u *url.URL) error { + for _, h := range hosts { + if u.Hostname() == h { + return nil + } + } + return fmt.Errorf("host %q not allowed", u.Hostname()) + } +} + +func okServer(hit *atomic.Int32) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hit.Add(1) + _, _ = w.Write([]byte("secret")) + })) +} + +func TestRedirectToDisallowedHostRefused(t *testing.T) { + var hit atomic.Int32 + target := okServer(&hit) + defer target.Close() + // Same loopback server under a different hostname: allowed host redirects to a disallowed one. + redirectTo := strings.Replace(target.URL, "127.0.0.1", "localhost", 1) + origin := httptest.NewServer(http.RedirectHandler(redirectTo, http.StatusFound)) + defer origin.Close() + + _, _, err := redirectClient(true).GetWithRedirectCheck(context.Background(), origin.URL, nil, hostPolicy("127.0.0.1")) + require.Error(t, err) + assert.Zero(t, hit.Load(), "disallowed hop must not be fetched") +} + +func TestRedirectToLoopbackRefused(t *testing.T) { + var hit atomic.Int32 + target := okServer(&hit) + defer target.Close() + // Allowed by name, but resolves to loopback on a different host:port than the origin. + origin := httptest.NewServer(http.RedirectHandler(strings.Replace(target.URL, "127.0.0.1", "localhost", 1), http.StatusFound)) + defer origin.Close() + + _, _, err := redirectClient(false).GetWithRedirectCheck(context.Background(), origin.URL, nil, hostPolicy("127.0.0.1", "localhost")) + require.Error(t, err) + assert.Zero(t, hit.Load(), "loopback hop must not be fetched") +} + +func TestRedirectToPrivateLiteralRefused(t *testing.T) { + for _, loc := range []string{"http://10.1.2.3/x", "http://169.254.169.254/latest/meta-data", "http://[::1]/x", "http://192.168.0.1/x"} { + origin := httptest.NewServer(http.RedirectHandler(loc, http.StatusFound)) + _, _, err := redirectClient(false).Get(context.Background(), origin.URL, nil) + origin.Close() + require.Error(t, err, loc) + } +} + +func TestRedirectAllowedToAllowedWorks(t *testing.T) { + var hit atomic.Int32 + target := okServer(&hit) + defer target.Close() + origin := httptest.NewServer(http.RedirectHandler(strings.Replace(target.URL, "127.0.0.1", "localhost", 1), http.StatusFound)) + defer origin.Close() + + body, status, err := redirectClient(true).GetWithRedirectCheck(context.Background(), origin.URL, nil, hostPolicy("127.0.0.1", "localhost")) + require.NoError(t, err) + defer func() { _ = body.Close() }() + data, _ := io.ReadAll(body) + assert.Equal(t, http.StatusOK, status) + assert.Equal(t, "secret", string(data)) +} + +func TestRedirectHopsCapped(t *testing.T) { + var hits atomic.Int32 + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + http.Redirect(w, r, srv.URL+"/loop", http.StatusFound) + })) + defer srv.Close() + + _, _, err := redirectClient(true).Get(context.Background(), srv.URL, nil) + require.Error(t, err) + assert.LessOrEqual(t, int(hits.Load()), 11) +} + +func TestRedirectToNonHTTPSchemeRefused(t *testing.T) { + origin := httptest.NewServer(http.RedirectHandler("file:///etc/passwd", http.StatusFound)) + defer origin.Close() + _, _, err := redirectClient(true).Get(context.Background(), origin.URL, nil) + require.Error(t, err) +} + +func TestRedirectDropsAuthorizationAcrossHosts(t *testing.T) { + var got atomic.Value + got.Store("unset") + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got.Store(r.Header.Get("Authorization")) + })) + defer target.Close() + origin := httptest.NewServer(http.RedirectHandler(strings.Replace(target.URL, "127.0.0.1", "localhost", 1), http.StatusFound)) + defer origin.Close() + + body, _, err := redirectClient(true).Get(context.Background(), origin.URL, map[string]string{"Authorization": "Bearer x"}) + require.NoError(t, err) + _ = body.Close() + assert.Equal(t, "", got.Load()) +} + +func TestSameHostRedirectToLoopbackStillWorks(t *testing.T) { + // A private index redirecting within itself is operator-trusted. + mux := http.NewServeMux() + mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/b", http.StatusFound) }) + mux.HandleFunc("/b", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }) + srv := httptest.NewServer(mux) + defer srv.Close() + + body, status, err := redirectClient(false).Get(context.Background(), srv.URL+"/a", nil) + require.NoError(t, err) + _ = body.Close() + assert.Equal(t, http.StatusOK, status) +} diff --git a/pkg/proxy/pypi/pypi.go b/pkg/proxy/pypi/pypi.go index 5ec7eca..70269b7 100644 --- a/pkg/proxy/pypi/pypi.go +++ b/pkg/proxy/pypi/pypi.go @@ -51,6 +51,16 @@ func isAllowedPyPIHost(host string, allowed []string) bool { return false } +// get fetches from upstream; every redirect hop must be on the allowlist, as for original_url. +func (h *Handler) get(ctx context.Context, rawURL string, headers map[string]string) (io.ReadCloser, int, error) { + return h.client.GetWithRedirectCheck(ctx, rawURL, headers, func(u *url.URL) error { + if !isAllowedPyPIHost(u.Host, h.allowedHosts) { + return fmt.Errorf("redirect host %q not on allowlist", u.Hostname()) + } + return nil + }) +} + // Handler implements the PyPI Simple API (PEP 503) type Handler struct { cache *cache.Manager @@ -130,7 +140,7 @@ func (h *Handler) handleIndex(ctx context.Context, w http.ResponseWriter, r *htt url := h.upstream + "/" entry, err := h.cache.Get(ctx, "pypi", "index", "latest", func(ctx context.Context) (*cache.FetchResult, error) { - body, statusCode, err := h.client.Get(ctx, url, nil) + body, statusCode, err := h.get(ctx, url, nil) if err != nil { return nil, err } @@ -178,7 +188,7 @@ func (h *Handler) handlePackagePage(ctx context.Context, w http.ResponseWriter, } entry, err := h.cache.Get(ctx, "pypi", packageName, cacheVersion, func(ctx context.Context) (*cache.FetchResult, error) { - body, statusCode, err := h.client.Get(ctx, url, upstreamHeaders) + body, statusCode, err := h.get(ctx, url, upstreamHeaders) if err != nil { return nil, err } @@ -323,7 +333,7 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter, headers["Authorization"] = credentials } - body, statusCode, err := h.client.Get(ctx, originalURL, headers) + body, statusCode, err := h.get(ctx, originalURL, headers) if err != nil { return nil, err } @@ -454,7 +464,7 @@ func (h *Handler) serveMetadataSidecar(ctx context.Context, w http.ResponseWrite if credentials != "" { headers["Authorization"] = credentials } - body, status, err := h.client.Get(ctx, upstreamURL, headers) + body, status, err := h.get(ctx, upstreamURL, headers) if err != nil { log.Error().Err(err).Str("url", upstreamURL).Msg("Failed to fetch PEP 658 metadata") http.Error(w, "Failed to fetch package metadata", http.StatusBadGateway) diff --git a/pkg/proxy/pypi/redirect_test.go b/pkg/proxy/pypi/redirect_test.go new file mode 100644 index 0000000..9d51a3d --- /dev/null +++ b/pkg/proxy/pypi/redirect_test.go @@ -0,0 +1,41 @@ +package pypi + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/lukaszraczylo/gohoarder/pkg/network" +) + +// A PEP 658 sidecar fetched from an allowed host must not follow a redirect off the allowlist. +func TestSidecarRedirectOffAllowlistRefused(t *testing.T) { + var hit atomic.Int32 + internal := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hit.Add(1) + _, _ = w.Write([]byte("internal-secret")) + })) + defer internal.Close() + allowed := httptest.NewServer(http.RedirectHandler(strings.Replace(internal.URL, "127.0.0.1", "localhost", 1)+"/example-1.0.0-py3-none-any.whl.metadata", http.StatusFound)) + defer allowed.Close() + + client := network.NewClient(network.Config{Timeout: 5 * time.Second, MaxRetries: 1, AllowPrivateRedirects: true}) + h := &Handler{client: client, allowedHosts: []string{"127.0.0.1"}} + + const path = "/example/example-1.0.0-py3-none-any.whl.metadata" + q := url.Values{"original_url": {allowed.URL + "/files/example-1.0.0-py3-none-any.whl"}} + req := httptest.NewRequest(http.MethodGet, path+"?"+q.Encode(), nil) + w := httptest.NewRecorder() + h.handlePackageFile(req.Context(), w, req, path) + + if w.Code != http.StatusBadGateway { + t.Errorf("code=%d want 502 body=%q", w.Code, w.Body.String()) + } + if hit.Load() != 0 || strings.Contains(w.Body.String(), "internal-secret") { + t.Errorf("redirect target was fetched (hits=%d)", hit.Load()) + } +}