From f88cc9355ecaae2b4ce1f1713f5f6198d7c2cf55 Mon Sep 17 00:00:00 2001 From: ssenerg Date: Sun, 25 Oct 2026 17:59:57 +0330 Subject: [PATCH] Let users sign in with a code from an authenticator app too Users can turn on two-factor sign-in under Two-factor sign-in in their account menu: they add a secret to an authenticator app by QR code or by hand, and confirm it with a code (TOTP, RFC 6238, implemented here). That signs them out everywhere else and shows ten recovery codes once, each good for one sign-in. Signing in then asks for a code after the password; a sign-in waits for it five minutes, five tries at most, and wrong codes count against the client's budget. No code works twice. Scripts send the code with the password, or answer the challenge the login returns. Turning it off and making new recovery codes take the password. Superadmins, or goftp user two-factor-off, turn it off for someone who lost their app. App passwords are unchanged. Co-Authored-By: Claude Opus 5.5 --- README.md | 31 +- go.mod | 1 + go.sum | 2 + internal/auth/authtest/store.go | 117 ++++++- internal/auth/export_test.go | 4 + internal/auth/postgres.go | 98 +++++- internal/auth/service.go | 19 +- internal/auth/store.go | 32 ++ internal/auth/twofactor.go | 386 ++++++++++++++++++++++ internal/auth/twofactor_test.go | 221 +++++++++++++ internal/cli/cli.go | 23 +- internal/cli/cli_test.go | 4 + internal/db/db_test.go | 2 +- internal/db/migrations/010_two_factor.sql | 14 + internal/server/admin.go | 13 +- internal/server/auth.go | 29 +- internal/server/server.go | 2 + internal/server/templates/admin.html | 12 +- internal/server/templates/base.html | 9 + internal/server/templates/login.html | 16 + internal/server/templates/twofactor.html | 89 +++++ internal/server/twofactor.go | 284 ++++++++++++++++ internal/server/twofactor_test.go | 219 ++++++++++++ 23 files changed, 1604 insertions(+), 23 deletions(-) create mode 100644 internal/auth/export_test.go create mode 100644 internal/auth/twofactor.go create mode 100644 internal/auth/twofactor_test.go create mode 100644 internal/db/migrations/010_two_factor.sql create mode 100644 internal/server/templates/twofactor.html create mode 100644 internal/server/twofactor.go create mode 100644 internal/server/twofactor_test.go diff --git a/README.md b/README.md index 27f02d4..7d4ab0f 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ access to the database: goftp user add bob --role operator # prints a temporary password goftp user list goftp user passwd bob # new temporary password, ends bob's sessions +goftp user two-factor-off bob # for when he lost his app and recovery codes goftp user role bob admin goftp user quota bob 10GiB # how much his home may hold; none, or default goftp user delete bob # their home goes to the trash @@ -83,6 +84,23 @@ New and reset passwords are temporary: after signing in, users can do nothing but choose their own password (at least 12 characters), which ends all their other sessions. +### Two-factor sign-in + +Users can have signing in take a code from an authenticator app after +their password, under **Two-factor sign-in** in their account menu: they +scan a QR code (or type its key) into the app, and give the code it shows +to turn it on. That signs them out everywhere else, and shows 10 recovery +codes once, each of which works once instead of a code, for a lost phone; +new ones replace them, given the password. Codes are TOTP (RFC 6238: 6 +digits, 30 seconds, SHA-1, as apps expect), accepted 30 seconds early or +late, and none works twice. Turning it off takes the password too. Wrong +codes count against the client's sign-in budget, and a sign-in waits for +its code 5 minutes, 5 tries at most. For someone who lost both, a superadmin +turns it off under **Users** (marked *two-factor*), or with +`goftp user two-factor-off NAME`. App passwords still sign apps in over +WebDAV without a code: they are made by a user already signed in, for one +app each, and are revoked alone. + | Role | May | |--------------|-----------------------------------------------------------------------------------------| | `user` | list directories and download (`read`) | @@ -228,6 +246,15 @@ curl -s -H 'Content-Type: application/json' \ curl -C - -O -H "Authorization: Bearer $TOKEN" https://host/dir/file.iso ``` +With two-factor sign-in, add `"code"` (from the app, or a recovery code). +Without it, the answer is `401` with +`{"two_factor":true,"challenge":"..."}`; send +`{"challenge":"...","code":"..."}` within 5 minutes instead of the +password. Scripts turn it on with `action=start` (which answers with the +`secret` and `otpauth://` `uri` for the app) and then `action=confirm` +with `code` (answering with the `recovery_codes` and a new `token`), and +off with `action=off` and `password`, all on `POST /.auth/two-factor`. + A temporary password is changed with `POST /.auth/password` (`{"current_password":"...","new_password":"..."}`), which returns a new token. `POST /.auth/logout` ends the session. Sessions last @@ -497,7 +524,9 @@ Wrong app passwords count against the client's sign-in budget sends `X-Forwarded-Proto`) the session cookie is `Secure` and `__Host-` prefixed, and HSTS is sent. - Passwords are hashed with Argon2id; only SHA-256 hashes of session tokens - are stored. + and recovery codes are stored. Two-factor secrets are stored as they + are, as codes are made from them: whoever reads the database can make + codes, but still needs the password. - Failed sign-ins (and wrong current passwords) are rate limited per client (`limiter.*`), and each user can sign in at most 30 times a minute. Behind a reverse proxy, set `server.proxy_header` (`X-Forwarded-For`) diff --git a/go.mod b/go.mod index 1d39f59..8491844 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( golang.org/x/image v0.46.0 golang.org/x/sys v0.48.0 golang.org/x/text v0.42.0 + rsc.io/qr v0.2.0 ) require ( diff --git a/go.sum b/go.sum index 9e66085..af947ae 100644 --- a/go.sum +++ b/go.sum @@ -117,3 +117,5 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY= +rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs= diff --git a/internal/auth/authtest/store.go b/internal/auth/authtest/store.go index ae02294..3fba604 100644 --- a/internal/auth/authtest/store.go +++ b/internal/auth/authtest/store.go @@ -2,6 +2,7 @@ package authtest import ( + "bytes" "cmp" "context" "slices" @@ -21,6 +22,14 @@ type Store struct { uploads map[string]*upload // by token hash apps map[string]*auth.AppPassword // by token hash folders map[int64]*auth.FolderShare // by ID + factors map[int64]*twoFactor // by user ID +} + +// twoFactor is what is kept of a user's two-factor sign-in. +type twoFactor struct { + secret, pending []byte + step int64 + codes map[string]bool // recovery codes, by hash } type upload struct { @@ -38,7 +47,8 @@ var _ auth.Store = (*Store)(nil) func NewStore() *Store { return &Store{users: make(map[int64]*auth.User), sessions: make(map[string]session), shares: make(map[string]*auth.Share), - uploads: make(map[string]*upload), apps: make(map[string]*auth.AppPassword), folders: make(map[int64]*auth.FolderShare)} + uploads: make(map[string]*upload), apps: make(map[string]*auth.AppPassword), folders: make(map[int64]*auth.FolderShare), + factors: make(map[int64]*twoFactor)} } // NewService returns a service with an empty store and the default policy. @@ -111,6 +121,110 @@ func (s *Store) SetPassword(_ context.Context, userID int64, passwordHash string return nil } +// factor returns the two-factor sign-in of userID, made if need be. +func (s *Store) factor(userID int64) (*twoFactor, error) { + if _, ok := s.users[userID]; !ok { + return nil, auth.ErrNotFound + } + tf := s.factors[userID] + if tf == nil { + tf = &twoFactor{codes: map[string]bool{}} + s.factors[userID] = tf + } + return tf, nil +} + +func (s *Store) TwoFactor(_ context.Context, userID int64) (*auth.TwoFactor, error) { + s.mu.Lock() + defer s.mu.Unlock() + tf, err := s.factor(userID) + if err != nil { + return nil, err + } + return &auth.TwoFactor{Secret: tf.secret, Pending: tf.pending, Step: tf.step, RecoveryCodes: len(tf.codes)}, nil +} + +func (s *Store) SetTwoFactorPending(_ context.Context, userID int64, secret []byte) error { + s.mu.Lock() + defer s.mu.Unlock() + tf, err := s.factor(userID) + if err == nil { + tf.pending = secret + } + return err +} + +func (s *Store) EnableTwoFactor(_ context.Context, userID int64, secret []byte, step int64, hashes [][]byte) error { + s.mu.Lock() + defer s.mu.Unlock() + tf, err := s.factor(userID) + if err != nil { + return err + } + if tf.secret != nil || !bytes.Equal(tf.pending, secret) { + return auth.ErrNotFound + } + tf.secret, tf.pending, tf.step = secret, nil, step + s.users[userID].TwoFactor = true + s.deleteSessions(userID) + s.setCodes(tf, hashes) + return nil +} + +func (s *Store) setCodes(tf *twoFactor, hashes [][]byte) { + tf.codes = map[string]bool{} + for _, h := range hashes { + tf.codes[string(h)] = true + } +} + +func (s *Store) DisableTwoFactor(_ context.Context, userID int64) error { + s.mu.Lock() + defer s.mu.Unlock() + if _, err := s.factor(userID); err != nil { + return err + } + delete(s.factors, userID) + s.users[userID].TwoFactor = false + return nil +} + +func (s *Store) UseTwoFactorStep(_ context.Context, userID, step int64) (bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + tf, err := s.factor(userID) + if err != nil || tf.secret == nil || tf.step >= step { + return false, err + } + tf.step = step + return true, nil +} + +func (s *Store) UseRecoveryCode(_ context.Context, userID int64, hash []byte) (bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + tf, err := s.factor(userID) + if err != nil || !tf.codes[string(hash)] { + return false, err + } + delete(tf.codes, string(hash)) + return true, nil +} + +func (s *Store) SetRecoveryCodes(_ context.Context, userID int64, hashes [][]byte) error { + s.mu.Lock() + defer s.mu.Unlock() + tf, err := s.factor(userID) + if err != nil { + return err + } + if tf.secret == nil { + return auth.ErrNotFound + } + s.setCodes(tf, hashes) + return nil +} + func (s *Store) SetHomeQuota(_ context.Context, userID int64, quota *int64) error { s.mu.Lock() defer s.mu.Unlock() @@ -133,6 +247,7 @@ func (s *Store) DeleteUser(_ context.Context, userID int64) error { return auth.ErrNotFound } delete(s.users, userID) + delete(s.factors, userID) s.deleteSessions(userID) s.deleteShares(userID) s.deleteApps(userID) diff --git a/internal/auth/export_test.go b/internal/auth/export_test.go new file mode 100644 index 0000000..9448a9f --- /dev/null +++ b/internal/auth/export_test.go @@ -0,0 +1,4 @@ +package auth + +// TOTPCode is the code of secret for the time step, for tests. +var TOTPCode = totpCode diff --git a/internal/auth/postgres.go b/internal/auth/postgres.go index 58dc9a6..742bd06 100644 --- a/internal/auth/postgres.go +++ b/internal/auth/postgres.go @@ -21,11 +21,11 @@ type PgStore struct{ db *pgxpool.Pool } func NewPgStore(db *pgxpool.Pool) *PgStore { return &PgStore{db: db} } -const userColumns = "id, username, password_hash, must_change_password, created_at, home_quota" +const userColumns = "id, username, password_hash, must_change_password, created_at, home_quota, totp_secret IS NOT NULL" func scanUser(row pgx.Row) (*User, error) { var u User - err := row.Scan(&u.ID, &u.Username, &u.PasswordHash, &u.MustChangePassword, &u.CreatedAt, &u.HomeQuota) + err := row.Scan(&u.ID, &u.Username, &u.PasswordHash, &u.MustChangePassword, &u.CreatedAt, &u.HomeQuota, &u.TwoFactor) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } @@ -141,8 +141,9 @@ func (s *PgStore) AppPasswordUser(ctx context.Context, username string, tokenHas lastUsed *time.Time ) err := s.db.QueryRow(ctx, `SELECT u.id, u.username, u.password_hash, u.must_change_password, u.created_at, u.home_quota, - a.last_used_at FROM app_passwords a JOIN users u ON u.id = a.user_id WHERE a.token_hash = $1 AND u.username = $2`, - tokenHash, username).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.MustChangePassword, &u.CreatedAt, &u.HomeQuota, &lastUsed) + u.totp_secret IS NOT NULL, a.last_used_at FROM app_passwords a JOIN users u ON u.id = a.user_id + WHERE a.token_hash = $1 AND u.username = $2`, + tokenHash, username).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.MustChangePassword, &u.CreatedAt, &u.HomeQuota, &u.TwoFactor, &lastUsed) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } @@ -231,6 +232,91 @@ func (s *PgStore) MoveFolderShare(ctx context.Context, id int64, p string) error }) } +func (s *PgStore) TwoFactor(ctx context.Context, userID int64) (*TwoFactor, error) { + var tf TwoFactor + err := s.db.QueryRow(ctx, `SELECT totp_secret, totp_pending, totp_step, + (SELECT count(*) FROM recovery_codes WHERE user_id = users.id) FROM users WHERE id = $1`, userID). + Scan(&tf.Secret, &tf.Pending, &tf.Step, &tf.RecoveryCodes) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return &tf, nil +} + +func (s *PgStore) SetTwoFactorPending(ctx context.Context, userID int64, secret []byte) error { + tag, err := s.db.Exec(ctx, "UPDATE users SET totp_pending = $2 WHERE id = $1", userID, secret) + if err == nil && tag.RowsAffected() == 0 { + err = ErrNotFound + } + return err +} + +func (s *PgStore) EnableTwoFactor(ctx context.Context, userID int64, secret []byte, step int64, hashes [][]byte) error { + return pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error { + tag, err := tx.Exec(ctx, `UPDATE users SET totp_secret = totp_pending, totp_pending = NULL, totp_step = $3 + WHERE id = $1 AND totp_pending = $2 AND totp_secret IS NULL`, userID, secret, step) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + if _, err := tx.Exec(ctx, "DELETE FROM sessions WHERE user_id = $1", userID); err != nil { + return err + } + return setRecoveryCodes(ctx, tx, userID, hashes) + }) +} + +func (s *PgStore) DisableTwoFactor(ctx context.Context, userID int64) error { + return pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error { + tag, err := tx.Exec(ctx, "UPDATE users SET totp_secret = NULL, totp_pending = NULL, totp_step = 0 WHERE id = $1", userID) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + _, err = tx.Exec(ctx, "DELETE FROM recovery_codes WHERE user_id = $1", userID) + return err + }) +} + +func (s *PgStore) UseTwoFactorStep(ctx context.Context, userID, step int64) (bool, error) { + tag, err := s.db.Exec(ctx, "UPDATE users SET totp_step = $2 WHERE id = $1 AND totp_step < $2 AND totp_secret IS NOT NULL", userID, step) + return err == nil && tag.RowsAffected() == 1, err +} + +func (s *PgStore) UseRecoveryCode(ctx context.Context, userID int64, hash []byte) (bool, error) { + tag, err := s.db.Exec(ctx, "DELETE FROM recovery_codes WHERE user_id = $1 AND code_hash = $2", userID, hash) + return err == nil && tag.RowsAffected() == 1, err +} + +func (s *PgStore) SetRecoveryCodes(ctx context.Context, userID int64, hashes [][]byte) error { + return pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error { + var on bool + err := tx.QueryRow(ctx, "SELECT totp_secret IS NOT NULL FROM users WHERE id = $1 FOR UPDATE", userID).Scan(&on) + if errors.Is(err, pgx.ErrNoRows) || err == nil && !on { + return ErrNotFound + } + if err != nil { + return err + } + return setRecoveryCodes(ctx, tx, userID, hashes) + }) +} + +func setRecoveryCodes(ctx context.Context, tx pgx.Tx, userID int64, hashes [][]byte) error { + if _, err := tx.Exec(ctx, "DELETE FROM recovery_codes WHERE user_id = $1", userID); err != nil { + return err + } + _, err := tx.Exec(ctx, "INSERT INTO recovery_codes (user_id, code_hash) SELECT $1, unnest($2::bytea[])", userID, hashes) + return err +} + func (s *PgStore) SetHomeQuota(ctx context.Context, userID int64, quota *int64) error { tag, err := s.db.Exec(ctx, "UPDATE users SET home_quota = $2 WHERE id = $1", userID, quota) if err == nil && tag.RowsAffected() == 0 { @@ -272,8 +358,8 @@ func (s *PgStore) CreateSession(ctx context.Context, tokenHash []byte, u *User, } func (s *PgStore) SessionUser(ctx context.Context, tokenHash []byte) (*User, error) { - return scanUser(s.db.QueryRow(ctx, `SELECT u.id, u.username, u.password_hash, u.must_change_password, u.created_at, u.home_quota - FROM sessions s JOIN users u ON u.id = s.user_id + return scanUser(s.db.QueryRow(ctx, `SELECT u.id, u.username, u.password_hash, u.must_change_password, u.created_at, u.home_quota, + u.totp_secret IS NOT NULL FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now()`, tokenHash)) } diff --git a/internal/auth/service.go b/internal/auth/service.go index 6656730..96fe582 100644 --- a/internal/auth/service.go +++ b/internal/auth/service.go @@ -44,6 +44,8 @@ type Service struct { homes atomic.Value // the folder of users' homes (see SetHomes) fold atomic.Value // how rules compare paths (see SetFold) + + challenges challenges // sign-ins that wait for a two-factor code } func NewService(store Store, enforcer *casbin.SyncedEnforcer, sessionTTL time.Duration) *Service { @@ -110,10 +112,18 @@ type Session struct { Token string Expires time.Time User *User + // RecoveryCode is set when the user signed in with a recovery code. + RecoveryCode bool } -// Login checks the credentials and starts a session. +// Login checks the credentials and starts a session; for users with +// two-factor sign-in, see LoginWithCode. func (s *Service) Login(ctx context.Context, username, password string) (*Session, error) { + return s.LoginWithCode(ctx, username, password, "") +} + +// checkLogin checks the credentials and returns their user. +func (s *Service) checkLogin(ctx context.Context, username, password string) (*User, error) { username = NormalizeUsername(username) if checkUsername(username) != nil { return nil, ErrNoSuchUser @@ -134,12 +144,7 @@ func (s *Service) Login(ctx context.Context, username, password string) (*Sessio case !ok: return nil, errWrongPassword } - sess, err := s.newSession(ctx, u) - if errors.Is(err, ErrNotFound) { - // Changed (or the user was deleted) since it was checked. - return nil, errChangedMeanwhile - } - return sess, err + return u, nil } func (s *Service) newSession(ctx context.Context, u *User) (*Session, error) { diff --git a/internal/auth/store.go b/internal/auth/store.go index 6351385..2efc1c5 100644 --- a/internal/auth/store.go +++ b/internal/auth/store.go @@ -22,6 +22,17 @@ type User struct { // HomeQuota is how much their home may hold, in bytes: nil for the // server's default, 0 for no limit. HomeQuota *int64 + // TwoFactor is set when they sign in with a code too (see + // LoginWithCode). + TwoFactor bool +} + +// TwoFactor is what is stored of a user's two-factor sign-in. +type TwoFactor struct { + Secret []byte // nil while it is off + Pending []byte // a secret being set up, until a code of it comes; nil if none + Step int64 // the last time step a code was used for + RecoveryCodes int // how many are left } // Share is a link that lets people without an account read a file or @@ -116,6 +127,27 @@ type Store interface { // folder that is gone left (ErrNotFound if there is no share id). MoveFolderShare(ctx context.Context, id int64, p string) error + // TwoFactor returns what is stored of userID's two-factor sign-in + // (ErrNotFound if there is no such user). + TwoFactor(ctx context.Context, userID int64) (*TwoFactor, error) + // SetTwoFactorPending keeps secret for userID until a code of it comes. + SetTwoFactorPending(ctx context.Context, userID int64, secret []byte) error + // EnableTwoFactor turns two-factor sign-in on for userID with secret, + // if it is still pending (ErrNotFound otherwise), noting step as used, + // with the recovery codes of hashes; all of the user's sessions end. + EnableTwoFactor(ctx context.Context, userID int64, secret []byte, step int64, hashes [][]byte) error + // DisableTwoFactor turns it off, and deletes the recovery codes. + DisableTwoFactor(ctx context.Context, userID int64) error + // UseTwoFactorStep notes that a code of step was used, and reports + // whether none of it or of a later step had been. + UseTwoFactorStep(ctx context.Context, userID, step int64) (bool, error) + // UseRecoveryCode deletes the recovery code of hash, and reports + // whether userID had it. + UseRecoveryCode(ctx context.Context, userID int64, hash []byte) (bool, error) + // SetRecoveryCodes replaces userID's recovery codes with those of + // hashes. + SetRecoveryCodes(ctx context.Context, userID int64, hashes [][]byte) error + // CreateSession starts a session for u, unless u was deleted or changed // password since it was read (ErrNotFound). It may drop the user's // oldest sessions to bound their number. diff --git a/internal/auth/twofactor.go b/internal/auth/twofactor.go new file mode 100644 index 0000000..98a44cc --- /dev/null +++ b/internal/auth/twofactor.go @@ -0,0 +1,386 @@ +package auth + +import ( + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha1" + "encoding/base32" + "encoding/binary" + "errors" + "fmt" + "net/url" + "strconv" + "strings" + "sync" + "time" +) + +// Two-factor sign-in asks users who turn it on for a code from an +// authenticator app after their password (TOTP, RFC 6238, as such apps +// expect: HMAC-SHA1, 30-second steps, 6 digits), or for one of their +// recovery codes, each of which works once. No code works twice. App +// passwords sign in without one: each is a secret of its own, for one app, +// and is revoked alone. +const ( + totpPeriod = 30 + totpDigits = 6 + // totpSkew is how many steps before and after now are accepted too, + // for clocks that drift. + totpSkew = 1 + // Recovery codes have 10 letters and digits, 50 bits; they are shown in + // two groups of five. + recoveryCodes = 10 + recoveryCodeLength = 10 + // A sign-in that waits for a code may get it for a while, a few times. + challengeTTL = 5 * time.Minute + challengeTries = 5 + maxChallenges = 10_000 +) + +var ( + // ErrWrongCode is a two-factor code that is wrong, or was used already. + ErrWrongCode = fmt.Errorf("%w: wrong two-factor code", ErrInvalidCredentials) + // ErrChallengeGone is a sign-in that waited for a code too long, or got + // too many wrong ones: it starts again with the password. + ErrChallengeGone = errors.New("sign in again") +) + +// CodeNeeded is the error of a sign-in of a user with two-factor sign-in +// that came without a code. Challenge stands for the password checked: +// ContinueLogin takes it with a code, for a while. +type CodeNeeded struct{ Challenge string } + +func (e *CodeNeeded) Error() string { return "a two-factor code is needed" } + +// challenge is a sign-in that waits for a code. +type challenge struct { + user *User + expires time.Time + tries int +} + +// challenges are the sign-ins that wait for a code, by token hash. +type challenges struct { + mu sync.Mutex + m map[string]*challenge +} + +// start keeps a sign-in of u waiting for a code, and returns its token. +func (cs *challenges) start(u *User) (string, error) { + cs.mu.Lock() + defer cs.mu.Unlock() + now := time.Now() + if cs.m == nil { + cs.m = map[string]*challenge{} + } + if len(cs.m) >= maxChallenges { + for k, c := range cs.m { + if now.After(c.expires) { + delete(cs.m, k) + } + } + if len(cs.m) >= maxChallenges { + return "", ErrBusy + } + } + token := newToken() + cs.m[string(tokenHash(token))] = &challenge{user: u, expires: now.Add(challengeTTL)} + return token, nil +} + +// try counts a try of the sign-in token and returns its user, unless it is +// gone; done ends it. +func (cs *challenges) try(token string) (u *User, done func(), err error) { + key := string(tokenHash(token)) + cs.mu.Lock() + defer cs.mu.Unlock() + c, ok := cs.m[key] + if ok && time.Now().After(c.expires) { + delete(cs.m, key) + ok = false + } + if !ok { + return nil, nil, ErrChallengeGone + } + if c.tries++; c.tries >= challengeTries { + delete(cs.m, key) + } + return c.user, func() { + cs.mu.Lock() + delete(cs.m, key) + cs.mu.Unlock() + }, nil +} + +// LoginWithCode is Login for a user who may have two-factor sign-in: it +// then also needs code, from their app or a recovery code. Without one, it +// returns a *CodeNeeded. +func (s *Service) LoginWithCode(ctx context.Context, username, password, code string) (*Session, error) { + u, err := s.checkLogin(ctx, username, password) + if err != nil { + return nil, err + } + recovery := false + if u.TwoFactor { + if strings.TrimSpace(code) == "" { + token, err := s.challenges.start(u) + if err != nil { + return nil, err + } + return nil, &CodeNeeded{Challenge: token} + } + if recovery, err = s.checkCode(ctx, u, code); err != nil { + return nil, err + } + } + return s.loginSession(ctx, u, recovery) +} + +// ContinueLogin goes on with the sign-in that challenge stands for (see +// CodeNeeded), given code. ErrWrongCode leaves a few more tries; +// ErrChallengeGone means signing in again. +func (s *Service) ContinueLogin(ctx context.Context, challenge, code string) (*Session, error) { + if len(challenge) != 43 { + return nil, ErrChallengeGone + } + u, done, err := s.challenges.try(challenge) + if err != nil { + return nil, err + } + recovery, err := s.checkCode(ctx, u, code) + if err != nil { + return nil, err + } + done() + return s.loginSession(ctx, u, recovery) +} + +func (s *Service) loginSession(ctx context.Context, u *User, recovery bool) (*Session, error) { + sess, err := s.newSession(ctx, u) + if errors.Is(err, ErrNotFound) { + // Changed (or the user was deleted) since it was checked. + return nil, errChangedMeanwhile + } + if err != nil { + return nil, err + } + sess.RecoveryCode = recovery + return sess, nil +} + +// checkCode checks code, from u's app or one of their recovery codes, and +// uses it up. It reports whether it was a recovery code. Without two-factor +// sign-in, as it was turned off meanwhile, any code will do. +func (s *Service) checkCode(ctx context.Context, u *User, code string) (bool, error) { + tf, err := s.store.TwoFactor(ctx, u.ID) + if err != nil { + return false, err + } + if tf.Secret == nil { + return false, nil + } + code = strings.Map(func(r rune) rune { + if r == ' ' || r == '-' { + return -1 + } + return r + }, strings.ToLower(strings.TrimSpace(code))) + if step, ok := matchTOTP(tf.Secret, code, time.Now(), tf.Step); ok { + used, err := s.store.UseTwoFactorStep(ctx, u.ID, step) + if err != nil || !used { + return false, cmpErr(err, ErrWrongCode) + } + return false, nil + } + if len(code) != recoveryCodeLength || strings.ContainsFunc(code, func(r rune) bool { return !('a' <= r && r <= 'z' || '2' <= r && r <= '7') }) { + return false, ErrWrongCode + } + used, err := s.store.UseRecoveryCode(ctx, u.ID, tokenHash(code)) + if err != nil || !used { + return false, cmpErr(err, ErrWrongCode) + } + return true, nil +} + +// cmpErr returns err, or otherwise if err is nil. +func cmpErr(err, otherwise error) error { + if err != nil { + return err + } + return otherwise +} + +// matchTOTP returns the time step around now for which code is the code of +// secret, if one is, after the step last. +func matchTOTP(secret []byte, code string, now time.Time, last int64) (int64, bool) { + if len(code) != totpDigits || strings.ContainsFunc(code, func(r rune) bool { return r < '0' || r > '9' }) { + return 0, false + } + at := now.Unix() / totpPeriod + for step := at - totpSkew; step <= at+totpSkew; step++ { + if step > last && hmac.Equal([]byte(totpCode(secret, step)), []byte(code)) { + return step, true + } + } + return 0, false +} + +// totpCode is the code of secret for the time step (RFC 4226, 5.3). +func totpCode(secret []byte, step int64) string { + mac := hmac.New(sha1.New, secret) + _ = binary.Write(mac, binary.BigEndian, step) + sum := mac.Sum(nil) + offset := sum[len(sum)-1] & 0x0f + n := binary.BigEndian.Uint32(sum[offset:]) & 0x7fffffff + code := strconv.Itoa(int(n % 1_000_000)) + return strings.Repeat("0", totpDigits-len(code)) + code +} + +var secretEncoding = base32.StdEncoding.WithPadding(base32.NoPadding) + +// TwoFactorState says how far a user is with two-factor sign-in. +type TwoFactorState struct { + On bool + // Pending is the secret being set up, in base32, as apps take it; "" + // if none. + Pending string + RecoveryCodes int // left +} + +// TwoFactorOf says how far u is with two-factor sign-in. +func (s *Service) TwoFactorOf(ctx context.Context, u *User) (*TwoFactorState, error) { + tf, err := s.store.TwoFactor(ctx, u.ID) + if err != nil { + return nil, err + } + st := &TwoFactorState{On: tf.Secret != nil, RecoveryCodes: tf.RecoveryCodes} + if tf.Pending != nil && tf.Secret == nil { + st.Pending = secretEncoding.EncodeToString(tf.Pending) + } + return st, nil +} + +// StartTwoFactor makes a new secret for u to add to their app, and returns +// it in base32: two-factor sign-in is on once ConfirmTwoFactor gets a code +// of it. ErrInvalid if it is on already. +func (s *Service) StartTwoFactor(ctx context.Context, u *User) (string, error) { + tf, err := s.store.TwoFactor(ctx, u.ID) + if err != nil { + return "", err + } + if tf.Secret != nil { + return "", fmt.Errorf("%w: two-factor sign-in is on already", ErrInvalid) + } + secret := make([]byte, 20) + _, _ = rand.Read(secret) + if err := s.store.SetTwoFactorPending(ctx, u.ID, secret); err != nil { + return "", err + } + return secretEncoding.EncodeToString(secret), nil +} + +// ConfirmTwoFactor turns two-factor sign-in on for u, given a code of the +// secret StartTwoFactor made (ErrWrongCode otherwise; ErrNotFound if none +// is being set up). It returns their recovery codes, which are not kept, +// and a new session: all of u's sessions end. +func (s *Service) ConfirmTwoFactor(ctx context.Context, u *User, code string) ([]string, *Session, error) { + tf, err := s.store.TwoFactor(ctx, u.ID) + switch { + case err != nil: + return nil, nil, err + case tf.Secret != nil: + return nil, nil, fmt.Errorf("%w: two-factor sign-in is on already", ErrInvalid) + case tf.Pending == nil: + return nil, nil, ErrNotFound + } + step, ok := matchTOTP(tf.Pending, strings.ReplaceAll(strings.TrimSpace(code), " ", ""), time.Now(), 0) + if !ok { + return nil, nil, ErrWrongCode + } + codes, hashes := newRecoveryCodes() + if err := s.store.EnableTwoFactor(ctx, u.ID, tf.Pending, step, hashes); err != nil { + return nil, nil, err + } + on := *u + on.TwoFactor = true + sess, err := s.newSession(ctx, &on) + if err != nil { + return nil, nil, err + } + return codes, sess, nil +} + +// NewRecoveryCodes replaces u's recovery codes, after checking their +// password, and returns them: they are not kept. ErrInvalid if two-factor +// sign-in is off. +func (s *Service) NewRecoveryCodes(ctx context.Context, u *User, password string) ([]string, error) { + if err := s.checkPasswordOf(ctx, u, password); err != nil { + return nil, err + } + codes, hashes := newRecoveryCodes() + err := s.store.SetRecoveryCodes(ctx, u.ID, hashes) + if errors.Is(err, ErrNotFound) { + return nil, fmt.Errorf("%w: two-factor sign-in is off", ErrInvalid) + } + if err != nil { + return nil, err + } + return codes, nil +} + +// DisableTwoFactor turns two-factor sign-in off for u, after checking their +// password. +func (s *Service) DisableTwoFactor(ctx context.Context, u *User, password string) error { + if err := s.checkPasswordOf(ctx, u, password); err != nil { + return err + } + return s.store.DisableTwoFactor(ctx, u.ID) +} + +// ResetTwoFactor turns two-factor sign-in off for the user username, for +// administrators: for a user who lost their app and their recovery codes. +// It reports whether it was on. +func (s *Service) ResetTwoFactor(ctx context.Context, username string) (bool, error) { + u, err := s.store.UserByName(ctx, NormalizeUsername(username)) + if err != nil { + return false, err + } + if !u.TwoFactor { + return false, nil + } + return true, s.store.DisableTwoFactor(ctx, u.ID) +} + +// checkPasswordOf checks the password of the signed-in u. +func (s *Service) checkPasswordOf(ctx context.Context, u *User, password string) error { + if password == "" || len(password) > MaxPasswordLength { + return errWrongPassword + } + ok, err := s.verify(ctx, u, password) + if err != nil { + return err + } + if !ok { + return errWrongPassword + } + return nil +} + +// newRecoveryCodes makes recovery codes, as shown and as kept. +func newRecoveryCodes() (codes []string, hashes [][]byte) { + for range recoveryCodes { + raw := strings.ToLower(rand.Text()[:recoveryCodeLength]) + codes = append(codes, raw[:5]+"-"+raw[5:]) + hashes = append(hashes, tokenHash(raw)) + } + return codes, hashes +} + +// OTPAuthURI is the URI that authenticator apps take, as a QR code, for +// the secret (in base32) of the user username, at the site issuer. +func OTPAuthURI(issuer, username, secret string) string { + q := url.Values{"secret": {secret}, "issuer": {issuer}, "algorithm": {"SHA1"}, + "digits": {strconv.Itoa(totpDigits)}, "period": {strconv.Itoa(totpPeriod)}} + return "otpauth://totp/" + url.PathEscape(issuer) + ":" + url.PathEscape(username) + "?" + q.Encode() +} diff --git a/internal/auth/twofactor_test.go b/internal/auth/twofactor_test.go new file mode 100644 index 0000000..393cf00 --- /dev/null +++ b/internal/auth/twofactor_test.go @@ -0,0 +1,221 @@ +package auth_test + +import ( + "context" + "encoding/base32" + "errors" + "regexp" + "strings" + "testing" + "time" + + "goftp/internal/auth" +) + +// The test vectors of RFC 6238, appendix B, for SHA-1, to six digits. +func TestTOTPCode(t *testing.T) { + secret := []byte("12345678901234567890") + for unix, want := range map[int64]string{59: "287082", 1111111109: "081804", 1111111111: "050471", 1234567890: "005924", + 2000000000: "279037", 20000000000: "353130"} { + if got := auth.TOTPCode(secret, unix/30); got != want { + t.Errorf("at %d: %s, want %s", unix, got, want) + } + } +} + +// codeOf is the code of the base32 secret, steps from now. +func codeOf(t *testing.T, secret string, steps int64) string { + t.Helper() + raw, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret) + if err != nil { + t.Fatal(err) + } + return auth.TOTPCode(raw, time.Now().Unix()/30+steps) +} + +// otherCode is a code that is not code. +func otherCode(code string) string { + return string('0'+(code[0]-'0'+1)%10) + code[1:] +} + +func TestTwoFactor(t *testing.T) { + services(t, func(t *testing.T, svc *auth.Service) { + ctx := context.Background() + password, err := svc.CreateUser(ctx, "dora", "user") + if err != nil { + t.Fatal(err) + } + dora := userNamed(t, svc, "dora") + before, err := svc.Login(ctx, "dora", password) + if err != nil { + t.Fatal(err) + } + + // Set up: a secret, which is on once a code of it comes. + if _, _, err := svc.ConfirmTwoFactor(ctx, dora, "123456"); !errors.Is(err, auth.ErrNotFound) { + t.Errorf("confirmed nothing: %v", err) + } + secret, err := svc.StartTwoFactor(ctx, dora) + if err != nil { + t.Fatal(err) + } + if !regexp.MustCompile(`^[A-Z2-7]{32}$`).MatchString(secret) { + t.Errorf("secret %q", secret) + } + if st, err := svc.TwoFactorOf(ctx, dora); err != nil || st.On || st.Pending != secret { + t.Errorf("pending: %+v, %v", st, err) + } + if _, err := svc.Login(ctx, "dora", password); err != nil { + t.Errorf("signing in while it is set up: %v", err) + } + code := codeOf(t, secret, 0) + if _, _, err := svc.ConfirmTwoFactor(ctx, dora, otherCode(code)); !errors.Is(err, auth.ErrWrongCode) { + t.Errorf("a wrong code: %v", err) + } + codes, sess, err := svc.ConfirmTwoFactor(ctx, dora, code) + if err != nil { + t.Fatal(err) + } + if len(codes) != 10 || !regexp.MustCompile(`^[a-z2-7]{5}-[a-z2-7]{5}$`).MatchString(codes[0]) || codes[0] == codes[1] { + t.Errorf("recovery codes %q", codes) + } + if !sess.User.TwoFactor { + t.Error("the new session's user") + } + // It signs out everywhere else. + if _, err := svc.Authenticate(ctx, before.Token); !errors.Is(err, auth.ErrNotFound) { + t.Errorf("an older session: %v", err) + } + if u, err := svc.Authenticate(ctx, sess.Token); err != nil || !u.TwoFactor { + t.Errorf("the new session: %+v, %v", u, err) + } + if st, err := svc.TwoFactorOf(ctx, dora); err != nil || !st.On || st.Pending != "" || st.RecoveryCodes != 10 { + t.Errorf("on: %+v, %v", st, err) + } + if _, err := svc.StartTwoFactor(ctx, dora); !errors.Is(err, auth.ErrInvalid) { + t.Errorf("set up again: %v", err) + } + dora = userNamed(t, svc, "dora") + + // Signing in now takes a code, after the password. + if _, err := svc.LoginWithCode(ctx, "dora", "wrong password", ""); !errors.Is(err, auth.ErrInvalidCredentials) { + t.Errorf("a wrong password: %v", err) + } + _, err = svc.Login(ctx, "dora", password) + var needed *auth.CodeNeeded + if !errors.As(err, &needed) || len(needed.Challenge) != 43 { + t.Fatalf("without a code: %v", err) + } + // The code used to set it up was used. + if _, err := svc.ContinueLogin(ctx, needed.Challenge, code); !errors.Is(err, auth.ErrWrongCode) { + t.Errorf("a code used before: %v", err) + } + next := codeOf(t, secret, 1) + sess, err = svc.ContinueLogin(ctx, needed.Challenge, " "+next[:3]+" "+next[3:]) + if err != nil || sess.RecoveryCode || sess.User.ID != dora.ID { + t.Fatalf("with a code: %+v, %v", sess, err) + } + if _, err := svc.ContinueLogin(ctx, needed.Challenge, next); !errors.Is(err, auth.ErrChallengeGone) { + t.Errorf("signed in twice: %v", err) + } + if _, err := svc.LoginWithCode(ctx, "dora", password, next); !errors.Is(err, auth.ErrWrongCode) { + t.Errorf("a code used again: %v", err) + } + for _, bad := range []string{"12345", "1234567", "abcdef", "aaaaa-aaaaa", "x"} { + if _, err := svc.LoginWithCode(ctx, "dora", password, bad); !errors.Is(err, auth.ErrWrongCode) { + t.Errorf("code %q: %v", bad, err) + } + } + + // Recovery codes work once each, as typed. + sess, err = svc.LoginWithCode(ctx, "dora", password, codes[0]) + if err != nil || !sess.RecoveryCode { + t.Errorf("a recovery code: %+v, %v", sess, err) + } + if _, err := svc.LoginWithCode(ctx, "dora", password, codes[0]); !errors.Is(err, auth.ErrWrongCode) { + t.Errorf("a recovery code used again: %v", err) + } + if _, err := svc.LoginWithCode(ctx, "dora", password, strings.ToUpper(strings.ReplaceAll(codes[1], "-", " "))); err != nil { + t.Errorf("a recovery code as typed: %v", err) + } + if st, err := svc.TwoFactorOf(ctx, dora); err != nil || st.RecoveryCodes != 8 { + t.Errorf("left: %+v, %v", st, err) + } + + // A sign-in waits for a code a few tries long. + _, err = svc.Login(ctx, "dora", password) + if !errors.As(err, &needed) { + t.Fatal(err) + } + for i := range 5 { + if _, err := svc.ContinueLogin(ctx, needed.Challenge, "000000"); !errors.Is(err, auth.ErrWrongCode) && !(i == 4 && err == nil) { + t.Errorf("try %d: %v", i, err) + } + } + if _, err := svc.ContinueLogin(ctx, needed.Challenge, codes[2]); !errors.Is(err, auth.ErrChallengeGone) { + t.Errorf("after five tries: %v", err) + } + if _, err := svc.ContinueLogin(ctx, "nope", codes[2]); !errors.Is(err, auth.ErrChallengeGone) { + t.Errorf("no such sign-in: %v", err) + } + + // New recovery codes, and turning it off, take the password. + if _, err := svc.NewRecoveryCodes(ctx, dora, "wrong password"); !errors.Is(err, auth.ErrInvalidCredentials) { + t.Errorf("new codes, wrong password: %v", err) + } + fresh, err := svc.NewRecoveryCodes(ctx, dora, password) + if err != nil || len(fresh) != 10 { + t.Fatalf("new codes: %v, %v", fresh, err) + } + if _, err := svc.LoginWithCode(ctx, "dora", password, codes[3]); !errors.Is(err, auth.ErrWrongCode) { + t.Errorf("an old recovery code: %v", err) + } + if _, err := svc.LoginWithCode(ctx, "dora", password, fresh[0]); err != nil { + t.Errorf("a new recovery code: %v", err) + } + if err := svc.DisableTwoFactor(ctx, dora, "wrong password"); !errors.Is(err, auth.ErrInvalidCredentials) { + t.Errorf("off, wrong password: %v", err) + } + if err := svc.DisableTwoFactor(ctx, dora, password); err != nil { + t.Fatal(err) + } + if _, err := svc.Login(ctx, "dora", password); err != nil { + t.Errorf("off: %v", err) + } + if st, err := svc.TwoFactorOf(ctx, dora); err != nil || st.On || st.RecoveryCodes != 0 { + t.Errorf("off: %+v, %v", st, err) + } + if _, err := svc.NewRecoveryCodes(ctx, dora, password); !errors.Is(err, auth.ErrInvalid) { + t.Errorf("new codes while off: %v", err) + } + + // Administrators turn it off for those who lost their app. + secret, err = svc.StartTwoFactor(ctx, dora) + if err != nil { + t.Fatal(err) + } + if _, _, err := svc.ConfirmTwoFactor(ctx, dora, codeOf(t, secret, 0)); err != nil { + t.Fatal(err) + } + if on, err := svc.ResetTwoFactor(ctx, "Dora"); err != nil || !on { + t.Errorf("reset: %v, %v", on, err) + } + if on, err := svc.ResetTwoFactor(ctx, "dora"); err != nil || on { + t.Errorf("reset again: %v, %v", on, err) + } + if _, err := svc.ResetTwoFactor(ctx, "nobody"); !errors.Is(err, auth.ErrNotFound) { + t.Errorf("reset nobody: %v", err) + } + if _, err := svc.Login(ctx, "dora", password); err != nil { + t.Errorf("after the reset: %v", err) + } + }) +} + +func TestOTPAuthURI(t *testing.T) { + got := auth.OTPAuthURI("files.example.com", "dora", "ABCDEF") + want := "otpauth://totp/files.example.com:dora?algorithm=SHA1&digits=6&issuer=files.example.com&period=30&secret=ABCDEF" + if got != want { + t.Errorf("%s, want %s", got, want) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 5fe9e88..9268cf5 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -242,6 +242,27 @@ func userCmd() *cobra.Command { }, } + twoFactorOff := &cobra.Command{ + Use: "two-factor-off NAME", + Short: "Turn off two-factor sign-in for a user who lost their app and recovery codes", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return withService(cmd, func(svc *auth.Service) error { + on, err := svc.ResetTwoFactor(cmd.Context(), args[0]) + if err != nil { + return err + } + name := auth.NormalizeUsername(args[0]) + if !on { + cmd.Printf("two-factor sign-in was off for %s already\n", name) + return nil + } + cmd.Printf("turned off two-factor sign-in for %s: their password alone signs them in\n", name) + return nil + }) + }, + } + role := &cobra.Command{ Use: "role NAME ROLE", Short: "Change a user's role (" + roles + ")", @@ -310,7 +331,7 @@ func userCmd() *cobra.Command { }, } - cmd.AddCommand(add, list, passwd, role, quota, del) + cmd.AddCommand(add, list, passwd, twoFactorOff, role, quota, del) return cmd } diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index f9c6ea0..64d2ccf 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -49,6 +49,7 @@ func TestUserCommands(t *testing.T) { {"user", "add", "X Y"}, {"user", "role", "nobody", "admin"}, {"user", "passwd", "nobody"}, + {"user", "two-factor-off", "nobody"}, {"user", "delete", "nobody"}, {"user", "add"}, } { @@ -75,6 +76,9 @@ func TestUserCommands(t *testing.T) { t.Errorf("user quota default: %q", out) } + if out := mustRun(t, "user", "two-factor-off", "bob"); !strings.Contains(out, "two-factor sign-in was off for bob already") { + t.Errorf("user two-factor-off: %q", out) + } mustRun(t, "user", "role", "bob", "admin") out = mustRun(t, "user", "passwd", "bob") if !tempPassword.MatchString(out) { diff --git a/internal/db/db_test.go b/internal/db/db_test.go index ccb00fe..e6ca1be 100644 --- a/internal/db/db_test.go +++ b/internal/db/db_test.go @@ -56,7 +56,7 @@ func TestConcurrentMigrations(t *testing.T) { if err := pools[0].QueryRow(ctx, "SELECT count(*) FROM casbin_rule").Scan(&rules); err != nil { t.Fatal(err) } - if versions != 9 || rules != 9 { + if versions != 10 || rules != 9 { t.Errorf("%d migrations recorded, %d rules seeded", versions, rules) } } diff --git a/internal/db/migrations/010_two_factor.sql b/internal/db/migrations/010_two_factor.sql new file mode 100644 index 0000000..f325eb5 --- /dev/null +++ b/internal/db/migrations/010_two_factor.sql @@ -0,0 +1,14 @@ +-- Two-factor sign-in: the TOTP secret (RFC 6238) of users who turned it on, +-- one being set up until a code of it comes, and the last time step a code +-- was used for, so that none works twice. Recovery codes work once each; +-- only the SHA-256 of each is kept. +ALTER TABLE users + ADD COLUMN totp_secret BYTEA, + ADD COLUMN totp_pending BYTEA, + ADD COLUMN totp_step BIGINT NOT NULL DEFAULT 0; + +CREATE TABLE recovery_codes ( + user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + code_hash BYTEA NOT NULL, + PRIMARY KEY (user_id, code_hash) +); diff --git a/internal/server/admin.go b/internal/server/admin.go index 1fd247f..8d7ca3e 100644 --- a/internal/server/admin.go +++ b/internal/server/admin.go @@ -38,6 +38,7 @@ type adminPage struct { type adminUser struct { Name, Role string MustChange, Self bool + TwoFactor bool Added, AddedISO string Quota string // how much their home may hold, as set: "" for the default, "none" for no limit } @@ -66,6 +67,7 @@ var adminNotices = map[string]string{ "deleted": "The user was deleted.", "deleted-home": "The user was deleted. Their home went to the trash, where a superadmin can restore it for them.", "deleted-all": "The user was deleted, and their home with everything in it, as the trash is off.", + "two-factor": "Two-factor sign-in is off for them: their password alone signs them in, until they turn it on again.", "rule-added": "The rule was added.", "rule-removed": "The rule was removed.", } @@ -105,7 +107,8 @@ func (s *Server) rulesPage(c fiber.Ctx) error { } // usersAction adds users, gives them new temporary passwords, changes their -// roles and deletes them. Superadmins cannot change their own account here, +// roles, turns two-factor sign-in off for those who lost their app, and +// deletes them. Superadmins cannot change their own account here, // so they cannot lock themselves out. func (s *Server) usersAction(c fiber.Ctx) error { if ok, err := s.superadmin(c); !ok { @@ -150,6 +153,12 @@ func (s *Server) usersAction(c fiber.Ctx) error { s.recount(name) s.logAdmin(c, "home quota set", zap.String("target", name), zap.String("quota", form["quota"])) return s.redirect(c, usersPath+"?done=quota") + case "two-factor-off": + if _, err := s.auth.ResetTwoFactor(ctx, name); err != nil { + return s.adminFailure(c, "users", err) + } + s.logAdmin(c, "two-factor sign-in turned off", zap.String("target", name)) + return s.redirect(c, usersPath+"?done=two-factor") case "role": if err := s.auth.SetRole(ctx, name, role); err != nil { return s.adminFailure(c, "users", err) @@ -265,7 +274,7 @@ func (s *Server) renderAdmin(c fiber.Ctx, status int, tab, notice, failure strin me := userOf(c).Username for _, u := range users { data.Users = append(data.Users, adminUser{ - Name: u.Username, Role: u.Role, MustChange: u.MustChangePassword, Self: u.Username == me, + Name: u.Username, Role: u.Role, MustChange: u.MustChangePassword, Self: u.Username == me, TwoFactor: u.TwoFactor, Added: u.CreatedAt.UTC().Format("Jan 2, 2006"), AddedISO: isoTime(u.CreatedAt), }) if q := u.HomeQuota; q != nil { diff --git a/internal/server/auth.go b/internal/server/auth.go index 899b7b4..084bc1b 100644 --- a/internal/server/auth.go +++ b/internal/server/auth.go @@ -346,6 +346,8 @@ type authPage struct { Next string Username string Forced bool + // Challenge is set when signing in waits for a two-factor code. + Challenge string } func (s *Server) loginPage(c fiber.Ctx) error { @@ -368,6 +370,9 @@ func (s *Server) login(c fiber.Ctx) error { } return s.render(c, status, "login", authPage{page: s.page(c, "Sign in"), Error: msg, Next: next, Username: form["username"]}) } + if form["challenge"] != "" { + return s.loginCode(c, form, isJSON, next) + } check, wait := s.checkPassword(c, form["username"]) if wait > 0 { @@ -376,8 +381,16 @@ func (s *Server) login(c fiber.Ctx) error { } ctx, cancel := dbContext(c) defer cancel() - sess, err := s.auth.Login(ctx, form["username"], form["password"]) + sess, err := s.auth.LoginWithCode(ctx, form["username"], form["password"], form["code"]) + var needed *auth.CodeNeeded switch { + case errors.As(err, &needed): + check.succeeded() + return s.askCode(c, isJSON, needed.Challenge, next) + case errors.Is(err, auth.ErrWrongCode): + // The password was right; the failure still counts. + s.log.Warn("login code wrong", zap.String("ip", c.IP()), zap.String("user", auth.NormalizeUsername(form["username"]))) + return fail(fiber.StatusUnauthorized, "Wrong two-factor code.") case errors.Is(err, auth.ErrInvalidCredentials): // A name that matches no user is not logged: it may be a password // typed into the wrong field. @@ -396,8 +409,14 @@ func (s *Server) login(c fiber.Ctx) error { return err } check.succeeded() - s.log.Info("login", zap.String("ip", c.IP()), zap.String("user", sess.User.Username)) + return s.signedIn(c, sess, isJSON, next) +} +// signedIn answers a sign-in that succeeded with sess: scripts get its +// token, browsers its cookie and go on to next. +func (s *Server) signedIn(c fiber.Ctx, sess *auth.Session, isJSON bool, next string) error { + s.log.Info("login", zap.String("ip", c.IP()), zap.String("user", sess.User.Username), zap.Bool("two_factor", sess.User.TwoFactor), + zap.Bool("recovery_code", sess.RecoveryCode)) if isJSON { c.Set(fiber.HeaderCacheControl, "no-store") return c.JSON(fiber.Map{ @@ -407,8 +426,12 @@ func (s *Server) login(c fiber.Ctx) error { }) } s.setCookie(c, sess) - if sess.User.MustChangePassword { + switch { + case sess.User.MustChangePassword: next = passwordPath + "?next=" + url.QueryEscape(next) + case sess.RecoveryCode: + // Say how many are left. + next = twoFactorPath + "?recovered=1" } return s.redirect(c, next) } diff --git a/internal/server/server.go b/internal/server/server.go index 4a6683b..55e3962 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -161,6 +161,8 @@ func New(cfg *config.Config, log *zap.Logger, authSvc *auth.Service) (*Server, e s.app.Post(logoutPath, s.logout) s.app.Get(passwordPath, s.passwordPage) s.app.Post(passwordPath, s.changePassword) + s.app.Get(twoFactorPath, s.twoFactorPage) + s.app.Post(twoFactorPath, s.twoFactorAction) s.app.Get(strings.TrimSuffix(adminPath, "/"), s.adminHome) s.app.Get(adminPath, s.adminHome) s.app.Get(usersPath, s.usersPage) diff --git a/internal/server/templates/admin.html b/internal/server/templates/admin.html index 7c20f2e..c30019b 100644 --- a/internal/server/templates/admin.html +++ b/internal/server/templates/admin.html @@ -47,7 +47,7 @@

