245 lines
9.4 KiB
Go
245 lines
9.4 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha1"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/base32"
|
|
"encoding/base64"
|
|
"encoding/binary"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func (s *Store) encryptAuthSecret(plain []byte) (string, error) {
|
|
block, err := aes.NewCipher(s.authKey)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err = rand.Read(nonce); err != nil {
|
|
return "", err
|
|
}
|
|
sealed := gcm.Seal(nonce, nonce, plain, nil)
|
|
return base64.RawStdEncoding.EncodeToString(sealed), nil
|
|
}
|
|
func (s *Store) decryptAuthSecret(encoded string) ([]byte, error) {
|
|
sealed, err := base64.RawStdEncoding.DecodeString(encoded)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
block, err := aes.NewCipher(s.authKey)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil || len(sealed) < gcm.NonceSize() {
|
|
return nil, errors.New("invalid encrypted secret")
|
|
}
|
|
return gcm.Open(nil, sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():], nil)
|
|
}
|
|
|
|
func (s *Store) BeginTOTPEnrollment(principalUUID string) (string, error) {
|
|
raw := make([]byte, 20)
|
|
if _, err := rand.Read(raw); err != nil {
|
|
return "", err
|
|
}
|
|
secret := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw)
|
|
encrypted, err := s.encryptAuthSecret([]byte(secret))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
err = s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
|
_, err := tx.ExecContext(ctx, `INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,parameters_json,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(9)+`) ON CONFLICT(kind,identifier) DO UPDATE SET secret_hash=excluded.secret_hash,parameters_json='{}',enabled=0,updated_at_ms=excluded.updated_at_ms`, uuid.NewString(), principalUUID, "totp-pending", principalUUID, encrypted, "{}", 0, now, now)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return secret, nil
|
|
}
|
|
func totpCode(secret string, counter int64) (string, error) {
|
|
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(strings.ToUpper(secret))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
buf := make([]byte, 8)
|
|
binary.BigEndian.PutUint64(buf, uint64(counter))
|
|
mac := hmac.New(sha1.New, key)
|
|
_, _ = mac.Write(buf)
|
|
sum := mac.Sum(nil)
|
|
offset := sum[len(sum)-1] & 15
|
|
value := (uint32(sum[offset])&0x7f)<<24 | uint32(sum[offset+1])<<16 | uint32(sum[offset+2])<<8 | uint32(sum[offset+3])
|
|
return fmt.Sprintf("%06d", value%1000000), nil
|
|
}
|
|
func verifyTOTPCode(secret, code string, last int64) (int64, bool) {
|
|
code = strings.TrimSpace(code)
|
|
now := time.Now().Unix() / 30
|
|
for delta := int64(-1); delta <= 1; delta++ {
|
|
counter := now + delta
|
|
if counter <= last {
|
|
continue
|
|
}
|
|
expected, err := totpCode(secret, counter)
|
|
if err == nil && hmac.Equal([]byte(expected), []byte(code)) {
|
|
return counter, true
|
|
}
|
|
}
|
|
return 0, false
|
|
}
|
|
func (s *Store) confirmTOTP(ctx context.Context, tx *sql.Tx, principalUUID, kind, code string) (int64, error) {
|
|
var encrypted, params string
|
|
err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT secret_hash,parameters_json FROM auth_credentials WHERE principal_uuid=%s AND kind=%s AND identifier=%s AND (kind='totp-pending' OR enabled=1)`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), principalUUID, kind, principalUUID).Scan(&encrypted, ¶ms)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
plain, err := s.decryptAuthSecret(encrypted)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
var state struct {
|
|
LastCounter int64 `json:"last_counter"`
|
|
}
|
|
if json.Unmarshal([]byte(params), &state) != nil {
|
|
return 0, ErrAccessDenied
|
|
}
|
|
counter, ok := verifyTOTPCode(string(plain), code, state.LastCounter)
|
|
if !ok {
|
|
return 0, ErrAccessDenied
|
|
}
|
|
return counter, nil
|
|
}
|
|
func (s *Store) ConfirmTOTPEnrollment(principalUUID, code string) error {
|
|
return s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
|
counter, err := s.confirmTOTP(ctx, tx, principalUUID, "totp-pending", code)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
params, _ := json.Marshal(map[string]int64{"last_counter": counter})
|
|
if _, err = tx.ExecContext(ctx, `DELETE FROM auth_credentials WHERE principal_uuid=`+s.sqlParam(1)+` AND kind='totp'`, principalUUID); err != nil {
|
|
return err
|
|
}
|
|
result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE auth_credentials SET kind='totp',enabled=1,parameters_json=%s,updated_at_ms=%s WHERE principal_uuid=%s AND kind='totp-pending'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), string(params), time.Now().UnixMilli(), principalUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
n, err := result.RowsAffected()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n != 1 {
|
|
return ErrAccessDenied
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
func (s *Store) HasTOTP(principalUUID string) bool {
|
|
var exists bool
|
|
_ = s.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM auth_credentials WHERE principal_uuid=`+s.sqlParam(1)+` AND kind='totp' AND enabled=1)`, principalUUID).Scan(&exists)
|
|
return exists
|
|
}
|
|
func (s *Store) PendingTOTPSecret(principalUUID string) string {
|
|
var encrypted string
|
|
if s.DB.QueryRow(`SELECT secret_hash FROM auth_credentials WHERE principal_uuid=`+s.sqlParam(1)+` AND kind='totp-pending'`, principalUUID).Scan(&encrypted) != nil {
|
|
return ""
|
|
}
|
|
plain, err := s.decryptAuthSecret(encrypted)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return string(plain)
|
|
}
|
|
func (s *Store) VerifyTOTP(principalUUID, code string) error {
|
|
return s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
|
// Validation and counter advancement share the same lock on both DBs.
|
|
// No JSON SQL dialect is needed, and enrollment cannot race verification.
|
|
counter, err := s.confirmTOTP(ctx, tx, principalUUID, "totp", code)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
params, _ := json.Marshal(map[string]int64{"last_counter": counter})
|
|
_, err = tx.ExecContext(ctx, fmt.Sprintf(`UPDATE auth_credentials SET parameters_json=%s,updated_at_ms=%s WHERE principal_uuid=%s AND kind='totp' AND enabled=1`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), string(params), time.Now().UnixMilli(), principalUUID)
|
|
return err
|
|
})
|
|
}
|
|
func (s *Store) DisableTOTP(principalUUID string) error {
|
|
return s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
|
_, err := tx.ExecContext(ctx, `DELETE FROM auth_credentials WHERE principal_uuid=`+s.sqlParam(1)+` AND kind IN ('totp','totp-pending')`, principalUUID)
|
|
return err
|
|
})
|
|
}
|
|
|
|
func TOTPURI(secret, account, issuer string) string {
|
|
query := url.Values{"secret": {secret}, "issuer": {issuer}, "algorithm": {"SHA1"}, "digits": {"6"}, "period": {"30"}}
|
|
return "otpauth://totp/" + url.PathEscape(issuer+":"+account) + "?" + query.Encode()
|
|
}
|
|
|
|
func (s *Store) CreateTOTPLoginChallenge(domainUUID, principalUUID string) (string, error) {
|
|
return s.CreateTOTPLoginChallengeForLogin(domainUUID, principalUUID, false)
|
|
}
|
|
|
|
func (s *Store) CreateTOTPLoginChallengeForLogin(domainUUID, principalUUID string, remember bool) (string, error) {
|
|
token, hash, err := authToken()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
payload, _ := json.Marshal(map[string]any{"principal_uuid": principalUUID, "remember": remember})
|
|
_, err = s.DB.Exec(`INSERT INTO auth_challenges(uuid,domain_uuid,principal_uuid,kind,token_hash,payload_json,expires_at_ms,created_at_ms) VALUES(`+s.sqlValues(8)+`)`, uuid.NewString(), domainUUID, principalUUID, "totp-login", hash, string(payload), now+5*60*1000, now)
|
|
if err != nil {
|
|
return "", s.sqlError("TOTP login challenge", err)
|
|
}
|
|
return token, nil
|
|
}
|
|
func (s *Store) CompleteTOTPLoginChallenge(domainUUID, token, code string) (string, error) {
|
|
id, _, err := s.CompleteTOTPLoginChallengeForLogin(domainUUID, token, code)
|
|
return id, err
|
|
}
|
|
|
|
func (s *Store) CompleteTOTPLoginChallengeForLogin(domainUUID, token, code string) (string, bool, error) {
|
|
sum := sha256.Sum256([]byte(token))
|
|
hash := base64.RawURLEncoding.EncodeToString(sum[:])
|
|
var challengeUUID, principalUUID, payload string
|
|
var expires int64
|
|
var attempts int
|
|
err := s.DB.QueryRow(fmt.Sprintf(`SELECT uuid,principal_uuid,expires_at_ms,attempt_count,payload_json FROM auth_challenges WHERE domain_uuid=%s AND kind='totp-login' AND token_hash=%s AND consumed_at_ms=0`, s.sqlParam(1), s.sqlParam(2)), domainUUID, hash).Scan(&challengeUUID, &principalUUID, &expires, &attempts, &payload)
|
|
if err != nil || expires < time.Now().UnixMilli() || attempts >= 5 {
|
|
return "", false, ErrAccessDenied
|
|
}
|
|
var options struct {
|
|
Remember bool `json:"remember"`
|
|
}
|
|
if json.Unmarshal([]byte(payload), &options) != nil {
|
|
return "", false, ErrAccessDenied
|
|
}
|
|
if err = s.VerifyTOTP(principalUUID, code); err != nil {
|
|
_, _ = s.DB.Exec(fmt.Sprintf(`UPDATE auth_challenges SET attempt_count=attempt_count+1,consumed_at_ms=CASE WHEN attempt_count+1>=5 THEN %s ELSE consumed_at_ms END WHERE uuid=%s AND consumed_at_ms=0`, s.sqlParam(1), s.sqlParam(2)), time.Now().UnixMilli(), challengeUUID)
|
|
return "", false, err
|
|
}
|
|
result, err := s.DB.Exec(fmt.Sprintf(`UPDATE auth_challenges SET consumed_at_ms=%s WHERE uuid=%s AND consumed_at_ms=0 AND attempt_count<5 AND expires_at_ms>%s`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), time.Now().UnixMilli(), challengeUUID, time.Now().UnixMilli())
|
|
if err != nil {
|
|
return "", false, s.sqlError("TOTP challenge consumption", err)
|
|
}
|
|
changed, _ := result.RowsAffected()
|
|
if changed != 1 {
|
|
return "", false, ErrAccessDenied
|
|
}
|
|
return principalUUID, options.Remember, nil
|
|
}
|