console: canonical, bounded SNS signing-cert cache (H5-M12)
The unauthenticated SES door cached each verified cert key by the raw SigningCertURL, so a fragment or query variant cost a fresh fetch and a map entry that never left. Key and fetch now use the canonical URL (https, lowercased host, path only), and the cache keeps at most eight entries, oldest out first. The regional host pin is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+175
−4
internal/console/hunt_H5-M12_test.go+88 −0internal/console/server.go+2 −1internal/console/sesevents.go+44 −3internal/console/sesevents_test.go+41 −0
Intent
diff --git a/internal/console/hunt_H5-M12_test.go b/internal/console/hunt_H5-M12_test.go| new file mode 100644 |
| index 000000000..a694e8453 |
| --- /dev/null |
| +++ b/internal/console/hunt_H5-M12_test.go |
| @@ -0,0 +1,88 @@ |
| +package console |
| + |
| +// Hunt H5-M12 (verifier: opus). POST /api/ses/events is unauthenticated. With |
| +// the deployment's (non-secret) TopicArn and a SigningCertURL on the pinned |
| +// regional SNS host, validSigningCertURL accepts any fragment (and any query), |
| +// verifiedCertKey caches by the WHOLE URL string, and the entry is stored |
| +// before the signature is checked. So each distinct fragment is a fresh |
| +// outbound fetch and a new map entry that lives forever, with the URL string |
| +// itself (up to the 256 KiB body ceiling) as the retained key. |
| +// |
| +// Production wiring: the real registered route, snsVerify left nil so the |
| +// real verifySNSSignature -> verifiedCertKey -> fetchVerifiedCertKey path |
| +// runs. Only the network under snsFetchClient is pointed at a local TLS |
| +// listener (hijackFetchClient, the existing seam), and TLS hostname |
| +// verification still runs against sns.eu-west-1.amazonaws.com. |
| + |
| +import ( |
| + "crypto/tls" |
| + "encoding/json" |
| + "encoding/pem" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| +) |
| + |
| +func TestHunt_H5_M12_FragmentsGrowCertCache(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.MailDeployment.SNSTopicARN = "arn:aws:sns:eu-west-1:1:carlos-mail" |
| + fx.srv.cfg.MailDeployment.Region = "eu-west-1" |
| + if fx.srv.snsVerify != nil { |
| + t.Fatal("test bug: the real signature path must run") |
| + } |
| + |
| + const regional = "sns.eu-west-1.amazonaws.com" |
| + tlsDER, tlsLeaf, tlsKey := genLeafCert(t, regional) |
| + pemDER, _, _ := genLeafCert(t, snsCertDNSName) |
| + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pemDER}) |
| + var fetches atomic.Int64 |
| + ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + fetches.Add(1) |
| + w.Write(certPEM) |
| + })) |
| + ts.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{tlsDER}, PrivateKey: tlsKey}}} |
| + ts.StartTLS() |
| + t.Cleanup(ts.Close) |
| + hijackFetchClient(t, ts.Listener.Addr().String(), tlsLeaf) |
| + |
| + post := func(certURL string) int { |
| + env := map[string]string{ |
| + "Type": "Notification", "MessageId": "m", "TopicArn": fx.srv.cfg.MailDeployment.SNSTopicARN, |
| + "Message": "{}", "Timestamp": "2026-10-25T00:00:00Z", "SignatureVersion": "1", |
| + "Signature": "Ym9ndXM=", "SigningCertURL": certURL, |
| + } |
| + b, _ := json.Marshal(env) |
| + resp := sesPost(t, fx, string(b)) |
| + resp.Body.Close() |
| + return resp.StatusCode |
| + } |
| + |
| + const n = 25 |
| + base := "https://" + regional + "/SimpleNotificationService-0123456789abcdef.pem" |
| + for i := 0; i < n; i++ { |
| + if code := post(fmt.Sprintf("%s#%d", base, i)); code != http.StatusForbidden { |
| + t.Fatalf("request %d = %d, want 403 (bogus signature)", i, code) |
| + } |
| + } |
| + // One long fragment: the retained key is the attacker's string. |
| + long := base + "#" + strings.Repeat("A", 200<<10) |
| + if code := post(long); code != http.StatusForbidden { |
| + t.Fatalf("long-fragment request = %d, want 403", code) |
| + } |
| + |
| + fx.srv.snsCerts.mu.Lock() |
| + entries, keyBytes := len(fx.srv.snsCerts.keys), 0 |
| + for k := range fx.srv.snsCerts.keys { |
| + keyBytes += len(k) |
| + } |
| + fx.srv.snsCerts.mu.Unlock() |
| + |
| + if entries > 1 || fetches.Load() > 1 { |
| + t.Fatalf("H5-M12: %d unauthenticated requests with invalid signatures, differing only in the URL fragment, "+ |
| + "caused %d outbound certificate fetches and left %d cache entries retaining %d bytes of attacker-chosen keys "+ |
| + "(want one canonical entry and one fetch)", n+1, fetches.Load(), entries, keyBytes) |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index cb60800dd..75f01ce82 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1528,7 +1528,8 @@ type Server struct { |
| // only place production ever sends. A test points it at an httptest |
| // server instead. The path still goes through the same validation. |
| mailPushTarget func(acct, app, path string) string |
| - // snsCerts caches a verified signing certificate's RSA public key by URL |
| + // snsCerts caches a verified signing certificate's RSA public key by its |
| + // canonical URL, a few entries at most |
| // (sesevents.go) — otherwise every request bearing the deployment's |
| // TopicArn, which is not a secret, triggers a fresh outbound HTTPS fetch |
| // and full chain verification. Zero value is ready to use. |
diff --git a/internal/console/sesevents.go b/internal/console/sesevents.go| index 0f086fa46..49b24295e 100644 |
| --- a/internal/console/sesevents.go |
| +++ b/internal/console/sesevents.go |
| @@ -716,14 +716,27 @@ func (s *Server) confirmSNSSubscription(ctx context.Context, subscribeURL string |
| // outbound amplification, one connection out per request in. The AWS SDKs |
| // cache verification certs by URL for the same reason. |
| // |
| +// The key is the CANONICAL URL (canonicalSigningCertURL), and the map holds |
| +// at most snsCertCacheMax entries (H5-M12). The door is unauthenticated and |
| +// the entry is stored before the message signature is checked, so keying on |
| +// the raw string let any caller with the TopicArn mint a fresh fetch and a |
| +// map entry that lived forever per fragment or query variant, the URL itself |
| +// (up to the body ceiling) retained as the key. SNS signs with one |
| +// certificate at a time and rotates rarely; a handful of slots is plenty, |
| +// and the oldest entry makes room when they are full. |
| +// |
| // 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 |
| - keys map[string]*rsa.PublicKey |
| + mu sync.Mutex |
| + keys map[string]*rsa.PublicKey |
| + order []string // insertion order of keys, oldest first |
| } |
| +// snsCertCacheMax bounds snsCertCache. |
| +const snsCertCacheMax = 8 |
| + |
| func (c *snsCertCache) get(certURL string) (*rsa.PublicKey, bool) { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| @@ -737,14 +750,42 @@ func (c *snsCertCache) put(certURL string, pub *rsa.PublicKey) { |
| if c.keys == nil { |
| c.keys = map[string]*rsa.PublicKey{} |
| } |
| + if _, ok := c.keys[certURL]; !ok { |
| + for len(c.order) >= snsCertCacheMax { |
| + delete(c.keys, c.order[0]) |
| + c.order = c.order[1:] |
| + } |
| + c.order = append(c.order, certURL) |
| + } |
| c.keys[certURL] = pub |
| } |
| +// 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 |
| +// the wire and a query is not part of an SNS certificate's address, so |
| +// neither may make a second fetch or a second cache entry (H5-M12). |
| +// Userinfo goes too. raw has already passed validSigningCertURL. |
| +func canonicalSigningCertURL(raw string) (string, error) { |
| + u, err := url.Parse(raw) |
| + if err != nil { |
| + return "", fmt.Errorf("sns: unparseable SigningCertURL") |
| + } |
| + host := strings.ToLower(u.Host) |
| + host = strings.TrimSuffix(host, ":443") |
| + c := url.URL{Scheme: "https", Host: host, Path: u.Path, RawPath: u.RawPath} |
| + return c.String(), nil |
| +} |
| + |
| // 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. |
| +// certificate on a miss. Both use the canonical URL. |
| 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 |
| } |
diff --git a/internal/console/sesevents_test.go b/internal/console/sesevents_test.go| index 3e9394a5a..46432da21 100644 |
| --- a/internal/console/sesevents_test.go |
| +++ b/internal/console/sesevents_test.go |
| @@ -25,6 +25,7 @@ import ( |
| "encoding/base64" |
| "encoding/pem" |
| "errors" |
| + "fmt" |
| "log" |
| "math/big" |
| "net" |
| @@ -703,6 +704,46 @@ func TestVerifiedCertKeyServesFromCache(t *testing.T) { |
| } |
| } |
| +// The cache holds at most snsCertCacheMax keys (H5-M12): the oldest makes |
| +// room, and the newest is always kept. |
| +func TestSNSCertCacheIsBounded(t *testing.T) { |
| + var c snsCertCache |
| + key, err := rsa.GenerateKey(rand.Reader, 1024) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 3*snsCertCacheMax; i++ { |
| + c.put(fmt.Sprintf("https://sns.eu-west-1.amazonaws.com/%d.pem", i), &key.PublicKey) |
| + } |
| + if len(c.keys) != snsCertCacheMax || len(c.order) != snsCertCacheMax { |
| + t.Fatalf("cache holds %d keys (%d ordered), want %d", len(c.keys), len(c.order), snsCertCacheMax) |
| + } |
| + if _, ok := c.get(fmt.Sprintf("https://sns.eu-west-1.amazonaws.com/%d.pem", 3*snsCertCacheMax-1)); !ok { |
| + t.Fatal("the newest key was evicted") |
| + } |
| + if _, ok := c.get("https://sns.eu-west-1.amazonaws.com/0.pem"); ok { |
| + t.Fatal("the oldest key survived past the bound") |
| + } |
| +} |
| + |
| +// Fragment, query, userinfo, host case and the default port do not change |
| +// the certificate a SigningCertURL names, so none may change the cache key. |
| +func TestCanonicalSigningCertURL(t *testing.T) { |
| + const want = "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-abc.pem" |
| + for _, raw := range []string{ |
| + want, |
| + want + "#x", |
| + want + "?a=b", |
| + want + "?a=b#x", |
| + "https://u:p@SNS.eu-west-1.amazonaws.com:443/SimpleNotificationService-abc.pem", |
| + } { |
| + got, err := canonicalSigningCertURL(raw) |
| + if err != nil || got != want { |
| + t.Errorf("canonicalSigningCertURL(%q) = %q, %v; want %q", raw, got, err, want) |
| + } |
| + } |
| +} |
| + |
| // ---- event-to-domain attribution (I6, review follow-up) -------------------- |
| // |
| // ParseEvent attributes an event by the domain of mail.source. If SES |