87 lines
2.3 KiB
Go
87 lines
2.3 KiB
Go
package auth
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha1"
|
|
"crypto/sha256"
|
|
"encoding/base32"
|
|
"encoding/binary"
|
|
"fmt"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
totpPeriod = int64(30)
|
|
totpDigits = 6
|
|
)
|
|
|
|
func NewTOTPSecret() (string, error) {
|
|
random := make([]byte, 20)
|
|
if _, err := rand.Read(random); err != nil {
|
|
return "", err
|
|
}
|
|
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(random), nil
|
|
}
|
|
|
|
func TOTPURI(secret, account string) string {
|
|
label := url.PathEscape("Sea vHost:" + account)
|
|
query := url.Values{"secret": {secret}, "issuer": {"Sea vHost"}, "algorithm": {"SHA1"}, "digits": {strconv.Itoa(totpDigits)}, "period": {strconv.FormatInt(totpPeriod, 10)}}
|
|
return "otpauth://totp/" + label + "?" + query.Encode()
|
|
}
|
|
|
|
func VerifyTOTP(secret, code string, now time.Time) bool {
|
|
code = strings.TrimSpace(code)
|
|
if len(code) != totpDigits {
|
|
return false
|
|
}
|
|
for _, character := range code {
|
|
if character < '0' || character > '9' {
|
|
return false
|
|
}
|
|
}
|
|
for offset := int64(-1); offset <= 1; offset++ {
|
|
if hmac.Equal([]byte(code), []byte(totpAt(secret, now.Unix()/totpPeriod+offset))) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func totpAt(secret string, counter int64) string {
|
|
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(strings.ToUpper(secret))
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
message := make([]byte, 8)
|
|
binary.BigEndian.PutUint64(message, uint64(counter))
|
|
mac := hmac.New(sha1.New, key)
|
|
_, _ = mac.Write(message)
|
|
digest := mac.Sum(nil)
|
|
offset := digest[len(digest)-1] & 0x0f
|
|
value := binary.BigEndian.Uint32(digest[offset:offset+4]) & 0x7fffffff
|
|
return fmt.Sprintf("%0*d", totpDigits, value%1000000)
|
|
}
|
|
|
|
func NewRecoveryCodes(count int) ([]string, error) {
|
|
codes := make([]string, 0, count)
|
|
for len(codes) < count {
|
|
random := make([]byte, 8)
|
|
if _, err := rand.Read(random); err != nil {
|
|
return nil, err
|
|
}
|
|
encoded := strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(random))
|
|
codes = append(codes, encoded[:4]+"-"+encoded[4:8]+"-"+encoded[8:12])
|
|
}
|
|
return codes, nil
|
|
}
|
|
|
|
func RecoveryCodeHash(code string) []byte {
|
|
normalized := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(code), "-", ""))
|
|
hash := sha256.Sum256([]byte("sea-vhost/mfa-recovery/v1\x00" + normalized))
|
|
return hash[:]
|
|
}
|