Two-factor sign-in
+Enter the code your authenticator app shows for this site, or one of your recovery codes.
+ +Sign in
Welcome back. Sign in to browse and share files.
No account yet? Ask your administrator to create one.
+ {{end}}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 @@
Enter the code your authenticator app shows for this site, or one of your recovery codes.
+ +Welcome back. Sign in to browse and share files.
No account yet? Ask your administrator to create one.
+ {{end}}{{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}}
+{{.CodesLeft}} of 10 left. New ones replace them all.
+ +Your password alone will sign you in again.
+ +Scan the code with the app, or enter this key in it by hand:
+{{.Secret}}
On this phone? Open it in the app.
+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.
+ +