227 lines
8.2 KiB
Go
227 lines
8.2 KiB
Go
package store
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha1"
|
|
"crypto/sha256"
|
|
"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.DB.Exec(`INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,parameters_json,enabled,created_at_ms,updated_at_ms) VALUES(?,?,?,?,?,'{}',0,?,?) 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, now, now)
|
|
return secret, err
|
|
}
|
|
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(principalUUID, kind, code string) (int64, error) {
|
|
var encrypted, params string
|
|
err := s.DB.QueryRow(`SELECT secret_hash,parameters_json FROM auth_credentials WHERE principal_uuid=? AND kind=? AND identifier=?`, 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"`
|
|
}
|
|
_ = json.Unmarshal([]byte(params), &state)
|
|
counter, ok := verifyTOTPCode(string(plain), code, state.LastCounter)
|
|
if !ok {
|
|
return 0, ErrAccessDenied
|
|
}
|
|
return counter, nil
|
|
}
|
|
func (s *Store) ConfirmTOTPEnrollment(principalUUID, code string) error {
|
|
counter, err := s.confirmTOTP(principalUUID, "totp-pending", code)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
params, _ := json.Marshal(map[string]int64{"last_counter": counter})
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
_, _ = tx.Exec(`DELETE FROM auth_credentials WHERE principal_uuid=? AND kind='totp'`, principalUUID)
|
|
_, err = tx.Exec(`UPDATE auth_credentials SET kind='totp',enabled=1,parameters_json=?,updated_at_ms=? WHERE principal_uuid=? AND kind='totp-pending'`, string(params), time.Now().UnixMilli(), principalUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
func (s *Store) HasTOTP(principalUUID string) bool {
|
|
var exists int
|
|
_ = s.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM auth_credentials WHERE principal_uuid=? AND kind='totp' AND enabled=1)`, principalUUID).Scan(&exists)
|
|
return exists != 0
|
|
}
|
|
func (s *Store) PendingTOTPSecret(principalUUID string) string {
|
|
var encrypted string
|
|
if s.DB.QueryRow(`SELECT secret_hash FROM auth_credentials WHERE principal_uuid=? 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 {
|
|
counter, err := s.confirmTOTP(principalUUID, "totp", code)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
params, _ := json.Marshal(map[string]int64{"last_counter": counter})
|
|
result, err := s.DB.Exec(`UPDATE auth_credentials SET parameters_json=?,updated_at_ms=? WHERE principal_uuid=? AND kind='totp' AND CAST(COALESCE(json_extract(parameters_json,'$.last_counter'),0) AS INTEGER)<?`, string(params), time.Now().UnixMilli(), principalUUID, counter)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
changed, _ := result.RowsAffected()
|
|
if changed != 1 {
|
|
return ErrAccessDenied
|
|
}
|
|
return nil
|
|
}
|
|
func (s *Store) DisableTOTP(principalUUID string) error {
|
|
_, err := s.DB.Exec(`DELETE FROM auth_credentials WHERE principal_uuid=? 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(?,?,?,?,?,?,?,?)`, uuid.NewString(), domainUUID, principalUUID, "totp-login", hash, string(payload), now+5*60*1000, now)
|
|
return token, err
|
|
}
|
|
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(`SELECT uuid,principal_uuid,expires_at_ms,attempt_count,payload_json FROM auth_challenges WHERE domain_uuid=? AND kind='totp-login' AND token_hash=? AND consumed_at_ms=0`, 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(`UPDATE auth_challenges SET attempt_count=attempt_count+1,consumed_at_ms=CASE WHEN attempt_count+1>=5 THEN ? ELSE consumed_at_ms END WHERE uuid=? AND consumed_at_ms=0`, time.Now().UnixMilli(), challengeUUID)
|
|
return "", false, err
|
|
}
|
|
result, err := s.DB.Exec(`UPDATE auth_challenges SET consumed_at_ms=? WHERE uuid=? AND consumed_at_ms=0`, time.Now().UnixMilli(), challengeUUID)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
changed, _ := result.RowsAffected()
|
|
if changed != 1 {
|
|
return "", false, ErrAccessDenied
|
|
}
|
|
return principalUUID, options.Remember, nil
|
|
}
|