fixes GHSA-whjr-3j94-gw3c constrain external jwt signer JWKS fetching

- adds HardenedJwksResolver, a jwks.Resolver that fetches an external jwt signer's
  jwksEndpoint with an http/https-only scheme check, a total timeout and a redirect cap
- adds JwksFetchPolicy, gating a fetch on both the URL hostname and the address being
  connected to, applied to the first request and to every redirect hop
- hostname gate: deniedHostnames blocks, allowedHostnames is exclusive when set; entries
  are an exact hostname or a '*.suffix' wildcard that matches subdomains at any depth but
  never the suffix itself, normalized to lower case punycode without a trailing dot
- address gate: built-in blocked (metadata, link-local, link-local multicast,
  unspecified), then deniedIPs, then allowedIPs, then blockPrivateAddresses,
  first-match-wins with deny over allow
- keeps the gates independent, so neither can authorize what the other refuses; the
  address check runs in the dialer against the resolved address, so a hostname that
  resolves to a blocked address is refused
- adds the [edge.externalJwtSigners.jwksFetch] config section with compatible defaults:
  empty hostname lists, blockPrivateAddresses false, timeout 5s, maxRedirects 5
- takes IP lists as a flat address or a CIDR block, hostname lists as names only, and
  rejects an entry belonging to the other list at startup
- rejects a jwksEndpoint the policy refuses when an external jwt signer is created or
  updated, and logs an existing signer whose endpoint the configuration now refuses
  when the token issuer cache loads
- documents both gates, their deny-wins precedence, the accepted entry forms and the
  wildcard matching rules in etc/ctrl.with.edge.yml and CHANGELOG.md
