carlos / platform Public

console: a stranger's wrong codes cannot lock the owner's code (H4-M6)

Twelve requests with only an address spent its 10-a-day wrong-code
budget on held challenges and locked the owner's sign-in and step-up
codes. A held challenge (code never sent) now never redeems, and its
wrong codes go to a window that throttles held challenges only; sent
challenges keep the per-address budget. Step-up gets its own budget,
and the demo-claim doors use the same held-aware reservation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5d5a6bd6c030519fb727235ff0faafdefc763dec parent 9e9eff9
8 files changed, +319 −34
  • internal/console/demo_claim_auth.go +1 −1
  • internal/console/demo_claim_page.go +1 −1
  • internal/console/emailsignin.go +8 −5
  • internal/console/emailsignin_limits.go +56 −13
  • internal/console/emailsignin_limits_test.go +74 −0
  • internal/console/emailsignin_store.go +31 −14
  • internal/console/emailsignin_store_test.go +40 −0
  • internal/console/hunt_H4-M6_test.go +108 −0

CI passed — run details

diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go
index ede96e8c9..4d4e6f2eb 100644
--- a/internal/console/demo_claim_auth.go
+++ b/internal/console/demo_claim_auth.go
@@ -253,7 +253,7 @@ func (s *Server) handleDemoClaimVerify(w http.ResponseWriter, r *http.Request) {
if s.cfg.DemoAPIOrigin == "" {
ip = s.clientIP(r)
}
- done, ok := s.limits.reserveGuess(c.Address, ip)
+ done, ok := s.limits.reserveCodeGuess(c, ip)
if !ok {
jsonError(w, 401, demoClaimBadProof)
return
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index 2c9e8f925..4e0de4ede 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -432,7 +432,7 @@ func (s *Server) handleDemoClaimBrowserProof(w http.ResponseWriter, r *http.Requ
s.demoClaimBrowserError(w, 401, demoClaimBadProof)
return
}
- done, ok := s.limits.reserveGuess(c.Address, ip)
+ done, ok := s.limits.reserveCodeGuess(c, ip)
if !ok {
s.demoClaimBrowserError(w, 401, demoClaimBadProof)
return
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index d663c65ce..ff2e4b773 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -437,8 +437,10 @@ func (s *Server) handleEmailLink(w http.ResponseWriter, r *http.Request) {
// flow. A challenge that was sent and one a refused request recorded unsent
// answer alike, so the code box says nothing about throttling. Wrong codes
// count against the challenge's address and the client IP across every
-// challenge (spec 5); past either cap the code is refused unchecked and
-// nothing is burned, so the emailed link still works.
+// challenge (spec 5), a held challenge's apart from the sent ones' so a
+// stranger cannot spend the owner's budget (reserveCodeGuess); past either
+// cap the code is refused unchecked and nothing is burned, so the emailed
+// link still works.
func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) {
if !s.sameOrigin(r) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
@@ -459,7 +461,7 @@ func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) {
// One guess is reserved before the check, so concurrent guesses cannot all
// pass on the same count; only a right code takes it back.
ip := s.clientIP(r)
- done, allowed := s.limits.reserveGuess(c.Address, ip)
+ done, allowed := s.limits.reserveCodeGuess(c, ip)
if !allowed {
log.Printf("console: code for %s from %s refused: too many wrong codes", c.Address, ip)
s.renderCheckError(w, flow, addr, next, copyText("check.code_throttled"))
@@ -618,7 +620,8 @@ func (s *Server) stepUpLink(w http.ResponseWriter, r *http.Request, link string,
// handleStepUpEmailCode is POST /auth/email/stepup/code: the typed code is
// checked only against the newest live step-up challenge made for this
// browser's session. Wrong codes count against the
-// challenge's address and the client IP, as for sign-in codes.
+// challenge's address and the client IP, as for sign-in codes, in a step-up
+// budget of their own that sign-in guesses cannot spend (reserveCodeGuess).
func (s *Server) handleStepUpEmailCode(w http.ResponseWriter, r *http.Request) {
addr, raw, ok := s.session(r)
if !ok {
@@ -636,7 +639,7 @@ func (s *Server) handleStepUpEmailCode(w http.ResponseWriter, r *http.Request) {
return
}
ip := s.clientIP(r)
- done, allowed := s.limits.reserveGuess(c.Address, ip)
+ done, allowed := s.limits.reserveCodeGuess(c, ip)
if !allowed {
log.Printf("console: step-up code for %s from %s refused: too many wrong codes", c.Address, ip)
s.renderStepUp(w, r, c.Address, copyText("check.code_throttled"))
diff --git a/internal/console/emailsignin_limits.go b/internal/console/emailsignin_limits.go
index ff4a2db6f..771243e16 100644
--- a/internal/console/emailsignin_limits.go
+++ b/internal/console/emailsignin_limits.go
@@ -24,7 +24,7 @@ const (
newPersonPerIPHour = 10 // new people per IP
newPersonGlobalHour = 200 // new people console-wide
stepUpPerAddrHour = 10 // step-up emails per address
- wrongCodesPerAddrDay = 10 // wrong codes per address
+ wrongCodesPerAddrDay = 10 // wrong codes per address, per budget (see reserveCodeGuess)
wrongCodesPerIPHour = 30 // wrong codes per IP
// Alert confirmations (fleet alerts spec §5.3): every verify row that
@@ -139,7 +139,9 @@ type emailLimits struct {
ipSends keyedWindow // sign-in emails, by IP
globalSend []time.Time // sign-in emails to unknown addresses, console-wide
stepUps keyedWindow // step-up emails, by address
- addrWrong keyedWindow // wrong codes, by address
+ addrWrong keyedWindow // wrong codes against sent sign-in challenges, by address
+ heldWrong keyedWindow // wrong codes against held (unsent) sign-in challenges, by address
+ stepWrong keyedWindow // wrong step-up codes, by address
ipWrong keyedWindow // wrong codes, by IP
alertConfirms keyedWindow // alert confirmation sends, by alert scope
@@ -174,7 +176,7 @@ func (l *emailLimits) submit(ip string) bool {
}
func (l *emailLimits) sweepWindows() []*keyedWindow {
- return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.ipWrong, &l.alertConfirms, &l.ipNewPeople}
+ return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.heldWrong, &l.stepWrong, &l.ipWrong, &l.alertConfirms, &l.ipNewPeople}
}
// newPerson reserves one new-person slot across all sign-in paths (social
@@ -318,25 +320,66 @@ func (l *emailLimits) stepUpSend(addr string) bool {
return true
}
-// reserveGuess is the guessing cap as one step, so concurrent guesses cannot
-// all pass on the same count. Under the lock it refuses (allowed false) once
-// addr has 10 guesses in 24 hours or ip has 30 in an hour; otherwise it
+// reserveGuess is reserveCodeGuess for a code typed against a sent sign-in
+// challenge for addr: the sign-in budget, charged to addr and ip.
+// Callers pass addr canonical (trimmed, lower-cased).
+func (l *emailLimits) reserveGuess(addr, ip string) (done func(ok bool), allowed bool) {
+ return l.reserveGuessIn(&l.addrWrong, nil, addr, ip)
+}
+
+// reserveCodeGuess is the guessing cap for a code typed against c, as one
+// step, so concurrent guesses cannot all pass on the same count. Under the
+// lock it refuses (allowed false) once c's address has 10 wrong codes in 24
+// hours in the budget that applies, or ip has 30 in an hour; otherwise it
// records one guess against both at once and returns done, through which the
// caller reports the verdict: done(true), a right code, takes the reservation
// back; done(false), any other outcome, keeps it as a wrong code. done acts
// once; later calls do nothing. Refused, done is a no-op.
-// Callers pass addr canonical (trimmed, lower-cased).
-func (l *emailLimits) reserveGuess(addr, ip string) (done func(ok bool), allowed bool) {
+//
+// Wrong codes are bounded per address across all its challenges (spec §5), so
+// a fresh challenge buys no fresh guesses. But the address budget is one a
+// stranger who knows only the address could spend, locking the owner's own
+// right code out for a day (H4-M6). So it is split by who could know a code:
+// - Sent sign-in challenges (and demo claims) share addrWrong. Only these
+// can be guessed into: their code is in the owner's mailbox.
+// - A held challenge (Store.HoldEmailChallenge: a refused request's, whose
+// code nobody is told) never redeems a code, so guessing it risks
+// nothing. Its wrong codes go to heldWrong, and the cap refuses a held
+// challenge on addrWrong plus heldWrong, so it is throttled exactly as a
+// sent one would be, while the owner's sent challenge reads addrWrong
+// alone.
+// - Step-up challenges go to stepWrong: only the address's own session can
+// ask for one, so sign-in guesses never lock it, nor it them.
+//
+// The IP budget covers them all.
+func (l *emailLimits) reserveCodeGuess(c *EmailChallenge, ip string) (done func(ok bool), allowed bool) {
+ switch {
+ case c.Purpose == ChallengeStepUp:
+ return l.reserveGuessIn(&l.stepWrong, nil, c.Address, ip)
+ case c.held:
+ return l.reserveGuessIn(&l.heldWrong, &l.addrWrong, c.Address, ip)
+ }
+ return l.reserveGuessIn(&l.addrWrong, nil, c.Address, ip)
+}
+
+// reserveGuessIn is reserveCodeGuess over one address window, w, charged and
+// counted; also, when not nil, counted but never charged here.
+func (l *emailLimits) reserveGuessIn(w, also *keyedWindow, addr, ip string) (done func(ok bool), allowed bool) {
l.mu.Lock()
defer l.mu.Unlock()
now := l.clock()
- l.addrWrong.trim(addr, now)
+ day := now.Add(-24 * time.Hour)
+ w.trim(addr, now)
l.ipWrong.trim(ip, now)
- if l.addrWrong.count(addr, now.Add(-24*time.Hour)) >= wrongCodesPerAddrDay ||
- l.ipWrong.count(ip, now.Add(-time.Hour)) >= wrongCodesPerIPHour {
+ n := w.count(addr, day)
+ if also != nil {
+ also.trim(addr, now)
+ n += also.count(addr, day)
+ }
+ if n >= wrongCodesPerAddrDay || l.ipWrong.count(ip, now.Add(-time.Hour)) >= wrongCodesPerIPHour {
return func(bool) {}, false
}
- l.addrWrong.add(addr, now)
+ w.add(addr, now)
l.ipWrong.add(ip, now)
var once sync.Once
return func(ok bool) {
@@ -346,7 +389,7 @@ func (l *emailLimits) reserveGuess(addr, ip string) (done func(ok bool), allowed
}
l.mu.Lock()
defer l.mu.Unlock()
- l.addrWrong.remove(addr, now)
+ w.remove(addr, now)
l.ipWrong.remove(ip, now)
})
}, true
diff --git a/internal/console/emailsignin_limits_test.go b/internal/console/emailsignin_limits_test.go
index af5dbf785..eaecf6e49 100644
--- a/internal/console/emailsignin_limits_test.go
+++ b/internal/console/emailsignin_limits_test.go
@@ -550,3 +550,77 @@ func TestSigninSendSweepCleansStaleAcrossCalls(t *testing.T) {
t.Fatal("stepUps or alertConfirms not swept")
}
}
+
+// The wrong-code budget is split by who could know the code (H4-M6): a held
+// challenge's wrong codes never lock the owner's sent one, yet a held one is
+// throttled as a sent one would be; step-up has its own budget; the IP
+// budget covers all.
+func TestReserveCodeGuessSplitsTheAddressBudget(t *testing.T) {
+ const addr = "bob@example.com"
+ sent := &EmailChallenge{Purpose: ChallengeSignIn, Address: addr}
+ held := &EmailChallenge{Purpose: ChallengeSignIn, Address: addr, held: true}
+ step := &EmailChallenge{Purpose: ChallengeStepUp, Address: addr}
+ guess := func(l *emailLimits, c *EmailChallenge, ip string) bool {
+ done, ok := l.reserveCodeGuess(c, ip)
+ done(false)
+ return ok
+ }
+
+ // A stranger spends ten wrong codes on held challenges.
+ l := newTestLimits(newLimitClock())
+ for i := 0; i < wrongCodesPerAddrDay; i++ {
+ if !guess(l, held, fmt.Sprintf("203.0.113.%d", i)) {
+ t.Fatalf("held guess %d refused early", i+1)
+ }
+ }
+ if guess(l, held, "203.0.113.200") {
+ t.Fatal("held challenge not throttled past the address cap")
+ }
+ if !guess(l, sent, "198.51.100.1") {
+ t.Fatal("held-challenge guesses locked the owner's sent challenge")
+ }
+ if !guess(l, step, "198.51.100.1") {
+ t.Fatal("sign-in guesses locked the owner's step-up")
+ }
+
+ // Ten wrong codes on sent challenges lock sent and held alike, not step-up.
+ l = newTestLimits(newLimitClock())
+ for i := 0; i < wrongCodesPerAddrDay; i++ {
+ if !guess(l, sent, fmt.Sprintf("203.0.113.%d", i)) {
+ t.Fatalf("sent guess %d refused early", i+1)
+ }
+ }
+ if guess(l, sent, "203.0.113.200") || guess(l, held, "203.0.113.200") {
+ t.Fatal("address not throttled after ten wrong codes on sent challenges")
+ }
+ if !guess(l, step, "198.51.100.1") {
+ t.Fatal("sign-in guesses locked the owner's step-up")
+ }
+
+ // Step-up's own ten lock step-up only.
+ l = newTestLimits(newLimitClock())
+ for i := 0; i < wrongCodesPerAddrDay; i++ {
+ if !guess(l, step, "198.51.100.1") {
+ t.Fatalf("step-up guess %d refused early", i+1)
+ }
+ }
+ if guess(l, step, "198.51.100.2") {
+ t.Fatal("step-up not throttled past its address cap")
+ }
+ if !guess(l, sent, "198.51.100.3") {
+ t.Fatal("step-up guesses locked sign-in")
+ }
+
+ // One IP's thirty wrong codes, across any budgets, refuse it everywhere.
+ l = newTestLimits(newLimitClock())
+ for i := 0; i < wrongCodesPerIPHour; i++ {
+ c := []*EmailChallenge{sent, held, step}[i%3]
+ c = &EmailChallenge{Purpose: c.Purpose, Address: fmt.Sprintf("u%d@example.com", i), held: c.held}
+ if !guess(l, c, "192.0.2.10") {
+ t.Fatalf("IP guess %d refused early", i+1)
+ }
+ }
+ if guess(l, &EmailChallenge{Purpose: ChallengeSignIn, Address: "fresh@example.com", held: true}, "192.0.2.10") {
+ t.Fatal("IP not throttled after thirty wrong codes")
+ }
+}
diff --git a/internal/console/emailsignin_store.go b/internal/console/emailsignin_store.go
index b16775c17..6e0ced18d 100644
--- a/internal/console/emailsignin_store.go
+++ b/internal/console/emailsignin_store.go
@@ -49,6 +49,10 @@ type EmailChallenge struct {
// row is the challenge's row key (id_hash), set by LiveEmailChallenge, so
// TakeEmailCode checks the very challenge that was read.
row string
+ // held, set by LiveEmailChallenge, is a challenge HoldEmailChallenge
+ // stored for a refused request: its code was never sent, and no code
+ // redeems it. reserveCodeGuess charges its wrong codes apart.
+ held bool
}
// CodeResult is the verdict of TakeEmailCode.
@@ -80,7 +84,8 @@ func (s *Store) migrateEmailSignin() error {
attempts INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
- flow_hash TEXT NOT NULL DEFAULT ''
+ flow_hash TEXT NOT NULL DEFAULT '',
+ held INTEGER NOT NULL DEFAULT 0
);`)
if err != nil {
return err
@@ -92,6 +97,12 @@ func (s *Store) migrateEmailSignin() error {
!strings.Contains(err.Error(), "duplicate column") {
return err
}
+ // Additive: 1 marks a held challenge (HoldEmailChallenge), whose code was
+ // never sent and never redeems. Rows from before it read 0, as they did.
+ if _, err := s.db.Exec(`ALTER TABLE email_challenges ADD COLUMN held INTEGER NOT NULL DEFAULT 0`); err != nil &&
+ !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
return nil
}
@@ -139,7 +150,7 @@ func (s *Store) CreateEmailChallenge(c EmailChallenge, now time.Time) (link, cod
if err := deleteBound(tx, c.Purpose, bindingOf(c)); err != nil {
return "", "", err
}
- if link, code, err = s.insertEmailChallenge(tx, c, now); err != nil {
+ if link, code, err = s.insertEmailChallenge(tx, c, false, now); err != nil {
return "", "", err
}
if err := tx.Commit(); err != nil {
@@ -152,7 +163,10 @@ func (s *Store) CreateEmailChallenge(c EmailChallenge, now time.Time) (link, cod
// c's binding already has a live challenge of c's purpose it changes nothing,
// so the email already sent keeps working; otherwise it stores c with a link
// and code nobody is ever told, so a typed code reads exactly as it would
-// against a sent one, and nothing the mailbox could redeem exists.
+// against a sent one, and nothing the mailbox could redeem exists. The row is
+// marked held: no code ever redeems it (TakeEmailCode), and its wrong codes
+// are charged apart from the address's sent challenges (reserveCodeGuess),
+// so guessing at it can neither sign anyone in nor lock the owner out.
func (s *Store) HoldEmailChallenge(c EmailChallenge, now time.Time) error {
col, ok := challengeBinding(c.Purpose)
if !ok {
@@ -174,7 +188,7 @@ func (s *Store) HoldEmailChallenge(c EmailChallenge, now time.Time) error {
if err := deleteBound(tx, c.Purpose, bindingOf(c)); err != nil {
return err
}
- if _, _, err := s.insertEmailChallenge(tx, c, now); err != nil {
+ if _, _, err := s.insertEmailChallenge(tx, c, true, now); err != nil {
return err
}
return tx.Commit()
@@ -192,8 +206,9 @@ func deleteBound(tx *sql.Tx, purpose, bind string) error {
}
// insertEmailChallenge mints a challenge's row key, link and code and stores
-// c under them. The row key is internal: no browser is given it.
-func (s *Store) insertEmailChallenge(tx *sql.Tx, c EmailChallenge, now time.Time) (link, code string, err error) {
+// c under them, marked held when it is HoldEmailChallenge's. The row key is
+// internal: no browser is given it.
+func (s *Store) insertEmailChallenge(tx *sql.Tx, c EmailChallenge, held bool, now time.Time) (link, code string, err error) {
row, err := randomToken()
if err != nil {
return "", "", err
@@ -211,10 +226,10 @@ func (s *Store) insertEmailChallenge(tx *sql.Tx, c EmailChallenge, now time.Time
exp = now.Add(ConfirmationTTL)
}
if _, err := tx.Exec(`INSERT INTO email_challenges
-(id_hash, link_hash, code_mac, purpose, address, session_hash, pending, next, flow_hash, attempts, created_at, expires_at)
-VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`,
+(id_hash, link_hash, code_mac, purpose, address, session_hash, pending, next, flow_hash, attempts, created_at, expires_at, held)
+VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)`,
hashToken(row), hashToken(link), s.codeMAC(hashToken(link), code), c.Purpose, c.Address,
- c.SessionHash, c.PendingHash, c.Next, c.FlowHash, now.Unix(), exp.Unix()); err != nil {
+ c.SessionHash, c.PendingHash, c.Next, c.FlowHash, now.Unix(), exp.Unix(), held); err != nil {
return "", "", err
}
return link, code, nil
@@ -246,10 +261,10 @@ func (s *Store) LiveEmailChallenge(purpose, bind string, now time.Time) (*EmailC
var row string
var c EmailChallenge
var exp int64
- err := s.db.QueryRow(`SELECT id_hash, `+challengeColumns+` FROM email_challenges
+ err := s.db.QueryRow(`SELECT id_hash, `+challengeColumns+`, held FROM email_challenges
WHERE purpose = ? AND `+col+` = ? AND expires_at >= ?
ORDER BY created_at DESC, rowid DESC LIMIT 1`, purpose, bind, now.Unix()).
- Scan(&row, &c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp)
+ Scan(&row, &c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp, &c.held)
if err != nil {
return nil, false
}
@@ -296,6 +311,7 @@ FROM email_challenges WHERE link_hash = ?`, hashToken(link)))
// meanwhile is reported CodeGone (an expired one is deleted); a wrong code
// adds an attempt, and the fifth burns the challenge (CodeBurned); a right
// code deletes it, with its binding's other challenges, and reports CodeOK.
+// On a held challenge every code is a wrong one: its code was never sent.
func (s *Store) TakeEmailCode(read *EmailChallenge, code string, now time.Time) (*EmailChallenge, CodeResult) {
if read == nil || read.row == "" {
return nil, CodeGone
@@ -307,11 +323,12 @@ func (s *Store) TakeEmailCode(read *EmailChallenge, code string, now time.Time)
defer tx.Rollback()
var mac, linkHash string
var attempts int
+ var held bool
var c EmailChallenge
var exp int64
- if err := tx.QueryRow(`SELECT `+challengeColumns+`, code_mac, link_hash, attempts
+ if err := tx.QueryRow(`SELECT `+challengeColumns+`, code_mac, link_hash, attempts, held
FROM email_challenges WHERE id_hash = ?`, read.row).
- Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp, &mac, &linkHash, &attempts); err != nil {
+ Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp, &mac, &linkHash, &attempts, &held); err != nil {
return nil, CodeGone
}
c.ExpiresAt = time.Unix(exp, 0)
@@ -329,7 +346,7 @@ FROM email_challenges WHERE id_hash = ?`, read.row).
if !strings.HasPrefix(mac, s.codeEpoch+":") {
return nil, CodeGone
}
- if !hmac.Equal([]byte(mac), []byte(s.codeMAC(linkHash, code))) {
+ if held || !hmac.Equal([]byte(mac), []byte(s.codeMAC(linkHash, code))) {
attempts++
res := CodeWrong
if attempts >= emailCodeAttempts {
diff --git a/internal/console/emailsignin_store_test.go b/internal/console/emailsignin_store_test.go
index 6114c700a..007f961af 100644
--- a/internal/console/emailsignin_store_test.go
+++ b/internal/console/emailsignin_store_test.go
@@ -463,3 +463,43 @@ func TestKnownAddress(t *testing.T) {
}
}
}
+
+// A held challenge (HoldEmailChallenge) never redeems a code, not even its
+// own (H4-M6): nobody was sent it, so a right guess must not sign anyone in.
+func TestHeldChallengeNeverRedeemsACode(t *testing.T) {
+ st := openTestStore(t)
+ now := time.Now()
+ c := EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("flow")}
+ tx, err := st.db.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, code, err := st.insertEmailChallenge(tx, c, true, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ live, ok := st.LiveEmailChallenge(ChallengeSignIn, c.FlowHash, now)
+ if !ok || !live.held {
+ t.Fatalf("live held challenge = %+v, %v; want held", live, ok)
+ }
+ if got, res := st.TakeEmailCode(live, code, now); res != CodeWrong || got != nil {
+ t.Fatalf("held challenge's own code = %v, %v; want CodeWrong", got, res)
+ }
+
+ // HoldEmailChallenge marks its row held; a sent one is not.
+ if err := st.HoldEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("other")}, now); err != nil {
+ t.Fatal(err)
+ }
+ if h, ok := st.LiveEmailChallenge(ChallengeSignIn, hashToken("other"), now); !ok || !h.held {
+ t.Fatalf("HoldEmailChallenge row = %+v, %v; want held", h, ok)
+ }
+ if _, _, err := st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("sent")}, now); err != nil {
+ t.Fatal(err)
+ }
+ if s, ok := st.LiveEmailChallenge(ChallengeSignIn, hashToken("sent"), now); !ok || s.held {
+ t.Fatalf("CreateEmailChallenge row = %+v, %v; want not held", s, ok)
+ }
+}
diff --git a/internal/console/hunt_H4-M6_test.go b/internal/console/hunt_H4-M6_test.go
new file mode 100644
index 000000000..ed7f3eda3
--- /dev/null
+++ b/internal/console/hunt_H4-M6_test.go
@@ -0,0 +1,108 @@
+package console
+
+// Hunt H4-M6 (verifier, opus): an unauthenticated client that knows only a
+// victim's address opens its own sign-in flows for that address and spends
+// the address-wide wrong-code budget (10 a day) with junk codes. The victim's
+// own correct code, in its own flow from another IP, is then refused.
+//
+// The assertions are the SECURE behaviour (the victim's right code still signs
+// in / still confirms the step-up). They fail on current code.
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+const huntM6AttackerAddr = "203.0.113.66:40000"
+
+// huntM6Attacker posts form to path through the production router from a
+// non-loopback client holding only its own flow cookie. It sends neither
+// Origin nor Sec-Fetch-Site, as a script would (sameOrigin lets that pass).
+func huntM6Attacker(t *testing.T, fx *consoleFixture, flow, path string, form url.Values) (int, string) {
+ t.Helper()
+ r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
+ r.RemoteAddr = huntM6AttackerAddr
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.AddCookie(&http.Cookie{Name: flowCookie, Value: flow})
+ w := httptest.NewRecorder()
+ fx.srv.ServeHTTP(w, r)
+ return w.Code, w.Body.String()
+}
+
+// huntM6Burn is the attack: two attacker flows for addr, five junk codes in
+// each. Twelve requests from one IP.
+func huntM6Burn(t *testing.T, fx *consoleFixture, addr string) {
+ t.Helper()
+ for _, flow := range []string{
+ "attacker-flow-one-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "attacker-flow-two-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ } {
+ status, body := huntM6Attacker(t, fx, flow, "/auth/continue", url.Values{"address": {addr}})
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("check.sent", "address", addr))) {
+ t.Fatalf("attacker continue = %d:\n%s", status, body)
+ }
+ for i := 1; i <= emailCodeAttempts; i++ {
+ status, body := huntM6Attacker(t, fx, flow, "/auth/email/code", url.Values{"code": {"zzzzzz"}})
+ want := "check.code_wrong"
+ if i == emailCodeAttempts {
+ want = "check.code_used_up"
+ }
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText(want))) {
+ t.Fatalf("attacker junk code %d = %d, want %s:\n%s", i, status, want, body)
+ }
+ }
+ }
+}
+
+func TestHunt_H4_M6_SigninCodeLockout(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "victim@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ victim := newBrowser(t)
+ code, link := askSignin(t, fx, m, victim, addr, "")
+
+ huntM6Burn(t, fx, addr)
+ if n := len(m.sentCopy()); n != 1 {
+ t.Logf("console mailer sent %d messages (the attacker's flows were held, not sent)", n)
+ }
+
+ // SECURE: the victim's own right code, in the victim's own flow and from
+ // the victim's own IP, signs the victim in.
+ status, loc, body := postCode(t, fx, victim, code)
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ throttled := strings.Contains(body, esc(copyText("check.code_throttled")))
+ t.Errorf("H4-M6: victim's correct sign-in code after an attacker's 10 junk codes from %s = %d -> %q (throttled page: %v); want 303 into an account",
+ huntM6AttackerAddr, status, loc, throttled)
+ }
+
+ // Residual (not the assertion under test): the emailed link still works.
+ if signedOut(t, fx, victim) {
+ other := newBrowser(t)
+ _, _, nonce := openLink(t, fx, other, link)
+ if status, loc, _ := postLink(t, fx, other, link, nonce); status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ t.Errorf("link after lockout = %d -> %q", status, loc)
+ } else {
+ t.Log("the emailed link still signs in after the lockout")
+ }
+ }
+}
+
+func TestHunt_H4_M6_StepUpCodeLockout(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ c := newBrowser(t)
+ raw, base := emailOwnerWorld(t, fx, m, c)
+ code, _ := askStepUp(t, fx, m, c, raw, base)
+
+ huntM6Burn(t, fx, "bob@example.com")
+
+ // SECURE: bob's right step-up code confirms the held removal.
+ status, loc, body := postStepUpCode(t, fx, c, code)
+ if status != http.StatusSeeOther || loc != base+"/team" {
+ throttled := strings.Contains(body, esc(copyText("check.code_throttled")))
+ t.Errorf("H4-M6: victim's correct step-up code after an attacker's 10 junk sign-in codes = %d -> %q (throttled page: %v); want 303 -> %s/team",
+ status, loc, throttled, base)
+ }
+}