Add a user

{{range .Users}} - {{.Name}}{{if .Self}}you{{end}}{{if .MustChange}}must choose a password{{end}} + {{.Name}}{{if .Self}}you{{end}}{{if .MustChange}}must choose a password{{end}}{{if .TwoFactor}}two-factor{{end}} {{if .Self}}{{.Role}}{{else}}
@@ -75,6 +75,16 @@

Add a user

+ {{if .TwoFactor}} +
+ +
+ +

Turn off two-factor sign-in for {{.Name}}? Their password alone will sign them in: do it only for someone who lost their app and recovery codes, and is who they say.

+
+
+
+ {{end}}
diff --git a/internal/server/templates/base.html b/internal/server/templates/base.html index f48f02d..781a5fd 100644 --- a/internal/server/templates/base.html +++ b/internal/server/templates/base.html @@ -434,6 +434,12 @@ .people-form { display: flex; flex-direction: column; gap: 12px; } .people-row { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 10px; } .people-row select { height: 38px; width: 100%; } + .twofactor-setup .qr-row { display: flex; flex-wrap: wrap; align-items: center; gap: 20px; } + .qr { display: block; width: 184px; height: 184px; border-radius: var(--radius-sm); } + .qr-key { display: flex; flex-direction: column; gap: 8px; min-width: 0; flex: 1 1 220px; font-size: 13.5px; } + .qr-key code { overflow-wrap: anywhere; font-size: 14px; letter-spacing: 0.06em; } + .recovery-codes { display: grid; grid-template-columns: repeat(2, max-content); gap: 4px 24px; margin: 0; padding: 0; list-style: none; } + .recovery-codes code { font-size: 15px; letter-spacing: 0.04em; } .shares-section { margin-top: 28px; } .shares-section:first-of-type { margin-top: 0; } .shares-section > h2 { margin-bottom: 10px; font-size: 16px; } @@ -495,6 +501,8 @@ .list-table td.act { width: auto; white-space: nowrap; } .who-cell { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; font-weight: 500; } .who-cell .avatar { width: 28px; height: 28px; font-size: 12.5px; } + .who-cell .chip { display: inline-flex; align-items: center; gap: 4px; } + .who-cell .chip .i { width: 13px; height: 13px; } .chip.warn { background: var(--danger-soft); border-color: transparent; color: var(--danger); } .role-form { display: flex; align-items: center; gap: 8px; } .role-form select { height: 32px; font-size: 13.5px; } @@ -735,6 +743,7 @@ {{if .Admin}}Users and rules{{end}} Sync Change password + Two-factor sign-in
diff --git a/internal/server/templates/login.html b/internal/server/templates/login.html index 8f83984..4d370ea 100644 --- a/internal/server/templates/login.html +++ b/internal/server/templates/login.html @@ -3,6 +3,21 @@
goftp
+ {{if .Challenge}} +

