| index 49b24295e..b27786cd7 100644 |
| --- a/internal/console/sesevents.go |
| +++ b/internal/console/sesevents.go |
| @@ -725,17 +725,72 @@ func (s *Server) confirmSNSSubscription(ctx context.Context, subscribeURL string |
| // certificate at a time and rotates rarely; a handful of slots is plenty, |
| // and the oldest entry makes room when they are full. |
| // |
| +// A cache only bounds hits; a miss is outbound work an unsigned request can |
| +// ask for (H5-M12 review 1). So, before any fetch: the path must have the |
| +// shape of an SNS signing certificate (validSigningCertPath); identical |
| +// misses in flight share one fetch; a failed URL is not fetched again until |
| +// its backoff (snsCertBackoff, doubling per failure to a ceiling) runs out, |
| +// and the failures remembered are bounded too; and the door as a whole |
| +// starts at most snsCertFetchesPerMinute fetches a minute and holds at most |
| +// snsCertFetchesInFlight at once, refusing past either without fetching. |
| +// A genuine message whose certificate is cached never fetches, so an |
| +// attacker filling these windows delays only a certificate rotation, and |
| +// SNS retries a refused delivery. |
| +// |
| // A value type with a nil-safe zero value on purpose: Server embeds one |
| // directly (no constructor call needed), the same way ceClientOnce |
| // (server.go) needs no init. |
| type snsCertCache struct { |
| mu sync.Mutex |
| + now func() time.Time // nil: time.Now |
| keys map[string]*rsa.PublicKey |
| order []string // insertion order of keys, oldest first |
| + |
| + fails map[string]snsCertFailure // failed fetches, by canonical URL |
| + failOrder []string // insertion order of fails, oldest first |
| + inflight map[string]*snsCertCall // fetches in flight, by canonical URL |
| + started []time.Time // fetch starts in the last minute |
| } |
| |
| -// snsCertCacheMax bounds snsCertCache. |
| -const snsCertCacheMax = 8 |
| +// snsCertFailure is a URL's failed fetches: how many in a row, the last |
| +// error, and when it may be fetched again. |
| +type snsCertFailure struct { |
| + n int |
| + err error |
| + until time.Time |
| +} |
| + |
| +// snsCertCall is one fetch in flight; done closes when pub and err are set. |
| +type snsCertCall struct { |
| + done chan struct{} |
| + pub *rsa.PublicKey |
| + err error |
| +} |
| + |
| +const ( |
| + // snsCertCacheMax bounds the verified keys, and snsCertFailMax the |
| + // failures, snsCertCache remembers. |
| + snsCertCacheMax = 8 |
| + snsCertFailMax = 64 |
| + // snsCertFetchesInFlight and snsCertFetchesPerMinute bound the |
| + // certificate fetches the whole door makes. |
| + snsCertFetchesInFlight = 2 |
| + snsCertFetchesPerMinute = 10 |
| + // A failed URL waits snsCertBackoffBase, doubling per failure in a row, |
| + // up to snsCertBackoffMax, before it is fetched again. |
| + snsCertBackoffBase = 30 * time.Second |
| + snsCertBackoffMax = 15 * time.Minute |
| +) |
| + |
| +// errSNSCertBusy refuses a miss past the door's fetch limits, unfetched. |
| +var errSNSCertBusy = errors.New("sns: signing cert fetches over their limit; not fetched") |
| + |
| +func (c *snsCertCache) clock() time.Time { |
| + if c.now != nil { |
| + return c.now() |
| + } |
| + return time.Now() |
| +} |
| |
| func (c *snsCertCache) get(certURL string) (*rsa.PublicKey, bool) { |
| c.mu.Lock() |
| @@ -747,6 +802,10 @@ func (c *snsCertCache) get(certURL string) (*rsa.PublicKey, bool) { |
| func (c *snsCertCache) put(certURL string, pub *rsa.PublicKey) { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| + c.putLocked(certURL, pub) |
| +} |
| + |
| +func (c *snsCertCache) putLocked(certURL string, pub *rsa.PublicKey) { |
| if c.keys == nil { |
| c.keys = map[string]*rsa.PublicKey{} |
| } |
| @@ -760,6 +819,118 @@ func (c *snsCertCache) put(certURL string, pub *rsa.PublicKey) { |
| c.keys[certURL] = pub |
| } |
| |
| +// snsCertBackoff is how long a URL waits after its nth failure in a row. |
| +func snsCertBackoff(n int) time.Duration { |
| + d := snsCertBackoffBase |
| + for i := 1; i < n && d < snsCertBackoffMax; i++ { |
| + d *= 2 |
| + } |
| + return min(d, snsCertBackoffMax) |
| +} |
| + |
| +// failLocked records a failed fetch of certURL. |
| +func (c *snsCertCache) failLocked(certURL string, err error, now time.Time) { |
| + if c.fails == nil { |
| + c.fails = map[string]snsCertFailure{} |
| + } |
| + f, ok := c.fails[certURL] |
| + if !ok { |
| + for len(c.failOrder) >= snsCertFailMax { |
| + delete(c.fails, c.failOrder[0]) |
| + c.failOrder = c.failOrder[1:] |
| + } |
| + c.failOrder = append(c.failOrder, certURL) |
| + } |
| + f.n++ |
| + f.err = err |
| + f.until = now.Add(snsCertBackoff(f.n)) |
| + c.fails[certURL] = f |
| +} |
| + |
| +// key returns certURL's verified key: cached, the answer of a fetch already |
| +// in flight for it, a remembered failure still in its backoff, a refusal |
| +// past the door's fetch limits, or else the result of fetching it now with |
| +// fetch. certURL is canonical and shape-checked. |
| +func (c *snsCertCache) key(ctx context.Context, certURL string, fetch func(context.Context, string) (*rsa.PublicKey, error)) (*rsa.PublicKey, error) { |
| + c.mu.Lock() |
| + if pub, ok := c.keys[certURL]; ok { |
| + c.mu.Unlock() |
| + return pub, nil |
| + } |
| + now := c.clock() |
| + if f, ok := c.fails[certURL]; ok && now.Before(f.until) { |
| + c.mu.Unlock() |
| + return nil, f.err |
| + } |
| + if call, ok := c.inflight[certURL]; ok { |
| + c.mu.Unlock() |
| + select { |
| + case <-call.done: |
| + return call.pub, call.err |
| + case <-ctx.Done(): |
| + return nil, ctx.Err() |
| + } |
| + } |
| + kept := c.started[:0] |
| + for _, t := range c.started { |
| + if t.After(now.Add(-time.Minute)) { |
| + kept = append(kept, t) |
| + } |
| + } |
| + c.started = kept |
| + if len(c.inflight) >= snsCertFetchesInFlight || len(c.started) >= snsCertFetchesPerMinute { |
| + c.mu.Unlock() |
| + return nil, errSNSCertBusy |
| + } |
| + if c.inflight == nil { |
| + c.inflight = map[string]*snsCertCall{} |
| + } |
| + call := &snsCertCall{done: make(chan struct{})} |
| + c.inflight[certURL] = call |
| + c.started = append(c.started, now) |
| + c.mu.Unlock() |
| + |
| + // The fetch is the door's, not this request's: a caller that gives up |
| + // must not fail the others waiting on it. |
| + call.pub, call.err = fetch(context.WithoutCancel(ctx), certURL) |
| + |
| + c.mu.Lock() |
| + delete(c.inflight, certURL) |
| + if call.err != nil { |
| + c.failLocked(certURL, call.err, c.clock()) |
| + } else { |
| + c.putLocked(certURL, call.pub) |
| + delete(c.fails, certURL) // its failOrder slot ages out |
| + } |
| + c.mu.Unlock() |
| + close(call.done) |
| + return call.pub, call.err |
| +} |
| + |
| +// snsCertPathPattern is the path of an SNS signing certificate: |
| +// /SimpleNotificationService-<hex>.pem, as every SigningCertURL AWS |
| +// documents and sends (the hex is 32 digits today; any length up to 64 is |
| +// let through so a change of digest does not stop mail). |
| +var snsCertPathPattern = regexp.MustCompile(`^/SimpleNotificationService-[0-9a-fA-F]{1,64}\.pem$`) |
| + |
| +// validSigningCertPath refuses a canonical SigningCertURL whose path is not |
| +// an SNS signing certificate's, or that names a port other than https's: |
| +// nothing else on the pinned host is worth a fetch (H5-M12 review 1). It is |
| +// for SigningCertURL only; SubscribeURL is a query on "/". |
| +func validSigningCertPath(certURL string) error { |
| + u, err := url.Parse(certURL) |
| + if err != nil { |
| + return fmt.Errorf("sns: unparseable SigningCertURL") |
| + } |
| + if u.Port() != "" { |
| + return fmt.Errorf("sns: SigningCertURL names a port") |
| + } |
| + if !snsCertPathPattern.MatchString(u.EscapedPath()) { |
| + return fmt.Errorf("sns: SigningCertURL path %q is not an SNS signing certificate", u.EscapedPath()) |
| + } |
| + return nil |
| +} |
| + |
| // canonicalSigningCertURL is the one URL a SigningCertURL names, for both |
| // the cache key and the fetch: https, the lowercased host (default port |
| // dropped), the path as given, and nothing else. A fragment never reaches |
| @@ -779,22 +950,18 @@ func canonicalSigningCertURL(raw string) (string, error) { |
| |
| // verifiedCertKey returns the RSA public key for a signing certificate URL |
| // — already pinned to an SNS host by the caller (validSigningCertURL) — |
| -// using the cache on a hit, and fetching plus fully verifying the |
| -// certificate on a miss. Both use the canonical URL. |
| +// canonical and shape-checked first, then through snsCertCache.key: the |
| +// cache on a hit, and on a miss, within the door's fetch limits, fetching |
| +// plus fully verifying the certificate. |
| func (s *Server) verifiedCertKey(ctx context.Context, certURL string) (*rsa.PublicKey, error) { |
| certURL, err := canonicalSigningCertURL(certURL) |
| if err != nil { |
| return nil, err |
| } |
| - if pub, ok := s.snsCerts.get(certURL); ok { |
| - return pub, nil |
| - } |
| - pub, err := fetchVerifiedCertKey(ctx, certURL) |
| - if err != nil { |
| + if err := validSigningCertPath(certURL); err != nil { |
| return nil, err |
| } |
| - s.snsCerts.put(certURL, pub) |
| - return pub, nil |
| + return s.snsCerts.key(ctx, certURL, fetchVerifiedCertKey) |
| } |
| |
| // snsCertDNSName is the hostname a genuine SNS message-signing certificate |