Count sign-in attempts per address and client, guard the sign-in form with a token, ration both forms per address
A wrong password from anywhere counted against the address, so ten locked its owner out. Attempts are now counted per address and client, with a looser bound per address alone. The sign-in form carries a token matched by a cookie (login CSRF). POST /login and /signup are rationed per client address, a hash waits at most ten seconds for a turn, and server init writes signup_open: false. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
f1b49d0251
commit
44cd58005a
11 files changed
+312
-22
No files matched your search
+21
-7
@@ -135,10 +135,12 @@ func NewAccountPages(a Accounts, k KeyOwner, pw account.PasswordChanger,
|
||||
func (p *AccountPages) Register(mux *http.ServeMux) {
|
||||
if p.accounts.SignupOpen() {
|
||||
mux.HandleFunc("GET /signup", p.signupForm)
|
||||
mux.HandleFunc("POST /signup", p.signup)
|
||||
// Each signup costs a password hash and a row: a few a minute from
|
||||
// one address is a person, more is a script.
|
||||
mux.HandleFunc("POST /signup", rationed(newRation(5, 10), p.signup))
|
||||
}
|
||||
mux.HandleFunc("GET /login", p.loginForm)
|
||||
mux.HandleFunc("POST /login", p.login)
|
||||
mux.HandleFunc("POST /login", rationed(newRation(30, 30), p.login))
|
||||
mux.HandleFunc("POST /logout", p.logout)
|
||||
mux.HandleFunc("GET /profile", p.profile)
|
||||
mux.HandleFunc("POST /profile/keys", p.createKey)
|
||||
@@ -196,25 +198,37 @@ type loginData struct {
|
||||
Email, Error string
|
||||
SignupOpen bool
|
||||
Version string
|
||||
// CSRF is the form's token, matched by a cookie.
|
||||
CSRF string
|
||||
}
|
||||
|
||||
func (p *AccountPages) loginForm(w http.ResponseWriter, _ *http.Request) {
|
||||
func (p *AccountPages) loginForm(w http.ResponseWriter, r *http.Request) {
|
||||
noStore(w)
|
||||
render(w, "login", loginData{SignupOpen: p.accounts.SignupOpen(), Version: p.version})
|
||||
render(w, "login", loginData{SignupOpen: p.accounts.SignupOpen(), Version: p.version, CSRF: setLoginToken(w, r)})
|
||||
}
|
||||
|
||||
func (p *AccountPages) login(w http.ResponseWriter, r *http.Request) {
|
||||
noStore(w)
|
||||
email := strings.TrimSpace(r.FormValue("email"))
|
||||
if !loginTokenOK(r) {
|
||||
// Not this site's form: another one posting a visitor into an
|
||||
// account of its choosing, or a form left open past its hour.
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render(w, "login", loginData{Email: email, SignupOpen: p.accounts.SignupOpen(), Version: p.version,
|
||||
Error: "the form had expired; sign in again", CSRF: setLoginToken(w, r)})
|
||||
return
|
||||
}
|
||||
|
||||
token, csrf, err := p.accounts.SignIn(r.Context(), email, r.FormValue("password"))
|
||||
ctx := account.WithClient(r.Context(), clientAddr(r))
|
||||
token, csrf, err := p.accounts.SignIn(ctx, email, r.FormValue("password"))
|
||||
if err != nil {
|
||||
d := loginData{Email: email, SignupOpen: p.accounts.SignupOpen(), Version: p.version}
|
||||
d := loginData{Email: email, SignupOpen: p.accounts.SignupOpen(), Version: p.version, CSRF: setLoginToken(w, r)}
|
||||
switch {
|
||||
case errors.Is(err, account.ErrBadCredentials),
|
||||
errors.Is(err, account.ErrNotApproved),
|
||||
errors.Is(err, account.ErrSuspended),
|
||||
errors.Is(err, account.ErrTooManyTries):
|
||||
errors.Is(err, account.ErrTooManyTries),
|
||||
errors.Is(err, account.ErrBusy):
|
||||
d.Error = err.Error()
|
||||
default:
|
||||
p.log.Error("sign-in failed", "err", err)
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The sign-in and signup forms are the two a browser posts before it has a
|
||||
// session: nothing ties them to the person in front of it, and nothing slows
|
||||
// a script posting them. Two guards: a token the form carries and a cookie
|
||||
// matches, so another site cannot sign a visitor into an account of its
|
||||
// choosing; and a ration per client address, so a script cannot spend the
|
||||
// password hasher, the database or an address's attempts at the rate it can
|
||||
// send.
|
||||
|
||||
// loginCSRFCookie is the sign-in form's token, before there is a session.
|
||||
const loginCSRFCookie = "llmgw_login_csrf"
|
||||
|
||||
// newFormToken is a token for one form.
|
||||
func newFormToken() string {
|
||||
b := make([]byte, 16)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// setLoginToken gives the sign-in form its token and the browser its match.
|
||||
func setLoginToken(w http.ResponseWriter, r *http.Request) string {
|
||||
t := newFormToken()
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: loginCSRFCookie, Value: t, Path: "/login",
|
||||
HttpOnly: true, Secure: isHTTPS(r), SameSite: http.SameSiteStrictMode, MaxAge: 3600,
|
||||
})
|
||||
return t
|
||||
}
|
||||
|
||||
// loginTokenOK reports whether a posted sign-in form carries the token its
|
||||
// cookie does.
|
||||
func loginTokenOK(r *http.Request) bool {
|
||||
c, err := r.Cookie(loginCSRFCookie)
|
||||
if err != nil || c.Value == "" {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(c.Value), []byte(r.FormValue("csrf"))) == 1
|
||||
}
|
||||
|
||||
// ration is a token bucket per client address.
|
||||
type ration struct {
|
||||
mu sync.Mutex
|
||||
rate float64 // a second
|
||||
burst float64
|
||||
by map[string]*allowance
|
||||
}
|
||||
|
||||
type allowance struct {
|
||||
tokens float64
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func newRation(perMinute, burst float64) *ration {
|
||||
return &ration{rate: perMinute / 60, burst: burst, by: map[string]*allowance{}}
|
||||
}
|
||||
|
||||
func (q *ration) allow(client string, now time.Time) bool {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
if len(q.by) > 50_000 {
|
||||
for k, v := range q.by {
|
||||
if now.Sub(v.at).Seconds()*q.rate >= q.burst {
|
||||
delete(q.by, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
a, ok := q.by[client]
|
||||
if !ok {
|
||||
a = &allowance{tokens: q.burst, at: now}
|
||||
q.by[client] = a
|
||||
}
|
||||
a.tokens = min(q.burst, a.tokens+now.Sub(a.at).Seconds()*q.rate)
|
||||
a.at = now
|
||||
if a.tokens < 1 {
|
||||
return false
|
||||
}
|
||||
a.tokens--
|
||||
return true
|
||||
}
|
||||
|
||||
// rationed refuses a client past its ration with 429 before next runs.
|
||||
func rationed(q *ration, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !q.allow(clientAddr(r), time.Now()) {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
http.Error(w, "too many attempts from this address; wait a minute", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// clientAddr is the address a request came from, without its port.
|
||||
func clientAddr(r *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
@@ -52,3 +52,48 @@ func TestASignupSaysWhatToDoIfTheAddressHadAnAccount(t *testing.T) {
|
||||
t.Errorf("the done page leaves someone who already had an account stuck: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheSignInFormWantsItsOwnTokenAndRationsAnAddress(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
NewAccountPages(signupAccounts{}, nil, nil, "v0", slog.New(slog.DiscardHandler)).Register(mux)
|
||||
post := func(form url.Values, cookie *http.Cookie) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.RemoteAddr = "203.0.113.9:1234"
|
||||
if cookie != nil {
|
||||
req.AddCookie(cookie)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
// No token: another site's form.
|
||||
if rec := post(url.Values{"email": {"a@b.c"}, "password": {"x"}}, nil); rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("a sign-in without the form's token: %d", rec.Code)
|
||||
}
|
||||
// The form's token, matched by its cookie, reaches the sign-in.
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil))
|
||||
var cookie *http.Cookie
|
||||
for _, c := range rec.Result().Cookies() {
|
||||
if c.Name == loginCSRFCookie {
|
||||
cookie = c
|
||||
}
|
||||
}
|
||||
if cookie == nil || !strings.Contains(rec.Body.String(), cookie.Value) {
|
||||
t.Fatal("the form carries no token")
|
||||
}
|
||||
if rec := post(url.Values{"email": {"a@b.c"}, "password": {"x"}, "csrf": {cookie.Value}}, cookie); rec.Code == http.StatusBadRequest {
|
||||
t.Errorf("the form's own token was refused")
|
||||
}
|
||||
// A script posting it is rationed.
|
||||
limited := false
|
||||
for range 40 {
|
||||
if post(url.Values{"csrf": {cookie.Value}}, cookie).Code == http.StatusTooManyRequests {
|
||||
limited = true
|
||||
}
|
||||
}
|
||||
if !limited {
|
||||
t.Error("forty sign-ins a moment from one address were all taken")
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@ an operator to reset it.</p>
|
||||
|
||||
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
|
||||
<form method="post" autocomplete="on">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<label>Email<input type="email" name="email" value="{{.Email}}" required autocomplete="email"></label>
|
||||
<label>Password<input type="password" name="password" required autocomplete="current-password"></label>
|
||||
<button type="submit">Sign in</button>
|
||||
|
||||
Reference in new issue
Block a user