Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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`) |
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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`)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
117 changes: 116 additions & 1 deletion internal/auth/authtest/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
package authtest

import (
"bytes"
"cmp"
"context"
"slices"
Expand All @@ -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 {
Expand All @@ -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.
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions internal/auth/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package auth

// TOTPCode is the code of secret for the time step, for tests.
var TOTPCode = totpCode
98 changes: 92 additions & 6 deletions internal/auth/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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))
}

Expand Down
Loading
Loading