Files
2026-12-04 23:49:29 +01:00

99 lines
2.5 KiB
Go

package service
import (
"sync"
"time"
)
const (
// mfaWrongCodes is how many wrong MFA codes in a row an account may give
mfaWrongCodes = 5
// mfaWrongCodeEvery is how long it takes until one more wrong code may
// be given
mfaWrongCodeEvery = 3 * time.Minute
)
// mfaAttemptCounter counts the wrong TOTP and recovery codes of each account.
// The count is per account and not per IP, so guessing a code from many
// addresses does not give more guesses. Only a caller that has the password
// or a session of the account gets to give a code.
type mfaAttemptCounter struct {
mu sync.Mutex
// used holds for each account the attempts in use and when that count
// was last brought up to date. An account with none in use has no entry.
used map[string]*mfaAttemptsUsed
lastSweep time.Time
}
type mfaAttemptsUsed struct {
count float64
at time.Time
}
var mfaAttempts = &mfaAttemptCounter{used: map[string]*mfaAttemptsUsed{}}
// current brings the count of the entry up to now, one attempt comes back
// each mfaWrongCodeEvery
func (e *mfaAttemptsUsed) current(now time.Time) float64 {
if gone := now.Sub(e.at); gone > 0 {
e.count -= float64(gone) / float64(mfaWrongCodeEvery)
if e.count < 0 {
e.count = 0
}
}
e.at = now
return e.count
}
// take takes one attempt of the account before a code is checked, so codes
// checked at the same time can not go past the limit. ok is false when no
// attempt is left. giveBack returns the attempt, call it when the code was
// right.
func (c *mfaAttemptCounter) take(userID string) (giveBack func(), ok bool) {
now := time.Now()
c.mu.Lock()
defer c.mu.Unlock()
c.sweep(now)
e := c.used[userID]
if e == nil {
e = &mfaAttemptsUsed{at: now}
c.used[userID] = e
}
if e.current(now)+1 > mfaWrongCodes {
return nil, false
}
e.count++
var once sync.Once
return func() {
once.Do(func() {
c.mu.Lock()
defer c.mu.Unlock()
if e := c.used[userID]; e != nil {
e.count--
if e.count < 0 {
e.count = 0
}
}
})
}, true
}
// sweep drops the accounts with no attempt in use, at most once a minute.
// The caller holds the lock.
func (c *mfaAttemptCounter) sweep(now time.Time) {
if now.Sub(c.lastSweep) < time.Minute {
return
}
c.lastSweep = now
for id, e := range c.used {
if e.current(now) == 0 {
delete(c.used, id)
}
}
}
// takeMFAAttempt takes one attempt of the account, see mfaAttemptCounter.take
func takeMFAAttempt(userID string) (giveBack func(), ok bool) {
return mfaAttempts.take(userID)
}