This commit is contained in:
Andrew Martinez
2026-07-25 12:03:39 -04:00
committed by Paul Lorenz
parent 0db32f7c1f
commit f64b6879cf
9 changed files with 2147 additions and 12 deletions
+35 -9
View File
@@ -16,21 +16,47 @@
* [DNS Upstream Query Modes](#dns-upstream-query-modes) - choose how multiple DNS upstreams are queried: parallel fan-out (default) or serial fail-through
* [Controller Read Throughput Under Load](#controller-read-throughput-under-load) - a bbolt upgrade lifts a ceiling on concurrent read transactions that could stall a busy controller
* [Logging Now Uses slog with an Async Handler](#logging-now-uses-slog-with-an-async-handler) - Logging moves to Go's `log/slog` behind an asynchronous sink; output is unchanged by default, with new flags to tune buffering
* [Security Advisories](#security-advisories) - Addresses a router-to-router link identity-spoofing vulnerability, and includes the two control-plane certificate validation fixes first released in 2.0.2
* [Security Advisories](#security-advisories) - Eight security advisories, plus the two control-plane certificate validation fixes first released in 2.0.2
## Security Advisories
This release addresses a router-to-router link identity-spoofing vulnerability. It also includes the two
control-plane certificate and identity validation fixes first released in 2.0.2 and 1.6.18; anyone upgrading
from 2.0.1 or earlier is picking those up here for the first time. See the linked GitHub Security Advisories
for full details, impact, and affected versions.
This release addresses eight security advisories. It also includes the two control-plane certificate and
identity validation fixes first released in 2.0.2 and 1.6.18; anyone upgrading from 2.0.1 or earlier is
picking those up here for the first time. See the linked GitHub Security Advisories for full details, impact,
and affected versions.
* [GHSA-hhm9-wf63-g7qj](https://github.com/openziti/ziti/security/advisories/GHSA-hhm9-wf63-g7qj) (Medium) - When accepting an incoming router-to-router link, a router
verified the dialing router's identity against the whole presented certificate chain instead of the leaf
certificate whose key the TLS handshake proved. An attacker holding enrolled router credentials could
* [GHSA-q8g9-jc4c-jp6q](https://github.com/openziti/ziti/security/advisories/GHSA-q8g9-jc4c-jp6q) (High) - The controller buffered the entire body of every
inbound request before any authentication check and with no size cap, so an unauthenticated client could
exhaust controller memory, and crash it, by sending parallel large-body requests to endpoints such as
enrollment.
* [GHSA-j952-6x8x-jmj6](https://github.com/openziti/ziti/security/advisories/GHSA-j952-6x8x-jmj6) (High) - The unauthenticated legacy enrollment path buffered
the request body a second time, allocating twice the memory per request and roughly halving the bandwidth
needed to drive the controller out of memory. Amplifies GHSA-q8g9-jc4c-jp6q.
* [GHSA-hhm9-wf63-g7qj](https://github.com/openziti/ziti/security/advisories/GHSA-hhm9-wf63-g7qj) (Medium) - When accepting an incoming router-to-router link, a
router verified the dialing router's identity against the whole presented certificate chain instead of the
leaf certificate whose key the TLS handshake proved. An attacker holding enrolled router credentials could
present another router's certificate as filler and be admitted on a link under that router's identity,
letting it intercept, inject, drop, or strand the circuits routed over that link.
* [GHSA-7868-235p-7497](https://github.com/openziti/ziti/security/advisories/GHSA-7868-235p-7497) (Medium) - The controller did not validate the API session
token when creating a circuit via CreateCircuitV3, taking the dialing identity from a router-supplied
header instead. An attacker holding enrolled router credentials could create circuits on behalf of any
identity permitted to dial the service through that router, without that identity having authenticated,
yielding data-plane access under an impersonated identity. The same gap meant expired and revoked API
sessions were not caught at circuit creation.
* [GHSA-4h58-w989-xgg4](https://github.com/openziti/ziti/security/advisories/GHSA-4h58-w989-xgg4) (Medium) - The token-based enrollment endpoint skipped
audience and issuer validation when the request carried a `ziti-token-issuer-id` header, so an attacker
holding any unexpired JWT signed by a configured external JWT signer, even one minted for a different
audience, could enroll a new identity onto the network.
* [GHSA-6v5r-p2wr-q492](https://github.com/openziti/ziti/security/advisories/GHSA-6v5r-p2wr-q492) (Medium) - The current-api-session certificates endpoint
performed an unscoped list, so any authenticated user could read the API session certificates (subject
DNs, fingerprints, and full PEM chains) of all identities, not just their own.
* [GHSA-whjr-3j94-gw3c](https://github.com/openziti/ziti/security/advisories/GHSA-whjr-3j94-gw3c) (Medium) - A JWKS endpoint URL configured on an external JWT
signer was fetched server-side with no timeout, private-range blocking, or allowlist, letting a caller with
external-jwt-signer management access make the controller issue requests to arbitrary internal URLs,
including cloud metadata endpoints (SSRF).
* [GHSA-354c-gpg9-j988](https://github.com/openziti/ziti/security/advisories/GHSA-354c-gpg9-j988) (Low) - With promptOnWake or promptOnUnlock enabled on an MFA
posture check, the edge router dereferenced a nil wake/unlock timestamp while locally evaluating an
authorized client's dial or bind, panicking and crashing the router (data-plane denial of service).
* [GHSA-mrpr-756c-xm47](https://github.com/openziti/ziti/security/advisories/GHSA-mrpr-756c-xm47) (Critical) - Improper peer certificate validation on the controller
cluster mesh, router links, and metrics endpoint. TLS peer checks accepted a connection when any presented
certificate chained to the trusted CA while taking the peer identity from the leaf certificate, allowing a
+336
View File
@@ -37,6 +37,7 @@ import (
"github.com/openziti/ziti/v2/common"
"github.com/openziti/ziti/v2/controller/command"
"github.com/pkg/errors"
"golang.org/x/net/idna"
)
const (
@@ -72,6 +73,17 @@ const (
DefaultIdentityOnlineStatusUnknownTimeout = 5 * time.Minute
DefaultIdentityOnlineStatusSource = IdentityStatusSourceHybrid
// DefaultJwksFetchBlockPrivateAddresses leaves private and loopback addresses reachable by
// default so that deployments using an internal IdP keep working. Metadata and link-local
// addresses are blocked regardless of this setting.
DefaultJwksFetchBlockPrivateAddresses = false
// DefaultJwksFetchTimeout bounds the total time spent fetching a JWKS endpoint.
DefaultJwksFetchTimeout = 5 * time.Second
// DefaultJwksFetchMaxRedirects bounds how many redirects a JWKS fetch will follow.
DefaultJwksFetchMaxRedirects = 5
)
type Enrollment struct {
@@ -136,6 +148,67 @@ func (o *Oidc) MaxTokenDuration() time.Duration {
return common.MaxTokenDuration(o.RefreshTokenDuration, o.AccessTokenDuration, o.IdTokenDuration)
}
// ExternalJwtSigners holds settings that govern how the controller interacts with
// external JWT signers.
type ExternalJwtSigners struct {
JwksFetch JwksFetch
}
// JwksFetch controls the server-side fetch of an external JWT signer's jwksEndpoint.
// The endpoint URL is supplied by an operator, so the fetch is constrained to keep it
// from being pointed at addresses the controller can reach but a caller should not.
//
// A hop is fetched only if it passes two independent gates. Neither gate can authorize what
// the other refuses, and both are applied to the initial request and to every redirect.
//
// The host gate is applied to the URL's hostname:
//
// 1. DeniedHostnames - blocked
// 2. AllowedHostnames, when non-empty and the host does not match - blocked
// 3. otherwise - passes
//
// The address gate is applied to the resolved address being connected to, first-match-wins,
// deny before allow:
//
// 1. built-in blocked addresses (cloud metadata, link-local, link-local multicast,
// unspecified) - always blocked, AllowedIPs cannot override
// 2. DeniedIPs - blocked, AllowedIPs cannot override
// 3. AllowedIPs - allowed; a carve-out of tier 4 only
// 4. BlockPrivateAddresses and the address is private or loopback - blocked
// 5. everything else - allowed
type JwksFetch struct {
// BlockPrivateAddresses blocks private and loopback addresses (address gate tier 4).
// Defaults to false so deployments with an internal IdP keep working; tier 1 applies
// regardless.
BlockPrivateAddresses bool
// DeniedIPs are CIDRs that are always blocked (address gate tier 2), above
// AllowedIPs.
DeniedIPs []*net.IPNet
// AllowedIPs are CIDRs that carve an exception out of BlockPrivateAddresses
// (address gate tier 3). They do not override tier 1 or DeniedIPs.
AllowedIPs []*net.IPNet
// DeniedHostnames are normalized hostname patterns that are blocked (hostname gate tier 1). Host
// matching only ever narrows what may be fetched: it cannot authorize an address the
// address gate blocks, and a caller can still reach the same target under another name,
// so the address gate remains the boundary.
DeniedHostnames []string
// AllowedHostnames are normalized hostname patterns that, when non-empty, are the only hosts that
// may be fetched (hostname gate tier 2). Entries are an exact hostname (idp.example.com) or a
// wildcard suffix (*.example.com), which matches any subdomain but not the suffix itself.
AllowedHostnames []string
// Timeout bounds the total time spent on a single JWKS fetch, including redirects.
Timeout time.Duration
// MaxRedirects bounds how many redirects a JWKS fetch will follow. Every hop is
// address-checked. Zero disables redirects.
MaxRedirects int
}
type EdgeConfig struct {
Enabled bool
Api Api
@@ -149,6 +222,7 @@ type EdgeConfig struct {
caCerts []*x509.Certificate
caCertPool *x509.CertPool
DisablePostureChecks bool
ExternalJwtSigners ExternalJwtSigners
}
type HttpTimeouts struct {
@@ -182,10 +256,24 @@ type IdentityStatusConfig struct {
UnknownTimeout time.Duration
}
// DefaultJwksFetch returns the default JWKS fetch settings. The defaults are deliberately
// compatible with existing deployments: only the non-disableable built-in blocked addresses
// are refused.
func DefaultJwksFetch() JwksFetch {
return JwksFetch{
BlockPrivateAddresses: DefaultJwksFetchBlockPrivateAddresses,
Timeout: DefaultJwksFetchTimeout,
MaxRedirects: DefaultJwksFetchMaxRedirects,
}
}
func NewEdgeConfig() *EdgeConfig {
return &EdgeConfig{
Enabled: false,
caPems: bytes.NewBuffer(nil),
ExternalJwtSigners: ExternalJwtSigners{
JwksFetch: DefaultJwksFetch(),
},
}
}
@@ -703,6 +791,250 @@ func (c *EdgeConfig) loadIdentityStatusConfig(cfgmap map[interface{}]interface{}
return nil
}
// loadExternalJwtSignersSection loads [edge.externalJwtSigners]. Every value is optional;
// absent values keep the defaults from DefaultJwksFetch.
func (c *EdgeConfig) loadExternalJwtSignersSection(edgeConfigMap map[any]any) error {
c.ExternalJwtSigners.JwksFetch = DefaultJwksFetch()
value, found := edgeConfigMap["externalJwtSigners"]
if !found || value == nil {
return nil
}
extJwtSignersMap, ok := value.(map[any]any)
if !ok {
return errors.Errorf("invalid type %T for [edge.externalJwtSigners], must be a map", value)
}
value, found = extJwtSignersMap["jwksFetch"]
if !found || value == nil {
return nil
}
jwksFetchMap, ok := value.(map[any]any)
if !ok {
return errors.Errorf("invalid type %T for [edge.externalJwtSigners.jwksFetch], must be a map", value)
}
jwksFetch := &c.ExternalJwtSigners.JwksFetch
if val, found := jwksFetchMap["blockPrivateAddresses"]; found && val != nil {
switch typedVal := val.(type) {
case bool:
jwksFetch.BlockPrivateAddresses = typedVal
case string:
boolVal, err := strconv.ParseBool(typedVal)
if err != nil {
return errors.Errorf("invalid value %q for [edge.externalJwtSigners.jwksFetch.blockPrivateAddresses], must be a boolean", typedVal)
}
jwksFetch.BlockPrivateAddresses = boolVal
default:
return errors.Errorf("invalid type %T for [edge.externalJwtSigners.jwksFetch.blockPrivateAddresses], must be a boolean", val)
}
}
if val, found := jwksFetchMap["deniedIPs"]; found && val != nil {
addresses, err := parseCidrList(val, "edge.externalJwtSigners.jwksFetch.deniedIPs")
if err != nil {
return err
}
jwksFetch.DeniedIPs = addresses
}
if val, found := jwksFetchMap["allowedIPs"]; found && val != nil {
addresses, err := parseCidrList(val, "edge.externalJwtSigners.jwksFetch.allowedIPs")
if err != nil {
return err
}
jwksFetch.AllowedIPs = addresses
}
if val, found := jwksFetchMap["deniedHostnames"]; found && val != nil {
hosts, err := parseHostnameList(val, "edge.externalJwtSigners.jwksFetch.deniedHostnames")
if err != nil {
return err
}
jwksFetch.DeniedHostnames = hosts
}
if val, found := jwksFetchMap["allowedHostnames"]; found && val != nil {
hosts, err := parseHostnameList(val, "edge.externalJwtSigners.jwksFetch.allowedHostnames")
if err != nil {
return err
}
jwksFetch.AllowedHostnames = hosts
}
if val, found := jwksFetchMap["timeout"]; found && val != nil {
strVal, ok := val.(string)
if !ok {
return errors.Errorf("invalid type %T for [edge.externalJwtSigners.jwksFetch.timeout], must be a string duration", val)
}
durationVal, err := time.ParseDuration(strVal)
if err != nil {
return errors.Errorf("error parsing [edge.externalJwtSigners.jwksFetch.timeout], invalid duration string %s, cannot parse as duration (e.g. 5s): %v", strVal, err)
}
if durationVal <= 0 {
return errors.Errorf("invalid value %s for [edge.externalJwtSigners.jwksFetch.timeout], must be greater than zero", strVal)
}
jwksFetch.Timeout = durationVal
}
if val, found := jwksFetchMap["maxRedirects"]; found && val != nil {
intVal, ok := val.(int)
if !ok {
return errors.Errorf("invalid type %T for [edge.externalJwtSigners.jwksFetch.maxRedirects], must be an integer", val)
}
if intVal < 0 {
return errors.Errorf("invalid value %v for [edge.externalJwtSigners.jwksFetch.maxRedirects], must not be negative", intVal)
}
jwksFetch.MaxRedirects = intVal
}
return nil
}
// parseCidrList parses a list of CIDRs, accepting a bare IP address as a single address CIDR
// (/32 for IPv4, /128 for IPv6). Hostnames are rejected: the address check happens at dial
// time against the resolved IP, so a hostname entry could never be matched reliably.
func parseCidrList(value any, field string) ([]*net.IPNet, error) {
values, ok := value.([]any)
if !ok {
return nil, errors.Errorf("invalid type %T for [%s], must be a list of CIDRs", value, field)
}
var result []*net.IPNet
for _, entry := range values {
strVal, ok := entry.(string)
if !ok {
return nil, errors.Errorf("invalid type %T for an entry in [%s], must be a string CIDR", entry, field)
}
ipNet, err := parseCidrOrIp(strings.TrimSpace(strVal))
if err != nil {
return nil, errors.Errorf("invalid value %q in [%s]: %v", strVal, field, err)
}
result = append(result, ipNet)
}
return result, nil
}
// parseHostnameList parses a list of hostname patterns, returning them normalized for comparison
// against a URL's hostname.
func parseHostnameList(value any, field string) ([]string, error) {
values, ok := value.([]any)
if !ok {
return nil, errors.Errorf("invalid type %T for [%s], must be a list of hostnames", value, field)
}
var result []string
for _, entry := range values {
strVal, ok := entry.(string)
if !ok {
return nil, errors.Errorf("invalid type %T for an entry in [%s], must be a string hostname", entry, field)
}
pattern, err := parseHostnamePattern(strings.TrimSpace(strVal))
if err != nil {
return nil, errors.Errorf("invalid value %q in [%s]: %v", strVal, field, err)
}
result = append(result, pattern)
}
return result, nil
}
// parseHostnamePattern validates a host entry and returns it normalized. An entry is either an
// exact host (idp.example.com) or a wildcard suffix (*.example.com), which matches any
// subdomain of that suffix but not the suffix itself. IP addresses are rejected: matching an
// address by name comparison would not be an address check.
func parseHostnamePattern(value string) (string, error) {
if value == "" {
return "", errors.New("must not be empty")
}
host := strings.TrimPrefix(value, "*.")
isWildcard := host != value
if net.ParseIP(strings.Trim(host, "[]")) != nil {
return "", errors.New("must be a hostname, use deniedIPs or allowedIPs for IP addresses")
}
if host == "" {
return "", errors.New("must include a hostname after the leading \"*.\"")
}
if strings.ContainsAny(host, "*/:@ \t") {
return "", errors.New("must be a bare host name, without a scheme, port or path, and a wildcard is only supported as a leading \"*.\"")
}
normalized := NormalizeHostname(host)
if normalized == "" {
return "", errors.New("must be a valid host name")
}
if isWildcard {
return "*." + normalized, nil
}
return normalized, nil
}
// NormalizeHostname returns a host in the form used for comparison: lower-cased, without a
// trailing dot, and converted to punycode when it contains non-ASCII labels. Config entries
// and request hosts are both normalized this way so that they compare consistently.
func NormalizeHostname(host string) string {
host = strings.TrimSuffix(strings.TrimSpace(host), ".")
if ascii, err := idna.Lookup.ToASCII(host); err == nil {
host = ascii
}
return strings.ToLower(host)
}
// parseCidrOrIp parses a CIDR or a bare IP address into a *net.IPNet. A bare IP address
// becomes a single address CIDR.
func parseCidrOrIp(value string) (*net.IPNet, error) {
if _, ipNet, err := net.ParseCIDR(value); err == nil {
return ipNet, nil
}
if ip := net.ParseIP(value); ip != nil {
if ip4 := ip.To4(); ip4 != nil {
return &net.IPNet{IP: ip4, Mask: net.CIDRMask(32, 32)}, nil
}
return &net.IPNet{IP: ip.To16(), Mask: net.CIDRMask(128, 128)}, nil
}
return nil, errors.New("must be a CIDR (e.g. 10.0.0.0/8) or an IP address, hostnames are not supported")
}
func LoadEdgeConfigFromMap(configMap map[interface{}]interface{}) (*EdgeConfig, error) {
edgeConfig := NewEdgeConfig()
@@ -748,6 +1080,10 @@ func LoadEdgeConfigFromMap(configMap map[interface{}]interface{}) (*EdgeConfig,
return nil, err
}
if err = edgeConfig.loadExternalJwtSignersSection(edgeConfigMap); err != nil {
return nil, err
}
if v, ok := edgeConfigMap["disablePostureChecks"]; ok {
if boolVal, ok := v.(bool); ok {
edgeConfig.DisablePostureChecks = boolVal
+255
View File
@@ -362,6 +362,261 @@ func Test_CalculateCaPems(t *testing.T) {
}
func Test_loadExternalJwtSignersSection(t *testing.T) {
t.Run("an absent section yields defaults", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
req.NoError(c.loadExternalJwtSignersSection(map[any]any{}))
req.False(c.ExternalJwtSigners.JwksFetch.BlockPrivateAddresses)
req.Empty(c.ExternalJwtSigners.JwksFetch.DeniedIPs)
req.Empty(c.ExternalJwtSigners.JwksFetch.AllowedIPs)
req.Empty(c.ExternalJwtSigners.JwksFetch.DeniedHostnames)
req.Empty(c.ExternalJwtSigners.JwksFetch.AllowedHostnames)
req.Equal(DefaultJwksFetchTimeout, c.ExternalJwtSigners.JwksFetch.Timeout)
req.Equal(DefaultJwksFetchMaxRedirects, c.ExternalJwtSigners.JwksFetch.MaxRedirects)
})
t.Run("an absent jwksFetch sub-section yields defaults", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
req.NoError(c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{},
}))
req.False(c.ExternalJwtSigners.JwksFetch.BlockPrivateAddresses)
req.Equal(DefaultJwksFetchTimeout, c.ExternalJwtSigners.JwksFetch.Timeout)
req.Equal(DefaultJwksFetchMaxRedirects, c.ExternalJwtSigners.JwksFetch.MaxRedirects)
})
t.Run("a fully specified section is parsed", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
req.NoError(c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"blockPrivateAddresses": true,
"deniedIPs": []any{"10.0.0.0/8", "203.0.113.5"},
"allowedIPs": []any{"192.168.10.0/24", "fd00:1234::1"},
"timeout": "12s",
"maxRedirects": 2,
},
},
}))
jwksFetch := c.ExternalJwtSigners.JwksFetch
req.True(jwksFetch.BlockPrivateAddresses)
req.Equal(12*time.Second, jwksFetch.Timeout)
req.Equal(2, jwksFetch.MaxRedirects)
req.Len(jwksFetch.DeniedIPs, 2)
req.Equal("10.0.0.0/8", jwksFetch.DeniedIPs[0].String())
req.Equal("203.0.113.5/32", jwksFetch.DeniedIPs[1].String(), "a bare IPv4 address should be treated as a /32")
req.Len(jwksFetch.AllowedIPs, 2)
req.Equal("192.168.10.0/24", jwksFetch.AllowedIPs[0].String())
req.Equal("fd00:1234::1/128", jwksFetch.AllowedIPs[1].String(), "a bare IPv6 address should be treated as a /128")
})
t.Run("host lists are parsed and normalized", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
req.NoError(c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"deniedHostnames": []any{"Blocked.Example.COM", "internal.example.com."},
"allowedHostnames": []any{"idp.example.com", "*.idp.example.org"},
},
},
}))
jwksFetch := c.ExternalJwtSigners.JwksFetch
req.Equal([]string{"blocked.example.com", "internal.example.com"}, jwksFetch.DeniedHostnames,
"host entries should be lower-cased with any trailing dot removed")
req.Equal([]string{"idp.example.com", "*.idp.example.org"}, jwksFetch.AllowedHostnames)
})
t.Run("a host list entry that is an IP address is an error", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
err := c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"deniedHostnames": []any{"10.0.0.5"},
},
},
})
req.Error(err, "an IP address in a host list would be a name comparison, not an address check")
req.Contains(err.Error(), "deniedIPs")
})
t.Run("a host list entry with a scheme, port or path is an error", func(t *testing.T) {
entries := []string{"https://idp.example.com", "idp.example.com:443", "idp.example.com/jwks", "idp.*.example.com", "*.", ""}
for _, entry := range entries {
t.Run(entry, func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
err := c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"allowedHostnames": []any{entry},
},
},
})
req.Error(err)
req.Contains(err.Error(), "allowedHostnames")
})
}
})
t.Run("blockPrivateAddresses accepts a string boolean", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
req.NoError(c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"blockPrivateAddresses": "true",
},
},
}))
req.True(c.ExternalJwtSigners.JwksFetch.BlockPrivateAddresses)
})
t.Run("maxRedirects of zero is allowed and disables redirects", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
req.NoError(c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"maxRedirects": 0,
},
},
}))
req.Equal(0, c.ExternalJwtSigners.JwksFetch.MaxRedirects)
})
t.Run("an invalid CIDR is an error", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
err := c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"deniedIPs": []any{"not-an-address"},
},
},
})
req.Error(err)
req.Contains(err.Error(), "deniedIPs")
})
t.Run("a hostname entry is an error", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
err := c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"allowedIPs": []any{"idp.example.com"},
},
},
})
req.Error(err, "hostnames are not valid entries, they cannot be enforced at dial time")
req.Contains(err.Error(), "allowedIPs")
})
t.Run("a non-list address value is an error", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
err := c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"deniedIPs": "10.0.0.0/8",
},
},
})
req.Error(err)
})
t.Run("an invalid duration is an error", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
err := c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"timeout": "not-a-duration",
},
},
})
req.Error(err)
})
t.Run("a non-positive timeout is an error", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
err := c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"timeout": "0s",
},
},
})
req.Error(err, "an unbounded fetch is exactly what this section exists to prevent")
})
t.Run("a negative maxRedirects is an error", func(t *testing.T) {
req := require.New(t)
c := NewEdgeConfig()
err := c.loadExternalJwtSignersSection(map[any]any{
"externalJwtSigners": map[any]any{
"jwksFetch": map[any]any{
"maxRedirects": -1,
},
},
})
req.Error(err)
})
}
func newSelfSignedCert(commonName string, isCas bool) (*x509.Certificate, crypto.PrivateKey) {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
@@ -17,14 +17,18 @@
package model
import (
"github.com/openziti/ziti/v2/controller/storage/ast"
"github.com/openziti/ziti/v2/controller/storage/boltz"
"strings"
"github.com/openziti/foundation/v2/errorz"
"github.com/openziti/ziti/v2/common/pb/edge_cmd_pb"
"github.com/openziti/ziti/v2/controller/apierror"
"github.com/openziti/ziti/v2/controller/change"
"github.com/openziti/ziti/v2/controller/command"
"github.com/openziti/ziti/v2/controller/db"
"github.com/openziti/ziti/v2/controller/fields"
"github.com/openziti/ziti/v2/controller/models"
"github.com/openziti/ziti/v2/controller/storage/ast"
"github.com/openziti/ziti/v2/controller/storage/boltz"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
@@ -33,6 +37,7 @@ import (
func NewExternalJwtSignerManager(env Env) *ExternalJwtSignerManager {
manager := &ExternalJwtSignerManager{
baseEntityManager: newBaseEntityManager[*ExternalJwtSigner, *db.ExternalJwtSigner](env, env.GetStores().ExternalJwtSigner),
jwksFetchPolicy: NewJwksFetchPolicy(JwksFetchConfig(env)),
}
manager.impl = manager
@@ -43,6 +48,10 @@ func NewExternalJwtSignerManager(env Env) *ExternalJwtSignerManager {
type ExternalJwtSignerManager struct {
baseEntityManager[*ExternalJwtSigner, *db.ExternalJwtSigner]
// jwksFetchPolicy is used to reject a jwksEndpoint at create/update time that could never
// be fetched. The same policy governs the fetch itself.
jwksFetchPolicy *JwksFetchPolicy
}
func (self *ExternalJwtSignerManager) NewModelEntity() *ExternalJwtSigner {
@@ -50,6 +59,10 @@ func (self *ExternalJwtSignerManager) NewModelEntity() *ExternalJwtSigner {
}
func (self *ExternalJwtSignerManager) Create(entity *ExternalJwtSigner, ctx *change.Context) error {
if err := self.validateJwksEndpoint(entity); err != nil {
return err
}
return DispatchCreate[*ExternalJwtSigner](self, entity, ctx)
}
@@ -59,9 +72,29 @@ func (self *ExternalJwtSignerManager) ApplyCreate(cmd *command.CreateEntityComma
}
func (self *ExternalJwtSignerManager) Update(entity *ExternalJwtSigner, checker fields.UpdatedFields, ctx *change.Context) error {
if err := self.validateJwksEndpoint(entity); err != nil {
return err
}
return DispatchUpdate[*ExternalJwtSigner](self, entity, checker, ctx)
}
// validateJwksEndpoint rejects a jwksEndpoint that the configured jwks fetch policy could
// never fetch, so the operator finds out on create/update rather than on a failed fetch. An
// endpoint that passes here can still be refused at fetch time, which is where the
// authoritative check lives.
func (self *ExternalJwtSignerManager) validateJwksEndpoint(entity *ExternalJwtSigner) error {
if entity.JwksEndpoint == nil || strings.TrimSpace(*entity.JwksEndpoint) == "" {
return nil
}
if err := self.jwksFetchPolicy.ValidateEndpoint(*entity.JwksEndpoint); err != nil {
return apierror.NewBadRequestFieldError(*errorz.NewFieldError(err.Error(), db.FieldExternalJwtSignerJwksEndpoint, *entity.JwksEndpoint))
}
return nil
}
func (self *ExternalJwtSignerManager) ApplyUpdate(cmd *command.UpdateEntityCommand[*ExternalJwtSigner], ctx boltz.MutateContext) error {
return self.updateEntity(cmd.Entity, cmd.UpdatedFields, ctx)
}
+392
View File
@@ -0,0 +1,392 @@
/*
Copyright NetFoundry Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package model
import (
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"syscall"
"github.com/openziti/jwks"
"github.com/openziti/ziti/v2/controller/config"
"github.com/openziti/ziti/v2/controller/db"
)
// builtInBlockedCidrs are always refused for a JWKS fetch and cannot be re-enabled by
// configuration. They are the addresses that turn the controller's network position into a
// credential oracle, plus the addresses that have no meaning as an IdP endpoint.
var builtInBlockedCidrs = []string{
"169.254.0.0/16", // IPv4 link-local, includes cloud instance metadata (169.254.169.254) and ECS task metadata (169.254.170.2)
"fe80::/10", // IPv6 link-local
"fd00:ec2::254/128", // AWS instance metadata over IPv6, inside unique-local space
"224.0.0.0/24", // IPv4 link-local multicast
"ff02::/16", // IPv6 link-local multicast
"0.0.0.0/32", // IPv4 unspecified
"::/128", // IPv6 unspecified
}
// JwksFetchConfig returns the [edge.externalJwtSigners.jwksFetch] settings from the
// environment, falling back to the defaults when no edge configuration is present.
func JwksFetchConfig(env Env) config.JwksFetch {
if cfg := env.GetConfig(); cfg != nil && cfg.Edge != nil {
return cfg.Edge.ExternalJwtSigners.JwksFetch
}
return config.DefaultJwksFetch()
}
// JwksFetchPolicy decides whether the controller may fetch a given JWKS endpoint. The
// endpoint URL is operator-supplied, so without this the controller's network position would
// be reachable by whoever can write an external JWT signer.
//
// A hop is fetched only if it passes both gates, and both gates are applied to the initial
// request and to every redirect. Neither gate can authorize what the other refuses: host
// matching only ever narrows what may be fetched.
//
// CheckHostname is the hostname gate, applied to the URL's hostname:
//
// 1. deniedHostnames - blocked
// 2. allowedHostnames - when non-empty and the host does not match, blocked
// 3. anything else - passes
//
// CheckIP is the address gate, applied to the address being connected to, first-match-wins,
// deny before allow:
//
// 1. builtInBlockedCidrs - blocked, not overridable
// 2. deniedIPs - blocked, not overridable by allowedIPs
// 3. allowedIPs - allowed, a carve-out of tier 4 only
// 4. blockPrivateAddresses and the address is private or loopback - blocked
// 5. anything else - allowed
type JwksFetchPolicy struct {
blockPrivateAddresses bool
builtInBlocked []*net.IPNet
deniedIPs []*net.IPNet
allowedIPs []*net.IPNet
deniedHostnames []string
allowedHostnames []string
}
// NewJwksFetchPolicy returns a JwksFetchPolicy built from the [edge.externalJwtSigners.jwksFetch]
// configuration section.
func NewJwksFetchPolicy(cfg config.JwksFetch) *JwksFetchPolicy {
result := &JwksFetchPolicy{
blockPrivateAddresses: cfg.BlockPrivateAddresses,
deniedIPs: cfg.DeniedIPs,
allowedIPs: cfg.AllowedIPs,
deniedHostnames: cfg.DeniedHostnames,
allowedHostnames: cfg.AllowedHostnames,
}
for _, cidr := range builtInBlockedCidrs {
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
// builtInBlockedCidrs is a compile-time constant list, a parse failure is a bug
panic(fmt.Errorf("invalid built-in blocked CIDR %s: %w", cidr, err))
}
result.builtInBlocked = append(result.builtInBlocked, ipNet)
}
return result
}
// CheckHostname returns nil if the controller may fetch from the given URL hostname, and an
// error otherwise. It is applied to the initial endpoint and to every redirect hop.
//
// Hostname matching narrows only. A hostname that passes here is still subject to CheckIP, and
// a caller may be able to reach the same target under a different name, so this is a filter on
// top of the address gate rather than a boundary of its own.
func (self *JwksFetchPolicy) CheckHostname(hostname string) error {
normalized := config.NormalizeHostname(hostname)
if normalized == "" {
return fmt.Errorf("jwks endpoint url must include a hostname")
}
if matchesHostname(self.deniedHostnames, normalized) {
return fmt.Errorf("jwks endpoint hostname %s is not permitted, it matches [edge.externalJwtSigners.jwksFetch.deniedHostnames]", normalized)
}
if len(self.allowedHostnames) > 0 && !matchesHostname(self.allowedHostnames, normalized) {
return fmt.Errorf("jwks endpoint hostname %s is not permitted, [edge.externalJwtSigners.jwksFetch.allowedHostnames] is set and does not include it", normalized)
}
return nil
}
// matchesHostname reports whether a normalized hostname matches any of the given normalized
// patterns. A pattern is either an exact hostname, or a "*.suffix" wildcard that matches any
// subdomain of suffix at any depth but never suffix itself: "*.sub.host.com" matches
// "idp.sub.host.com" and "a.b.sub.host.com", but not "sub.host.com".
func matchesHostname(patterns []string, hostname string) bool {
for _, pattern := range patterns {
if suffix, isWildcard := strings.CutPrefix(pattern, "*."); isWildcard {
if strings.HasSuffix(hostname, "."+suffix) {
return true
}
continue
}
if hostname == pattern {
return true
}
}
return false
}
// CheckIP returns nil if the controller may connect to the given address for a JWKS fetch,
// and an error describing which tier refused it otherwise. An address that cannot be
// classified is refused.
func (self *JwksFetchPolicy) CheckIP(ip net.IP) error {
if ip == nil {
return fmt.Errorf("jwks endpoint address could not be parsed")
}
// classify IPv4 and IPv4-mapped IPv6 addresses identically
if ip4 := ip.To4(); ip4 != nil {
ip = ip4
}
if containsIP(self.builtInBlocked, ip) {
return fmt.Errorf("jwks endpoint address %s is not permitted, it is a metadata, link-local or unspecified address", ip)
}
if containsIP(self.deniedIPs, ip) {
return fmt.Errorf("jwks endpoint address %s is not permitted, it matches [edge.externalJwtSigners.jwksFetch.deniedIPs]", ip)
}
if containsIP(self.allowedIPs, ip) {
return nil
}
if self.blockPrivateAddresses && (ip.IsPrivate() || ip.IsLoopback()) {
return fmt.Errorf("jwks endpoint address %s is not permitted, private and loopback addresses are blocked by [edge.externalJwtSigners.jwksFetch.blockPrivateAddresses]", ip)
}
return nil
}
// ValidateEndpoint checks an operator-supplied jwksEndpoint URL at create/update time so an
// obviously unusable endpoint is reported immediately instead of failing later during a
// fetch. It rejects a scheme other than http/https, a missing host, and a host that is a
// literal blocked IP address.
//
// This is advisory: no name resolution happens here, so a hostname that resolves to a blocked
// address passes this check and is refused by the dialer at fetch time. The dial-time check
// remains the authoritative one.
func (self *JwksFetchPolicy) ValidateEndpoint(endpoint string) error {
target, err := url.Parse(strings.TrimSpace(endpoint))
if err != nil {
return fmt.Errorf("could not parse jwks endpoint url: %w", err)
}
if err = validateJwksEndpointScheme(target); err != nil {
return err
}
host := target.Hostname()
if err = self.CheckHostname(host); err != nil {
return err
}
if ip := net.ParseIP(host); ip != nil {
return self.CheckIP(ip)
}
return nil
}
// checkJwksEndpointAllowed returns an error when a signer's jwksEndpoint is one the given
// policy refuses. A signer with no jwksEndpoint, or a blank one, is not reported.
func checkJwksEndpointAllowed(policy *JwksFetchPolicy, signer *db.ExternalJwtSigner) error {
if signer.JwksEndpoint == nil || strings.TrimSpace(*signer.JwksEndpoint) == "" {
return nil
}
return policy.ValidateEndpoint(*signer.JwksEndpoint)
}
// CheckDialAddress applies CheckIP to a host:port address as it is about to be dialed. The
// address has already been resolved at that point, which is what makes the check
// rebinding-safe: the address that is connected to is the address that is checked.
func (self *JwksFetchPolicy) CheckDialAddress(address string) error {
host, _, err := net.SplitHostPort(address)
if err != nil {
return fmt.Errorf("could not parse jwks endpoint dial address %s: %w", address, err)
}
return self.CheckIP(net.ParseIP(host))
}
// containsIP reports whether any of the given networks contains the given address.
func containsIP(ipNets []*net.IPNet, ip net.IP) bool {
for _, ipNet := range ipNets {
if ipNet.Contains(ip) {
return true
}
}
return false
}
var _ jwks.Resolver = (*HardenedJwksResolver)(nil)
// HardenedJwksResolver fetches JWKS responses over HTTP(S) with the constraints an
// operator-supplied URL requires: a bounded total time, a bounded number of redirects, an
// http/https-only scheme, and a JwksFetchPolicy check of every address that is connected to.
//
// The address check is installed as the dialer's control function, so it is the single choke
// point for the first request and for every redirect hop: it runs after DNS resolution and
// before the connection is made, which is what a check of the URL's hostname cannot do.
type HardenedJwksResolver struct {
client *http.Client
policy *JwksFetchPolicy
}
// NewHardenedJwksResolver returns a HardenedJwksResolver configured from the
// [edge.externalJwtSigners.jwksFetch] configuration section.
func NewHardenedJwksResolver(cfg config.JwksFetch) *HardenedJwksResolver {
if cfg.Timeout <= 0 {
cfg.Timeout = config.DefaultJwksFetchTimeout
}
if cfg.MaxRedirects < 0 {
cfg.MaxRedirects = config.DefaultJwksFetchMaxRedirects
}
policy := NewJwksFetchPolicy(cfg)
dialer := &net.Dialer{
Timeout: cfg.Timeout,
Control: func(_ string, address string, _ syscall.RawConn) error {
return policy.CheckDialAddress(address)
},
}
transport := &http.Transport{
DialContext: dialer.DialContext,
TLSHandshakeTimeout: cfg.Timeout,
// JWKS fetches are infrequent, so take a fresh, policy-checked connection every time
// rather than reusing one
DisableKeepAlives: true,
}
maxRedirects := cfg.MaxRedirects
client := &http.Client{
Timeout: cfg.Timeout,
Transport: transport,
CheckRedirect: func(request *http.Request, via []*http.Request) error {
if len(via) > maxRedirects {
return fmt.Errorf("jwks endpoint exceeded the maximum of %d redirect(s)", maxRedirects)
}
if err := validateJwksEndpointScheme(request.URL); err != nil {
return err
}
// every hop is checked on its own, an allowed first hop does not carry over
return policy.CheckHostname(request.URL.Hostname())
},
}
return &HardenedJwksResolver{
client: client,
policy: policy,
}
}
// Get implements jwks.Resolver. It returns the parsed JWKS response and the raw response body.
func (self *HardenedJwksResolver) Get(endpoint string) (*jwks.Response, []byte, error) {
target, err := url.Parse(strings.TrimSpace(endpoint))
if err != nil {
return nil, nil, fmt.Errorf("could not parse jwks endpoint url: %w", err)
}
if err = validateJwksEndpointScheme(target); err != nil {
return nil, nil, err
}
if err = self.policy.CheckHostname(target.Hostname()); err != nil {
return nil, nil, err
}
request, err := http.NewRequest(http.MethodGet, target.String(), nil)
if err != nil {
return nil, nil, fmt.Errorf("could not create jwks endpoint request: %w", err)
}
request.Header.Set("accept", "application/json")
response, err := self.client.Do(request)
if err != nil {
return nil, nil, err
}
defer func() {
_ = response.Body.Close()
}()
if response.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("could not fetch JWKS, status code was not 200 OK, got %d", response.StatusCode)
}
contentType := strings.ToLower(strings.TrimSpace(strings.Split(response.Header.Get("content-type"), ";")[0]))
if contentType != "application/json" && contentType != "application/jwk-set+json" && contentType != "application/jwk+json" {
return nil, nil, fmt.Errorf("invalid content type %s, expected application/json", contentType)
}
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, nil, fmt.Errorf("could not read jwks response: %w", err)
}
jwksResponse := &jwks.Response{}
if err = json.Unmarshal(body, jwksResponse); err != nil {
return nil, nil, fmt.Errorf("could not parse jwks response: %w", err)
}
return jwksResponse, body, nil
}
// validateJwksEndpointScheme allows only http and https. Anything else either cannot be
// fetched or would let the URL scheme choose the transport.
func validateJwksEndpointScheme(target *url.URL) error {
switch strings.ToLower(target.Scheme) {
case "http", "https":
return nil
}
return fmt.Errorf("invalid jwks endpoint scheme %s, only http and https are supported", target.Scheme)
}
+848
View File
@@ -0,0 +1,848 @@
package model
import (
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/openziti/ziti/v2/controller/config"
"github.com/openziti/ziti/v2/controller/db"
"github.com/stretchr/testify/require"
)
func Test_JwksFetchPolicy_CheckIP(t *testing.T) {
t.Run("with default settings", func(t *testing.T) {
policy := NewJwksFetchPolicy(config.DefaultJwksFetch())
t.Run("built-in blocked addresses are blocked", func(t *testing.T) {
blocked := []string{
"169.254.169.254", // cloud instance metadata
"169.254.170.2", // ECS task metadata
"fd00:ec2::254", // AWS IMDS over IPv6
"169.254.10.10", // link-local
"fe80::1", // link-local
"224.0.0.1", // link-local multicast
"ff02::1", // link-local multicast
"0.0.0.0", // unspecified
"::", // unspecified
}
for _, address := range blocked {
t.Run(address, func(t *testing.T) {
req := require.New(t)
err := policy.CheckIP(net.ParseIP(address))
req.Error(err, "%s must be blocked by the built-in tier", address)
})
}
})
t.Run("private and loopback addresses are allowed, the default posture is compatible", func(t *testing.T) {
allowed := []string{"127.0.0.1", "::1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "fc00::1"}
for _, address := range allowed {
t.Run(address, func(t *testing.T) {
req := require.New(t)
req.NoError(policy.CheckIP(net.ParseIP(address)))
})
}
})
t.Run("a public address is allowed", func(t *testing.T) {
req := require.New(t)
req.NoError(policy.CheckIP(net.ParseIP("93.184.216.34")))
})
})
t.Run("with blockPrivateAddresses enabled", func(t *testing.T) {
jwksFetch := config.DefaultJwksFetch()
jwksFetch.BlockPrivateAddresses = true
policy := NewJwksFetchPolicy(jwksFetch)
t.Run("private and loopback addresses are blocked", func(t *testing.T) {
blocked := []string{"127.0.0.1", "::1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "fc00::1"}
for _, address := range blocked {
t.Run(address, func(t *testing.T) {
req := require.New(t)
req.Error(policy.CheckIP(net.ParseIP(address)))
})
}
})
t.Run("a public address is still allowed", func(t *testing.T) {
req := require.New(t)
req.NoError(policy.CheckIP(net.ParseIP("93.184.216.34")))
})
})
t.Run("deniedIPs blocks an otherwise allowed public address", func(t *testing.T) {
req := require.New(t)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.DeniedIPs = mustCidrs(t, "203.0.113.0/24")
policy := NewJwksFetchPolicy(jwksFetch)
req.Error(policy.CheckIP(net.ParseIP("203.0.113.5")))
req.NoError(policy.CheckIP(net.ParseIP("203.0.114.5")))
})
t.Run("allowedIPs carves an exception out of blockPrivateAddresses", func(t *testing.T) {
req := require.New(t)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.BlockPrivateAddresses = true
jwksFetch.AllowedIPs = mustCidrs(t, "10.1.0.0/16")
policy := NewJwksFetchPolicy(jwksFetch)
req.NoError(policy.CheckIP(net.ParseIP("10.1.2.3")), "the carve-out address must be reachable")
req.Error(policy.CheckIP(net.ParseIP("10.2.2.3")), "a private address outside the carve-out must stay blocked")
})
t.Run("allowedIPs cannot override the built-in blocked tier", func(t *testing.T) {
req := require.New(t)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.AllowedIPs = mustCidrs(t, "169.254.0.0/16", "fd00:ec2::/64")
policy := NewJwksFetchPolicy(jwksFetch)
req.Error(policy.CheckIP(net.ParseIP("169.254.169.254")), "the metadata service must never be reachable")
req.Error(policy.CheckIP(net.ParseIP("fd00:ec2::254")), "the IPv6 metadata service must never be reachable")
})
t.Run("allowedIPs cannot override deniedIPs", func(t *testing.T) {
req := require.New(t)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.DeniedIPs = mustCidrs(t, "10.0.0.0/8")
jwksFetch.AllowedIPs = mustCidrs(t, "10.1.2.3/32")
policy := NewJwksFetchPolicy(jwksFetch)
req.Error(policy.CheckIP(net.ParseIP("10.1.2.3")), "deny wins over allow")
})
t.Run("an IPv4-mapped IPv6 address is classified as its IPv4 address", func(t *testing.T) {
t.Run("a mapped metadata address is blocked", func(t *testing.T) {
req := require.New(t)
policy := NewJwksFetchPolicy(config.DefaultJwksFetch())
req.Error(policy.CheckIP(net.ParseIP("::ffff:169.254.169.254")))
})
t.Run("a mapped private address is blocked when blockPrivateAddresses is set", func(t *testing.T) {
req := require.New(t)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.BlockPrivateAddresses = true
policy := NewJwksFetchPolicy(jwksFetch)
req.Error(policy.CheckIP(net.ParseIP("::ffff:10.1.2.3")))
})
t.Run("a mapped address matches an IPv4 allowedIPs carve-out", func(t *testing.T) {
req := require.New(t)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.BlockPrivateAddresses = true
jwksFetch.AllowedIPs = mustCidrs(t, "10.1.0.0/16")
policy := NewJwksFetchPolicy(jwksFetch)
req.NoError(policy.CheckIP(net.ParseIP("::ffff:10.1.2.3")))
})
t.Run("a mapped address matches an IPv4 deniedIPs entry", func(t *testing.T) {
req := require.New(t)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.DeniedIPs = mustCidrs(t, "203.0.113.0/24")
policy := NewJwksFetchPolicy(jwksFetch)
req.Error(policy.CheckIP(net.ParseIP("::ffff:203.0.113.5")))
})
})
t.Run("an unparsable address is blocked", func(t *testing.T) {
req := require.New(t)
policy := NewJwksFetchPolicy(config.DefaultJwksFetch())
req.Error(policy.CheckIP(nil), "an address that could not be parsed must never be treated as allowed")
})
}
func Test_JwksFetchPolicy_CheckHostname(t *testing.T) {
t.Run("with no host lists configured every host passes", func(t *testing.T) {
req := require.New(t)
policy := NewJwksFetchPolicy(config.DefaultJwksFetch())
req.NoError(policy.CheckHostname("idp.example.com"))
req.NoError(policy.CheckHostname("10.0.0.5"))
})
t.Run("an empty host is blocked", func(t *testing.T) {
req := require.New(t)
policy := NewJwksFetchPolicy(config.DefaultJwksFetch())
req.Error(policy.CheckHostname(""))
})
t.Run("deniedHostnames blocks a matching host", func(t *testing.T) {
jwksFetch := config.DefaultJwksFetch()
jwksFetch.DeniedHostnames = []string{"blocked.example.com", "*.internal.example.com"}
policy := NewJwksFetchPolicy(jwksFetch)
t.Run("an exact match is blocked", func(t *testing.T) {
req := require.New(t)
req.Error(policy.CheckHostname("blocked.example.com"))
})
t.Run("a wildcard suffix match is blocked", func(t *testing.T) {
req := require.New(t)
req.Error(policy.CheckHostname("idp.internal.example.com"))
req.Error(policy.CheckHostname("deep.idp.internal.example.com"))
})
t.Run("the wildcard suffix itself is not matched", func(t *testing.T) {
req := require.New(t)
req.NoError(policy.CheckHostname("internal.example.com"), "*.internal.example.com covers subdomains only")
})
t.Run("a wildcard matches whole labels only", func(t *testing.T) {
req := require.New(t)
// xinternal.example.com ends with internal.example.com as a string, but the
// wildcard replaces a whole label, so it is a different host
req.NoError(policy.CheckHostname("xinternal.example.com"))
req.NoError(policy.CheckHostname("notinternal.example.com"))
})
t.Run("an unlisted host passes", func(t *testing.T) {
req := require.New(t)
req.NoError(policy.CheckHostname("idp.example.com"))
})
t.Run("matching is case insensitive and ignores a trailing dot", func(t *testing.T) {
req := require.New(t)
req.Error(policy.CheckHostname("BLOCKED.example.com"))
req.Error(policy.CheckHostname("blocked.example.com."))
})
})
t.Run("allowedHostnames is exclusive when set", func(t *testing.T) {
jwksFetch := config.DefaultJwksFetch()
jwksFetch.AllowedHostnames = []string{"idp.example.com", "*.idp.example.org"}
policy := NewJwksFetchPolicy(jwksFetch)
t.Run("a listed host passes", func(t *testing.T) {
req := require.New(t)
req.NoError(policy.CheckHostname("idp.example.com"))
req.NoError(policy.CheckHostname("eu.idp.example.org"))
})
t.Run("an unlisted host is blocked", func(t *testing.T) {
req := require.New(t)
req.Error(policy.CheckHostname("evil.example.com"))
})
t.Run("a literal IP host is blocked", func(t *testing.T) {
req := require.New(t)
req.Error(policy.CheckHostname("93.184.216.34"), "an allowedHostnames list can only be satisfied by a name")
})
})
t.Run("deniedHostnames wins over allowedHostnames", func(t *testing.T) {
req := require.New(t)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.DeniedHostnames = []string{"old.idp.example.com"}
jwksFetch.AllowedHostnames = []string{"*.idp.example.com"}
policy := NewJwksFetchPolicy(jwksFetch)
req.Error(policy.CheckHostname("old.idp.example.com"))
req.NoError(policy.CheckHostname("new.idp.example.com"))
})
t.Run("an allowed host does not authorize a blocked address", func(t *testing.T) {
req := require.New(t)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.AllowedHostnames = []string{"idp.example.com"}
policy := NewJwksFetchPolicy(jwksFetch)
req.NoError(policy.CheckHostname("idp.example.com"))
req.Error(policy.CheckIP(net.ParseIP("169.254.169.254")), "the hostname gate must never widen the address gate")
})
}
func Test_JwksFetchPolicy_ValidateEndpoint(t *testing.T) {
t.Run("with default settings", func(t *testing.T) {
policy := NewJwksFetchPolicy(config.DefaultJwksFetch())
t.Run("an http or https endpoint is accepted", func(t *testing.T) {
endpoints := []string{
"https://idp.example.com/.well-known/jwks.json",
"http://idp.example.com/.well-known/jwks.json",
"HTTPS://idp.example.com/jwks",
}
for _, endpoint := range endpoints {
t.Run(endpoint, func(t *testing.T) {
req := require.New(t)
req.NoError(policy.ValidateEndpoint(endpoint))
})
}
})
t.Run("a non-http scheme is rejected", func(t *testing.T) {
endpoints := []string{"file:///etc/passwd", "ftp://idp.example.com/jwks", "idp.example.com/jwks", ""}
for _, endpoint := range endpoints {
t.Run(endpoint, func(t *testing.T) {
req := require.New(t)
req.Error(policy.ValidateEndpoint(endpoint))
})
}
})
t.Run("an endpoint without a host is rejected", func(t *testing.T) {
req := require.New(t)
req.Error(policy.ValidateEndpoint("http:///jwks"))
})
t.Run("a literal metadata address is rejected", func(t *testing.T) {
endpoints := []string{
"http://169.254.169.254/latest/meta-data/",
"http://169.254.170.2/v2/credentials",
"http://[fd00:ec2::254]/latest/meta-data/",
"http://169.254.169.254:8080/jwks",
}
for _, endpoint := range endpoints {
t.Run(endpoint, func(t *testing.T) {
req := require.New(t)
req.Error(policy.ValidateEndpoint(endpoint))
})
}
})
t.Run("a literal private address is accepted, the default posture allows it", func(t *testing.T) {
req := require.New(t)
req.NoError(policy.ValidateEndpoint("https://10.1.2.3/jwks"))
})
})
t.Run("with blockPrivateAddresses enabled", func(t *testing.T) {
jwksFetch := config.DefaultJwksFetch()
jwksFetch.BlockPrivateAddresses = true
policy := NewJwksFetchPolicy(jwksFetch)
t.Run("a literal private address is rejected", func(t *testing.T) {
req := require.New(t)
req.Error(policy.ValidateEndpoint("https://10.1.2.3/jwks"))
})
t.Run("a hostname is accepted, the dial-time check remains authoritative", func(t *testing.T) {
req := require.New(t)
// no DNS resolution happens at create/update time, so a hostname that resolves to
// a blocked address is caught by the dialer instead
req.NoError(policy.ValidateEndpoint("https://localhost/jwks"))
})
t.Run("a literal private address in allowedIPs is accepted", func(t *testing.T) {
req := require.New(t)
carveOut := config.DefaultJwksFetch()
carveOut.BlockPrivateAddresses = true
carveOut.AllowedIPs = mustCidrs(t, "10.1.0.0/16")
req.NoError(NewJwksFetchPolicy(carveOut).ValidateEndpoint("https://10.1.2.3/jwks"))
})
})
t.Run("with host lists configured", func(t *testing.T) {
jwksFetch := config.DefaultJwksFetch()
jwksFetch.DeniedHostnames = []string{"old.idp.example.com"}
jwksFetch.AllowedHostnames = []string{"idp.example.com", "*.idp.example.org"}
policy := NewJwksFetchPolicy(jwksFetch)
t.Run("an allowed host is accepted", func(t *testing.T) {
req := require.New(t)
req.NoError(policy.ValidateEndpoint("https://idp.example.com/.well-known/jwks.json"))
req.NoError(policy.ValidateEndpoint("https://eu.idp.example.org/jwks"))
})
t.Run("a host outside allowedHostnames is rejected", func(t *testing.T) {
req := require.New(t)
req.Error(policy.ValidateEndpoint("https://other.example.com/jwks"))
})
t.Run("a denied host is rejected", func(t *testing.T) {
req := require.New(t)
req.Error(policy.ValidateEndpoint("https://old.idp.example.com/jwks"))
})
})
}
func Test_checkJwksEndpointAllowed(t *testing.T) {
jwksFetch := config.DefaultJwksFetch()
jwksFetch.AllowedHostnames = []string{"idp.example.com"}
policy := NewJwksFetchPolicy(jwksFetch)
t.Run("a signer without a jwks endpoint is not reported", func(t *testing.T) {
req := require.New(t)
req.NoError(checkJwksEndpointAllowed(policy, &db.ExternalJwtSigner{}))
})
t.Run("a signer with a blank jwks endpoint is not reported", func(t *testing.T) {
req := require.New(t)
endpoint := " "
req.NoError(checkJwksEndpointAllowed(policy, &db.ExternalJwtSigner{JwksEndpoint: &endpoint}))
})
t.Run("a signer with an allowed jwks endpoint is not reported", func(t *testing.T) {
req := require.New(t)
endpoint := "https://idp.example.com/jwks"
req.NoError(checkJwksEndpointAllowed(policy, &db.ExternalJwtSigner{JwksEndpoint: &endpoint}))
})
t.Run("a signer whose jwks endpoint the configuration now refuses is reported", func(t *testing.T) {
req := require.New(t)
// the signer was created before the host list was set, so it is orphaned by the
// current configuration and the operator needs to know at startup
endpoint := "https://old-idp.example.com/jwks"
err := checkJwksEndpointAllowed(policy, &db.ExternalJwtSigner{JwksEndpoint: &endpoint})
req.Error(err)
req.Contains(err.Error(), "allowedHostnames")
})
t.Run("a signer whose jwks endpoint is a blocked address is reported", func(t *testing.T) {
req := require.New(t)
endpoint := "http://169.254.169.254/latest/meta-data/"
req.Error(checkJwksEndpointAllowed(NewJwksFetchPolicy(config.DefaultJwksFetch()),
&db.ExternalJwtSigner{JwksEndpoint: &endpoint}))
})
}
func Test_HardenedJwksResolver_Get(t *testing.T) {
const jwksBody = `{"keys":[{"kty":"RSA","kid":"test-kid","n":"AQAB","e":"AQAB"}]}`
t.Run("a valid JWKS endpoint resolves", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
resolver := NewHardenedJwksResolver(config.DefaultJwksFetch())
response, body, err := resolver.Get(server.URL + "/jwks")
req.NoError(err)
req.Len(response.Keys, 1)
req.Equal("test-kid", response.Keys[0].KeyId)
req.Equal(jwksBody, string(body))
})
t.Run("a blocked address is refused without contacting the endpoint", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.BlockPrivateAddresses = true
resolver := NewHardenedJwksResolver(jwksFetch)
_, _, err := resolver.Get(server.URL + "/jwks")
req.Error(err)
req.Contains(err.Error(), "is not permitted")
req.Zero(server.requestCount(), "the request must be stopped before it reaches the endpoint")
})
t.Run("a hostname that resolves to a blocked address is refused at dial time", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
// the URL host is a name, so only the resolved address can be checked - this is the
// DNS rebinding case, and it is why enforcement lives in the dialer
endpoint, err := server.urlWithHost("localhost")
req.NoError(err)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.BlockPrivateAddresses = true
resolver := NewHardenedJwksResolver(jwksFetch)
_, _, err = resolver.Get(endpoint)
req.Error(err)
req.Contains(err.Error(), "is not permitted")
req.Zero(server.requestCount(), "the request must be stopped before it reaches the endpoint")
})
t.Run("a redirect to a blocked address is refused", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
resolver := NewHardenedJwksResolver(config.DefaultJwksFetch())
_, _, err := resolver.Get(server.URL + "/redirect-to-metadata")
req.Error(err, "the metadata address must be blocked on a redirect hop, not just on the first hop")
req.Contains(err.Error(), "is not permitted", "the redirect hop must be refused by the address policy")
})
t.Run("a host that is not in allowedHostnames is refused without contacting the endpoint", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
endpoint, err := server.urlWithHost("localhost")
req.NoError(err)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.AllowedHostnames = []string{"idp.example.com"}
resolver := NewHardenedJwksResolver(jwksFetch)
_, _, err = resolver.Get(endpoint)
req.Error(err)
req.Contains(err.Error(), "allowedHostnames")
req.Zero(server.requestCount(), "the request must be stopped before it reaches the endpoint")
})
t.Run("a host in deniedHostnames is refused without contacting the endpoint", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
endpoint, err := server.urlWithHost("localhost")
req.NoError(err)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.DeniedHostnames = []string{"localhost"}
resolver := NewHardenedJwksResolver(jwksFetch)
_, _, err = resolver.Get(endpoint)
req.Error(err)
req.Contains(err.Error(), "deniedHostnames")
req.Zero(server.requestCount())
})
t.Run("a host in allowedHostnames is fetched", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
endpoint, err := server.urlWithHost("localhost")
req.NoError(err)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.AllowedHostnames = []string{"localhost"}
resolver := NewHardenedJwksResolver(jwksFetch)
response, _, err := resolver.Get(endpoint)
req.NoError(err)
req.Len(response.Keys, 1)
})
t.Run("a redirect to a host that is not in allowedHostnames is refused", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
endpoint, err := server.urlWithHost("localhost")
req.NoError(err)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.AllowedHostnames = []string{"localhost"}
resolver := NewHardenedJwksResolver(jwksFetch)
// the first hop is an allowed host, the redirect target is not - each hop is checked
// on its own
_, _, err = resolver.Get(strings.Replace(endpoint, "/jwks", "/redirect-to-unlisted-host", 1))
req.Error(err)
req.Contains(err.Error(), "allowedHostnames")
})
t.Run("a redirect within the cap is followed", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
resolver := NewHardenedJwksResolver(config.DefaultJwksFetch())
response, _, err := resolver.Get(server.URL + "/redirect-to-jwks")
req.NoError(err)
req.Len(response.Keys, 1)
})
t.Run("exceeding maxRedirects is an error", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.MaxRedirects = 2
resolver := NewHardenedJwksResolver(jwksFetch)
_, _, err := resolver.Get(server.URL + "/redirect-loop")
req.Error(err)
req.Contains(err.Error(), "redirect")
})
t.Run("maxRedirects of zero refuses to follow any redirect", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.MaxRedirects = 0
resolver := NewHardenedJwksResolver(jwksFetch)
_, _, err := resolver.Get(server.URL + "/redirect-to-jwks")
req.Error(err)
req.Contains(err.Error(), "redirect")
})
t.Run("a slow endpoint is cut off at the timeout", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
jwksFetch := config.DefaultJwksFetch()
jwksFetch.Timeout = 100 * time.Millisecond
resolver := NewHardenedJwksResolver(jwksFetch)
start := time.Now()
_, _, err := resolver.Get(server.URL + "/hang")
elapsed := time.Since(start)
req.Error(err)
req.Less(elapsed, 10*time.Second, "the fetch must be bounded by the configured timeout")
})
t.Run("a non-http scheme is refused", func(t *testing.T) {
endpoints := []string{
"file:///etc/passwd",
"ftp://example.com/jwks",
"gopher://example.com:70/jwks",
"/no/scheme/at/all",
}
for _, endpoint := range endpoints {
t.Run(endpoint, func(t *testing.T) {
req := require.New(t)
resolver := NewHardenedJwksResolver(config.DefaultJwksFetch())
_, _, err := resolver.Get(endpoint)
req.Error(err)
})
}
})
t.Run("an unparsable url is refused", func(t *testing.T) {
req := require.New(t)
resolver := NewHardenedJwksResolver(config.DefaultJwksFetch())
_, _, err := resolver.Get("http://[::1")
req.Error(err)
})
t.Run("a non-200 status is an error", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
resolver := NewHardenedJwksResolver(config.DefaultJwksFetch())
_, _, err := resolver.Get(server.URL + "/not-found")
req.Error(err)
})
t.Run("a non-json content type is an error", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
resolver := NewHardenedJwksResolver(config.DefaultJwksFetch())
_, _, err := resolver.Get(server.URL + "/html")
req.Error(err)
})
t.Run("a body that is not a JWKS response is an error", func(t *testing.T) {
req := require.New(t)
server := newTestJwksServer(t, jwksBody)
resolver := NewHardenedJwksResolver(config.DefaultJwksFetch())
_, _, err := resolver.Get(server.URL + "/not-json")
req.Error(err)
})
}
// testJwksServer is a local endpoint that serves the routes the resolver tests exercise and
// counts the requests that reach it.
type testJwksServer struct {
*httptest.Server
requests atomic.Int32
}
// requestCount returns how many requests reached the server.
func (self *testJwksServer) requestCount() int {
return int(self.requests.Load())
}
// urlWithHost returns the server's URL with its host replaced, keeping the port.
func (self *testJwksServer) urlWithHost(host string) (string, error) {
parsed, err := url.Parse(self.URL)
if err != nil {
return "", err
}
parsed.Host = net.JoinHostPort(host, parsed.Port())
return parsed.String() + "/jwks", nil
}
// newTestJwksServer starts a JWKS endpoint for the duration of the test.
func newTestJwksServer(t *testing.T, jwksBody string) *testJwksServer {
result := &testJwksServer{}
// released on test cleanup so the /hang route does not outlive the test
done := make(chan struct{})
result.Server = httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
result.requests.Add(1)
switch request.URL.Path {
case "/jwks":
writer.Header().Set("content-type", "application/json")
_, _ = writer.Write([]byte(jwksBody))
case "/redirect-to-jwks":
http.Redirect(writer, request, "/jwks", http.StatusFound)
case "/redirect-loop":
http.Redirect(writer, request, "/redirect-loop", http.StatusFound)
case "/redirect-to-metadata":
http.Redirect(writer, request, "http://169.254.169.254/latest/meta-data/", http.StatusFound)
case "/redirect-to-unlisted-host":
http.Redirect(writer, request, "http://unlisted.example.com/jwks", http.StatusFound)
case "/hang":
<-done
case "/html":
writer.Header().Set("content-type", "text/html")
_, _ = writer.Write([]byte("<html></html>"))
case "/not-json":
writer.Header().Set("content-type", "application/json")
_, _ = writer.Write([]byte("this is not json"))
default:
writer.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(func() {
close(done)
result.Close()
})
return result
}
// mustCidrs parses CIDRs for test setup, failing the test if any cannot be parsed.
func mustCidrs(t *testing.T, values ...string) []*net.IPNet {
t.Helper()
var result []*net.IPNet
for _, value := range values {
_, ipNet, err := net.ParseCIDR(value)
if err != nil {
t.Fatalf("could not parse test CIDR %s: %v", value, err)
}
result = append(result, ipNet)
}
return result
}
+23 -1
View File
@@ -54,6 +54,10 @@ type TokenIssuerCache struct {
// due to xweb API address binds
controllerIssuers cmap.ConcurrentMap[string, common.TokenIssuer]
// jwksResolver fetches JWKS endpoints for external issuers. It is shared by every
// external issuer so that they all fetch under the same configured constraints.
jwksResolver *HardenedJwksResolver
env Env
}
@@ -64,6 +68,7 @@ func NewTokenIssuerCache(env Env) *TokenIssuerCache {
env: env,
externalIssuers: cmap.New[common.TokenIssuer](),
controllerIssuers: cmap.New[common.TokenIssuer](),
jwksResolver: NewHardenedJwksResolver(JwksFetchConfig(env)),
}
env.GetStores().ExternalJwtSigner.AddEntityEventListenerF(result.onExtJwtCreate, boltz.EntityCreatedAsync)
@@ -172,7 +177,7 @@ func (a *TokenIssuerCache) onExtJwtCreate(signer *db.ExternalJwtSigner) {
signerRec := &TokenIssuerExtJwt{
externalJwtSigner: signer,
jwksResolver: &jwks.HttpResolver{},
jwksResolver: a.jwksResolver,
kidToPubKey: map[string]common.IssuerPublicKey{},
}
@@ -219,6 +224,21 @@ func (a *TokenIssuerCache) onExtJwtDelete(signer *db.ExternalJwtSigner) {
a.externalIssuers.Remove(*signer.Issuer)
}
// reportBlockedJwksEndpoint logs an existing external JWT signer whose jwksEndpoint the current
// [edge.externalJwtSigners.jwksFetch] configuration refuses. A configuration change can orphan a
// signer that was created while its endpoint was still permitted, so this is reported at startup
// rather than only when a fetch is attempted. Endpoints that resolve to a blocked address are not
// visible here, as no name resolution is done; those are reported by the fetch itself.
func (a *TokenIssuerCache) reportBlockedJwksEndpoint(signer *db.ExternalJwtSigner) {
if err := checkJwksEndpointAllowed(a.jwksResolver.policy, signer); err != nil {
pfxlog.Logger().WithFields(map[string]interface{}{
"id": signer.Id,
"name": signer.Name,
"jwksEndpoint": *signer.JwksEndpoint,
}).WithError(err).Error("external jwt signer jwks endpoint is not permitted by the current jwks fetch configuration, its keys cannot be resolved and authentication with this signer will fail")
}
}
// loadExisting loads all external JWT signers and controllers during initialization.
func (a *TokenIssuerCache) loadExisting() {
err := a.env.GetDb().View(func(tx *bbolt.Tx) error {
@@ -235,6 +255,8 @@ func (a *TokenIssuerCache) loadExisting() {
continue
}
a.reportBlockedJwksEndpoint(signer)
a.onExtJwtCreate(signer)
}
+135
View File
@@ -262,6 +262,141 @@ edge:
# database. Only runs on the raft leader.
# revocationEnforcerFrequency: 1m
# externalJwtSigners - optional
# Settings that govern how the controller interacts with external JWT signers.
externalJwtSigners:
# jwksFetch - optional
# Controls the controller's fetch of an external JWT signer's jwksEndpoint. That fetch is
# made by the controller, from the controller's own network position, to a URL supplied by
# whoever can write an external JWT signer. These settings constrain where it may go.
#
# A fetch is allowed only if it passes TWO GATES, and both gates are applied to the first
# request AND to every redirect that is followed:
#
# the HOSTNAME gate - checked against the hostname in the URL
# the ADDRESS gate - checked against the resolved address at connection time, so a
# hostname that resolves to a blocked address is still blocked
#
# NEITHER GATE CAN AUTHORIZE WHAT THE OTHER REFUSES. Hostname matching only ever narrows what
# may be fetched: allowedHostnames does not make a blocked address reachable, and
# allowedIPs does not make a blocked hostname reachable.
#
# HOSTNAME gate, first-match-wins. DENY WINS OVER ALLOW:
#
# 1. deniedHostnames - blocked
# 2. allowedHostnames - when set, ONLY these hostnames may be fetched; anything else is
# blocked
# 3. anything else - passes to the address gate
#
# ADDRESS gate, first-match-wins. DENY WINS OVER ALLOW:
#
# 1. built-in blocked addresses - always blocked, allowedIPs CANNOT override:
# cloud instance metadata (169.254.169.254, 169.254.170.2, fd00:ec2::254)
# link-local (169.254.0.0/16, fe80::/10)
# link-local multicast (224.0.0.0/24, ff02::/16)
# unspecified (0.0.0.0, ::)
# 2. deniedIPs - blocked, allowedIPs CANNOT override
# 3. allowedIPs - allowed; this is a carve-out of tier 4 ONLY
# 4. blockPrivateAddresses, and the address is private or loopback - blocked
# 5. anything else - allowed
#
# ENTRY FORMS. The two kinds of list do not accept each other's values.
#
# deniedIPs and allowedIPs take IP addresses only, in either of two forms:
#
# a flat IP address - 192.168.5.5 or fd00:1234::1
# matches that one address only (the same as /32 or /128)
# a CIDR block - 10.10.0.0/16 or fd00:1234::/64
# matches every address in the block
#
# Both IPv4 and IPv6 are accepted in either form. A hostname in one of these lists is a
# configuration error and the controller will not start: the address gate runs against the
# address actually being connected to, so there is no hostname there to compare against.
#
# deniedHostnames and allowedHostnames take hostnames only, in either of two forms:
#
# an exact hostname - idp.example.com
# matches that hostname only
# a wildcard suffix - '*.example.com'
# matches any subdomain of example.com, AT ANY DEPTH, but NEVER
# example.com itself
#
# Wildcard matching, spelled out, because the last part surprises people:
#
# '*.sub.host.com' MATCHES idp.sub.host.com
# MATCHES a.b.sub.host.com (any depth below the suffix)
# DOES NOT sub.host.com (the suffix itself is NOT matched)
# DOES NOT other.host.com
# DOES NOT xsub.host.com (a whole label must be replaced)
#
# To cover both a domain and its subdomains, list them both:
#
# - sub.host.com
# - '*.sub.host.com'
#
# The '*' is only supported as the entire leading label, written exactly as '*.'. Anything
# else (idp.*.example.com, *idp.example.com, a bare *) is a configuration error. Quote any
# entry that starts with '*', or YAML will reject it as an alias. Matching ignores case and
# a trailing dot, and a unicode hostname is compared in its punycode form. An IP address in
# one of these lists is a configuration error - use deniedIPs or allowedIPs.
jwksFetch:
# deniedHostnames - optional, default empty
# Tier 1 of the HOSTNAME gate: hostnames that may not be fetched. Takes exact hostnames
# and '*.suffix' wildcards, per ENTRY FORMS above.
# This narrows only, it is not a boundary on its own: the same target can be reached
# under a different name or as a literal IP, which is what the address gate is for.
# deniedHostnames:
# - old-idp.example.com
# - '*.internal.example.com'
# allowedHostnames - optional, default empty
# Tier 2 of the HOSTNAME gate: when this list is non-empty, these are the ONLY hostnames that
# may be fetched, on the first request and on every redirect hop. Same entry forms as
# deniedHostnames, and deniedHostnames still wins. It cannot widen the address gate: a listed
# hostname whose address is blocked stays blocked. Note that while this list is set, an
# endpoint written as a literal IP address can never satisfy it.
# allowedHostnames:
# - idp.example.com
# - '*.idp.example.org'
# blockPrivateAddresses - optional, default false
# Tier 4 of the ADDRESS gate: blocks private and loopback addresses
# (127.0.0.0/8, ::1, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7). Defaults to
# false so a deployment whose IdP is on an internal address keeps working. Tier 1 is
# blocked either way, so the metadata service is never reachable. For the strictest
# posture set this to true, list any internal IdP address in allowedIPs, and list
# the IdP hostnames in allowedHostnames.
# blockPrivateAddresses: false
# deniedIPs - optional, default empty
# Tier 2 of the ADDRESS gate: addresses that are always blocked. Takes flat IP addresses
# and CIDR blocks, per ENTRY FORMS above. Nothing in allowedIPs or allowedHostnames can
# re-enable an address listed here, so this is the right place for internal ranges that
# must never be fetched.
# deniedIPs:
# - 10.10.0.0/16 # a CIDR block
# - 192.168.5.5 # a flat IP address
# - fd00:1234::/64 # IPv6 is accepted in either form
# allowedIPs - optional, default empty
# Tier 3 of the ADDRESS gate: a carve-out of tier 4 ONLY. Same entry forms as deniedIPs.
# Listing an address here allows it despite blockPrivateAddresses; it does NOT override
# tier 1 or deniedIPs, and it does NOT satisfy the hostname gate. Use it to reach a
# specific internal IdP while blockPrivateAddresses is true.
# allowedIPs:
# - 10.20.30.0/24
# - 10.20.40.7
# timeout - optional, default 5s
# The total time allowed for a single JWKS fetch, including any redirects. Must be
# greater than zero.
# timeout: 5s
# maxRedirects - optional, default 5
# How many redirects a JWKS fetch will follow. Every hop passes through both gates. Set
# to 0 to refuse to follow redirects at all.
# maxRedirects: 5
# Set to true to disable posture check functionality
disablePostureChecks: false
@@ -0,0 +1,88 @@
//go:build apitests
/*
Copyright NetFoundry Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tests
import (
"testing"
"github.com/go-openapi/strfmt"
"github.com/openziti/edge-api/rest_model"
"github.com/openziti/foundation/v2/errorz"
"github.com/openziti/ziti/v2/common/eid"
)
// Test_ExternalJwtSigner_JwksEndpoint covers the create-time check on an external JWT signer's
// jwksEndpoint. The controller fetches that URL itself, so an endpoint that the configured
// fetch policy would refuse is rejected up front rather than failing later during a fetch.
func Test_ExternalJwtSigner_JwksEndpoint(t *testing.T) {
ctx := NewTestContext(t)
defer ctx.Teardown()
ctx.StartServer()
adminManClient := ctx.NewEdgeManagementApi(nil)
adminManApiSession, err := adminManClient.Authenticate(ctx.NewAdminCredentials(), nil)
ctx.Req.NoError(err)
ctx.Req.NotNil(adminManApiSession)
t.Run("an endpoint pointing at the instance metadata service is rejected", func(t *testing.T) {
ctx.testContextChanged(t)
detail, err := adminManClient.CreateExtJwtSigner(newJwksSignerCreate("http://169.254.169.254/latest/meta-data/"))
ctx.Req.Error(err, "the metadata service must never be fetchable, regardless of configuration")
ctx.Req.ApiErrorWithCode(err, errorz.InvalidFieldCode)
ctx.Req.Nil(detail)
})
t.Run("an endpoint with a non-http scheme is rejected", func(t *testing.T) {
ctx.testContextChanged(t)
detail, err := adminManClient.CreateExtJwtSigner(newJwksSignerCreate("file:///etc/passwd"))
ctx.Req.Error(err)
ctx.Req.ApiErrorWithCode(err, errorz.InvalidFieldCode)
ctx.Req.Nil(detail)
})
t.Run("an endpoint with a hostname is accepted", func(t *testing.T) {
ctx.testContextChanged(t)
// no name resolution happens at create time, the dial-time check covers a hostname
// that resolves to a blocked address
detail, err := adminManClient.CreateExtJwtSigner(newJwksSignerCreate("https://idp.example.com/.well-known/jwks.json"))
ctx.Req.NoError(err)
ctx.Req.NotNil(detail)
})
}
// newJwksSignerCreate returns a uniquely named external JWT signer create payload that uses
// the given jwksEndpoint.
func newJwksSignerCreate(jwksEndpoint string) *rest_model.ExternalJWTSignerCreate {
name := eid.New()
endpoint := strfmt.URI(jwksEndpoint)
return &rest_model.ExternalJWTSignerCreate{
Name: ToPtr(name),
Enabled: ToPtr(true),
Issuer: ToPtr(name + "-issuer"),
Audience: ToPtr(name + "-audience"),
JwksEndpoint: &endpoint,
}
}