package sso import ( "context" "errors" "net" "net/http" "net/netip" "syscall" "time" ) // ErrForbiddenAddress is returned when an IdP resolves to an address the // client may not contact. var ErrForbiddenAddress = errors.New("sso: issuer resolves to a non-public address") var cgnat = netip.MustParsePrefix("100.64.0.0/10") // SafeHTTPClient returns a client for talking to customer-configured IdPs. // Unless allowPrivate is set it refuses to connect to loopback, private, // link-local and similar ranges. The check runs on the resolved address at // dial time, so DNS rebinding and redirects cannot bypass it. func SafeHTTPClient(allowPrivate bool) *http.Client { d := &net.Dialer{Timeout: 5 * time.Second} if !allowPrivate { d.Control = func(_, address string, _ syscall.RawConn) error { ap, err := netip.ParseAddrPort(address) if err != nil || !isPublic(ap.Addr()) { return ErrForbiddenAddress } return nil } } tr := http.DefaultTransport.(*http.Transport).Clone() tr.Proxy = nil tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { return d.DialContext(ctx, network, addr) } return &http.Client{Transport: tr, Timeout: 10 * time.Second} } func isPublic(a netip.Addr) bool { a = a.Unmap() return a.IsGlobalUnicast() && !a.IsPrivate() && !cgnat.Contains(a) }