Two-factor sign-in

+

Enter the code your authenticator app shows for this site, or one of your recovery codes.

+
+ {{with .Error}}{{end}} + + + + +
+
+

Start over

+ {{else}}

Sign in

Welcome back. Sign in to browse and share files.

@@ -19,6 +34,7 @@

Sign in

No account yet? Ask your administrator to create one.

+ {{end}}
{{template "icons"}} {{script}} diff --git a/internal/server/templates/twofactor.html b/internal/server/templates/twofactor.html new file mode 100644 index 0000000..3e4f8b3 --- /dev/null +++ b/internal/server/templates/twofactor.html @@ -0,0 +1,89 @@ +{{define "twofactor"}}{{template "head" .}} + +{{template "topbar" .}} +
+
+
+

Two-factor sign-in

+

{{if .On}}On: after your password, signing in takes a code from your authenticator app, or a recovery code.{{else}}Off: your password alone signs you in.{{end}}

+
+
+ + {{with .Notice}}{{end}} + {{with .Error}}{{end}} + {{if and .Recovered .On}}{{end}} + {{with .Codes}} + + {{end}} + + {{if .On}} +
+

Recovery codes

+

{{.CodesLeft}} of 10 left. New ones replace them all.

+
+ + + + +
+
+
+

Turn off

+

Your password alone will sign you in again.

+
+ + + + +
+
+ {{else if .Setup}}{{with .Setup}} +
+

Add this site to your authenticator app

+
+ {{.QR}} +
+

Scan the code with the app, or enter this key in it by hand:

+

{{.Secret}}

+

On this phone? Open it in the app.

+
+
+
+ + + +
+
+ {{end}}{{else}} +
+

Turn on

+

Signing in will then take, after your password, a 6-digit code from an authenticator app on your phone, which changes every 30 seconds: a stolen password alone will not do. Sync apps keep signing in with their app passwords.

+
+ + +
+
+ {{end}} +
+{{template "footer" .}} +{{template "icons"}} +{{script}} + + +{{end}} diff --git a/internal/server/twofactor.go b/internal/server/twofactor.go new file mode 100644 index 0000000..9de73b1 --- /dev/null +++ b/internal/server/twofactor.go @@ -0,0 +1,284 @@ +package server + +import ( + "errors" + "fmt" + "html/template" + "strings" + "time" + + "github.com/gofiber/fiber/v3" + "go.uber.org/zap" + "rsc.io/qr" + + "goftp/internal/auth" +) + +// twoFactorPath is the page where users turn two-factor sign-in on and off +// (see auth.LoginWithCode). +const twoFactorPath = authPrefix + "two-factor" + +type twoFactorPage struct { + page + On bool + CodesLeft int + Setup *twoFactorSetup + Codes []string // new recovery codes, shown once + Recovered bool // the visitor just signed in with a recovery code + Notice string + Error string +} + +// twoFactorSetup is a secret being set up, for the visitor's app. +type twoFactorSetup struct { + Secret string // in groups of four, as people type it + URI template.URL + QR template.HTML +} + +var twoFactorNotices = map[string]string{ + "off": "Two-factor sign-in is off: your password alone signs you in.", +} + +func (s *Server) twoFactorPage(c fiber.Ctx) error { + if userOf(c) == nil { + return s.deny(c) + } + return s.renderTwoFactor(c, fiber.StatusOK, twoFactorPage{Notice: twoFactorNotices[c.Query("done")], Recovered: c.Query("recovered") == "1"}) +} + +// renderTwoFactor shows data, with how far the visitor is with two-factor +// sign-in. +func (s *Server) renderTwoFactor(c fiber.Ctx, status int, data twoFactorPage) error { + u := userOf(c) + ctx, cancel := dbContext(c) + defer cancel() + st, err := s.auth.TwoFactorOf(ctx, u) + if err != nil { + return err + } + data.page, data.On, data.CodesLeft = s.page(c, "Two-factor sign-in"), st.On, st.RecoveryCodes + if st.Pending != "" { + if data.Setup, err = s.setupOf(c, u, st.Pending); err != nil { + return err + } + } + return s.render(c, status, "twofactor", data) +} + +// setupOf describes the secret (in base32) that u is setting up. +func (s *Server) setupOf(c fiber.Ctx, u *auth.User, secret string) (*twoFactorSetup, error) { + var groups []string + for i := 0; i < len(secret); i += 4 { + groups = append(groups, secret[i:min(i+4, len(secret))]) + } + uri := auth.OTPAuthURI(c.Hostname(), u.Username, secret) + setup := &twoFactorSetup{Secret: strings.Join(groups, " "), URI: template.URL(uri)} + code, err := qr.Encode(uri, qr.M) + if err != nil { + return nil, err + } + setup.QR = qrSVG(code) + return setup, nil +} + +// qrSVG draws code, with the quiet zone around it that scanners need. +func qrSVG(code *qr.Code) template.HTML { + const quiet = 4 + var b strings.Builder + n := code.Size + 2*quiet + fmt.Fprintf(&b, ``, n, n) + fmt.Fprintf(&b, ``) + return template.HTML(b.String()) +} + +// twoFactorAction sets up two-factor sign-in, sent URL-encoded or as JSON: +// +// action=start makes a new secret for the visitor's app: +// {"secret": BASE32, "uri": "otpauth://..."} +// action=confirm&code=CODE turns it on, given a code of the secret, and +// answers with recovery codes, shown once; it +// signs out everywhere, so with a new session +// token too +// action=codes&password=PW makes new recovery codes +// action=off&password=PW turns it off +func (s *Server) twoFactorAction(c fiber.Ctx) error { + sess := sessionOf(c) + if sess == nil { + return s.deny(c) + } + u := sess.user + form, _, err := s.readForm(c) + if err != nil { + return err + } + // Scripts get JSON, as for links. + isJSON := !strings.Contains(c.Get(fiber.HeaderAccept), fiber.MIMETextHTML) + fail := func(status int, msg string) error { + if isJSON { + return sendMessage(c, status, msg) + } + return s.renderTwoFactor(c, status, twoFactorPage{Error: msg}) + } + ctx, cancel := dbContext(c) + defer cancel() + c.Set(fiber.HeaderCacheControl, "no-store") + + switch form["action"] { + case "start": + secret, err := s.auth.StartTwoFactor(ctx, u) + if errors.Is(err, auth.ErrInvalid) { + return fail(fiber.StatusConflict, "Two-factor sign-in is on already.") + } + if err != nil { + return err + } + if isJSON { + return c.JSON(fiber.Map{"secret": secret, "uri": auth.OTPAuthURI(c.Hostname(), u.Username, secret)}) + } + return s.redirect(c, twoFactorPath) + case "confirm": + codes, changed, err := s.auth.ConfirmTwoFactor(ctx, u, form["code"]) + switch { + case errors.Is(err, auth.ErrWrongCode): + return fail(fiber.StatusBadRequest, "That is not the code the app shows now: check that its clock is right, and try the next one.") + case errors.Is(err, auth.ErrNotFound): + return fail(fiber.StatusConflict, "Set it up first.") + case errors.Is(err, auth.ErrInvalid): + return fail(fiber.StatusConflict, "Two-factor sign-in is on already.") + case err != nil: + return err + } + s.log.Info("two-factor sign-in on", zap.String("ip", c.IP()), zap.String("user", u.Username)) + if isJSON { + return c.JSON(fiber.Map{"recovery_codes": codes, "token": changed.Token, "expires_at": changed.Expires.UTC().Format(time.RFC3339)}) + } + if sess.cookie { + s.setCookie(c, changed) + } + c.Locals(sessionKey, &session{user: changed.User, token: changed.Token, cookie: sess.cookie}) + return s.renderTwoFactor(c, fiber.StatusOK, twoFactorPage{Codes: codes, + Notice: "Two-factor sign-in is on. You were signed out everywhere else."}) + case "codes", "off": + default: + return fiber.ErrBadRequest + } + + // Both take the password. + check, wait := s.checkPassword(c, u.Username) + if wait > 0 { + retryAfter(c, wait) + return fail(fiber.StatusTooManyRequests, tooMany) + } + var codes []string + if form["action"] == "codes" { + codes, err = s.auth.NewRecoveryCodes(ctx, u, form["password"]) + } else { + err = s.auth.DisableTwoFactor(ctx, u, form["password"]) + } + switch { + case errors.Is(err, auth.ErrInvalidCredentials): + s.log.Warn("two-factor change refused: wrong password", zap.String("ip", c.IP()), zap.String("user", u.Username)) + return fail(fiber.StatusForbidden, "The password is wrong.") + case errors.Is(err, auth.ErrInvalid): + check.succeeded() + return fail(fiber.StatusConflict, "Two-factor sign-in is off.") + case errors.Is(err, auth.ErrBusy): + check.refund() + retryAfter(c, time.Second) + return fail(fiber.StatusServiceUnavailable, busy) + case err != nil: + check.refund() + return err + } + check.succeeded() + if form["action"] == "off" { + s.log.Info("two-factor sign-in off", zap.String("ip", c.IP()), zap.String("user", u.Username)) + if isJSON { + return c.SendStatus(fiber.StatusNoContent) + } + return s.redirect(c, twoFactorPath+"?done=off") + } + s.log.Info("recovery codes made", zap.String("ip", c.IP()), zap.String("user", u.Username)) + if isJSON { + return c.JSON(fiber.Map{"recovery_codes": codes}) + } + return s.renderTwoFactor(c, fiber.StatusOK, twoFactorPage{Codes: codes, Notice: "New recovery codes: the old ones no longer work."}) +} + +// checkCode admits a try of a two-factor code from the client, or says how +// long to wait: it counts against the client's failure budget, as a +// password check does. +func (s *Server) checkCode(c fiber.Ctx) (*passwordCheck, time.Duration) { + p := &passwordCheck{s: s} + if s.limiter != nil { + p.client = clientKey(c.IP()) + if wait := s.limiter.attempt(p.client, true, time.Now()); wait > 0 { + return nil, wait + } + } + return p, 0 +} + +// loginCode goes on with a sign-in that waits for a two-factor code: the +// form has its challenge and the code. +func (s *Server) loginCode(c fiber.Ctx, form map[string]string, isJSON bool, next string) error { + challenge := form["challenge"] + fail := func(status int, msg string, again bool) error { + if isJSON { + return sendMessage(c, status, msg) + } + data := authPage{page: s.page(c, "Sign in"), Error: msg, Next: next} + if !again { + data.Challenge = challenge + } + return s.render(c, status, "login", data) + } + check, wait := s.checkCode(c) + if wait > 0 { + retryAfter(c, wait) + return fail(fiber.StatusTooManyRequests, tooMany, false) + } + ctx, cancel := dbContext(c) + defer cancel() + sess, err := s.auth.ContinueLogin(ctx, challenge, form["code"]) + switch { + case errors.Is(err, auth.ErrWrongCode): + s.log.Warn("login code wrong", zap.String("ip", c.IP())) + return fail(fiber.StatusUnauthorized, "Wrong code. Enter the one your app shows now, or a recovery code.", false) + case errors.Is(err, auth.ErrChallengeGone): + return fail(fiber.StatusUnauthorized, "It took too long, or too many codes were wrong: sign in again.", true) + case errors.Is(err, auth.ErrInvalidCredentials): + // The password changed meanwhile. + return fail(fiber.StatusUnauthorized, "Sign in again.", true) + case err != nil: + check.refund() + return err + } + check.refund() + return s.signedIn(c, sess, isJSON, next) +} + +// askCode answers a sign-in that needs a two-factor code, with challenge to +// send back with it. +func (s *Server) askCode(c fiber.Ctx, isJSON bool, challenge, next string) error { + if isJSON { + c.Set(fiber.HeaderCacheControl, "no-store") + return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "a two-factor code is needed", "two_factor": true, "challenge": challenge}) + } + return s.render(c, fiber.StatusOK, "login", authPage{page: s.page(c, "Sign in"), Next: next, Challenge: challenge}) +} diff --git a/internal/server/twofactor_test.go b/internal/server/twofactor_test.go new file mode 100644 index 0000000..d7b756e --- /dev/null +++ b/internal/server/twofactor_test.go @@ -0,0 +1,219 @@ +package server + +import ( + "crypto/hmac" + "crypto/sha1" + "encoding/base32" + "encoding/binary" + "encoding/json" + "fmt" + "html" + "net/http" + "regexp" + "strings" + "testing" + "time" + + "goftp/internal/config" +) + +// totpOf is the code of the base32 secret, steps of 30 seconds from now +// (RFC 6238). +func totpOf(t *testing.T, secret string, steps int64) string { + t.Helper() + key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(strings.ReplaceAll(secret, " ", "")) + if err != nil { + t.Fatal(err) + } + mac := hmac.New(sha1.New, key) + _ = binary.Write(mac, binary.BigEndian, time.Now().Unix()/30+steps) + sum := mac.Sum(nil) + offset := sum[len(sum)-1] & 0x0f + return fmt.Sprintf("%06d", (binary.BigEndian.Uint32(sum[offset:])&0x7fffffff)%1_000_000) +} + +var ( + secretShown = regexp.MustCompile(`id="totp-secret">([A-Z2-7 ]+)<`) + recoveryShown = regexp.MustCompile(`
  • ([a-z2-7]{5}-[a-z2-7]{5})
  • `) + challengeSent = regexp.MustCompile(`name="challenge" value="([A-Za-z0-9_-]{43})"`) +) + +// setUpTwoFactor turns two-factor sign-in on for the user of f from the +// page, and returns their secret, recovery codes and new session. +func setUpTwoFactor(t *testing.T, f *fixture) (string, []string, *fixture) { + t.Helper() + html := []string{"Accept", "text/html"} + resp, _ := post(t, f, twoFactorPath, "action=start", html...) + if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != twoFactorPath { + t.Fatalf("start: %d %v", resp.StatusCode, resp.Header) + } + _, body := f.do(t, "GET", twoFactorPath, html...) + m := secretShown.FindStringSubmatch(body) + if m == nil || !strings.Contains(body, ``) { + t.Error("no menu entry") + } + _, body := dora.do(t, "GET", twoFactorPath, html...) + if !strings.Contains(body, "Off: your password alone signs you in.") || !strings.Contains(body, `value="start"`) { + t.Errorf("off: %s", body) + } + secret, codes, dora := setUpTwoFactor(t, dora) + _, body = dora.do(t, "GET", twoFactorPath, html...) + if !strings.Contains(body, "On: after your password") || !strings.Contains(body, "10 of 10 left.") { + t.Errorf("on: %s", body) + } + if _, body := f.as("superadmin").do(t, "GET", usersPath, html...); !strings.Contains(body, "two-factor") { + t.Error("not shown to superadmins") + } + + // The password first, then a code. + form := func(kv ...string) (*http.Response, string) { + t.Helper() + r, k, v := formBody(kv...) + return f.as("").send(t, "POST", loginPath, r, k, v) + } + resp, body := form("username", "dora", "password", testPassword("dora"), "next", "/docs/") + m := challengeSent.FindStringSubmatch(body) + if resp.StatusCode != http.StatusOK || m == nil || !strings.Contains(body, "

    Two-factor sign-in

    ") || cookieOf(resp, cookieName) != nil { + t.Fatalf("after the password: %d %s", resp.StatusCode, body) + } + resp, body = form("challenge", m[1], "code", "000000", "next", "/docs/") + if resp.StatusCode != http.StatusUnauthorized || !strings.Contains(body, "Wrong code.") || !strings.Contains(body, m[1]) { + t.Errorf("a wrong code: %d %s", resp.StatusCode, body) + } + resp, _ = form("challenge", m[1], "code", totpOf(t, secret, 1), "next", "/docs/") + if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != "/docs/" || cookieOf(resp, cookieName) == nil { + t.Errorf("with the code: %d %v", resp.StatusCode, resp.Header) + } + resp, body = form("challenge", m[1], "code", totpOf(t, secret, 1)) + if resp.StatusCode != http.StatusUnauthorized || !strings.Contains(body, "sign in again") || challengeSent.MatchString(body) { + t.Errorf("twice: %d %s", resp.StatusCode, body) + } + if e := f.logs.entries("login"); len(e) == 0 || e[len(e)-1]["two_factor"] != true || e[len(e)-1]["recovery_code"] != false { + t.Errorf("logged: %v", e) + } + + // Recovery codes, after which the page says how many are left. + _, body = form("username", "dora", "password", testPassword("dora")) + m = challengeSent.FindStringSubmatch(body) + resp, _ = form("challenge", m[1], "code", strings.ToUpper(codes[0])) + if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != twoFactorPath+"?recovered=1" { + t.Fatalf("a recovery code: %d %v", resp.StatusCode, resp.Header) + } + _, body = f.as("").do(t, "GET", twoFactorPath+"?recovered=1", "Accept", "text/html", "Cookie", cookieName+"="+cookieOf(resp, cookieName).Value) + if !strings.Contains(body, "You signed in with a recovery code: 9 are left.") { + t.Errorf("recovered: %s", body) + } + + // Scripts, in two steps or one. + login := func(body string) (*http.Response, map[string]any) { + t.Helper() + resp, raw := f.as("").send(t, "POST", loginPath, strings.NewReader(body), "Content-Type", "application/json") + var out map[string]any + _ = json.Unmarshal([]byte(raw), &out) + return resp, out + } + resp, out := login(`{"username":"dora","password":"` + testPassword("dora") + `"}`) + challenge, _ := out["challenge"].(string) + if resp.StatusCode != http.StatusUnauthorized || out["two_factor"] != true || len(challenge) != 43 { + t.Fatalf("without a code: %d %v", resp.StatusCode, out) + } + if resp, out := login(`{"challenge":"` + challenge + `","code":"` + codes[1] + `"}`); resp.StatusCode != http.StatusOK || len(out["token"].(string)) != 43 { + t.Errorf("with a code: %d %v", resp.StatusCode, out) + } + if resp, _ := login(`{"username":"dora","password":"` + testPassword("dora") + `","code":"` + codes[2] + `"}`); resp.StatusCode != http.StatusOK { + t.Errorf("in one step: %d", resp.StatusCode) + } + if resp, _ := login(`{"username":"dora","password":"` + testPassword("dora") + `","code":"` + codes[2] + `"}`); resp.StatusCode != http.StatusUnauthorized { + t.Errorf("a code used again: %d", resp.StatusCode) + } + + // New recovery codes, and turning it off, take the password. + resp, body = post(t, dora, twoFactorPath, "action=codes&password=wrong") + if resp.StatusCode != http.StatusForbidden { + t.Errorf("new codes, wrong password: %d %s", resp.StatusCode, body) + } + resp, body = post(t, dora, twoFactorPath, "action=codes&password="+testPassword("dora"), html...) + if resp.StatusCode != http.StatusOK || len(recoveryShown.FindAllString(body, -1)) != 10 || !strings.Contains(body, "the old ones no longer work") { + t.Errorf("new codes: %d %s", resp.StatusCode, body) + } + if resp, _ := post(t, dora, twoFactorPath, "action=off&password=wrong"); resp.StatusCode != http.StatusForbidden { + t.Errorf("off, wrong password: %d", resp.StatusCode) + } + resp, _ = post(t, dora, twoFactorPath, "action=off&password="+testPassword("dora"), html...) + if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != twoFactorPath+"?done=off" { + t.Errorf("off: %d %v", resp.StatusCode, resp.Header) + } + if resp, _ := form("username", "dora", "password", testPassword("dora")); resp.StatusCode != http.StatusSeeOther { + t.Errorf("signing in when off: %d", resp.StatusCode) + } + + // Superadmins turn it off for those who lost their app. + _, _, dora = setUpTwoFactor(t, dora) + resp, _ = post(t, f.as("superadmin"), usersPath, "action=two-factor-off&user=dora", html...) + if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != usersPath+"?done=two-factor" { + t.Errorf("reset: %d %v", resp.StatusCode, resp.Header) + } + if resp, _ := form("username", "dora", "password", testPassword("dora")); resp.StatusCode != http.StatusSeeOther { + t.Errorf("signing in after the reset: %d", resp.StatusCode) + } + if e := f.logs.entries("two-factor sign-in turned off"); len(e) != 1 || e[0]["target"] != "dora" { + t.Errorf("reset logged: %v", e) + } +} + +// Wrong codes count against the client's budget, as wrong passwords do. +func TestTwoFactorLimiter(t *testing.T) { + ta := newTestAuth(t) + f := newFixtureWith(t, ta, func(c *config.Config) { c.Limiter = config.LimiterConfig{MaxFailures: 3, Window: time.Minute} }) + _, codes, _ := setUpTwoFactor(t, f.signedIn(ta.addUser(t, "dora", "user"))) + form := func(kv ...string) (*http.Response, string) { + t.Helper() + r, k, v := formBody(kv...) + return f.as("").send(t, "POST", loginPath, r, k, v) + } + _, body := form("username", "dora", "password", testPassword("dora")) + m := challengeSent.FindStringSubmatch(body) + if m == nil { + t.Fatal(html.UnescapeString(body)) + } + for range 3 { + if resp, _ := form("challenge", m[1], "code", "000000"); resp.StatusCode != http.StatusUnauthorized { + t.Errorf("a wrong code: %d", resp.StatusCode) + } + } + if resp, _ := form("challenge", m[1], "code", codes[0]); resp.StatusCode != http.StatusTooManyRequests || resp.Header.Get("Retry-After") == "" { + t.Errorf("after the budget: %d", resp.StatusCode) + } +}