仰望星辰工作室

miaopanel

miaopanel/ internal/security/security.go 5.5 KB · 212 行 原始文件
1// Package security implements password hashing, session tokens and TOTP.
2package security
3
4import (
5 "crypto/hmac"
6 "crypto/rand"
7 "crypto/sha1"
8 "crypto/sha256"
9 "crypto/subtle"
10 "encoding/base32"
11 "encoding/base64"
12 "encoding/binary"
13 "errors"
14 "fmt"
15 "strconv"
16 "strings"
17 "time"
18
19 "golang.org/x/crypto/argon2"
20)
21
22// Password parameters follow OWASP recommendations for argon2id.
23const (
24 argonMemory = 64 * 1024
25 argonTime = 3
26 argonThreads = 2
27 argonKeyLen = 32
28 argonSaltLen = 16
29)
30
31// HashPassword returns a PHC formatted argon2id hash.
32func HashPassword(password string) (string, error) {
33 if len(password) < 8 {
34 return "", errors.New("密码至少 8 位")
35 }
36 if len(password) > 128 {
37 return "", errors.New("密码不能超过 128 位")
38 }
39 salt := make([]byte, argonSaltLen)
40 if _, err := rand.Read(salt); err != nil {
41 return "", err
42 }
43 key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
44 return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
45 argon2.Version, argonMemory, argonTime, argonThreads,
46 base64.RawStdEncoding.EncodeToString(salt),
47 base64.RawStdEncoding.EncodeToString(key)), nil
48}
49
50// VerifyPassword compares a plaintext password against a PHC hash in constant
51// time. It never returns an error for malformed hashes: those are treated as a
52// failed verification.
53func VerifyPassword(hash, password string) bool {
54 parts := strings.Split(hash, "$")
55 if len(parts) != 6 || parts[1] != "argon2id" {
56 return false
57 }
58 var version int
59 if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
60 return false
61 }
62 var m, t uint32
63 var p uint8
64 if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &m, &t, &p); err != nil {
65 return false
66 }
67 salt, err := base64.RawStdEncoding.DecodeString(parts[4])
68 if err != nil {
69 return false
70 }
71 want, err := base64.RawStdEncoding.DecodeString(parts[5])
72 if err != nil {
73 return false
74 }
75 got := argon2.IDKey([]byte(password), salt, t, m, p, uint32(len(want)))
76 return subtle.ConstantTimeCompare(got, want) == 1
77}
78
79// Token returns a URL safe random token and its storage hash.
80func Token(n int) (plain, hashed string, err error) {
81 if n <= 0 {
82 n = 32
83 }
84 b := make([]byte, n)
85 if _, err = rand.Read(b); err != nil {
86 return "", "", err
87 }
88 plain = base64.RawURLEncoding.EncodeToString(b)
89 return plain, HashToken(plain), nil
90}
91
92// HashToken hashes a session token before it touches the database.
93func HashToken(token string) string {
94 sum := sha256.Sum256([]byte(token))
95 return fmt.Sprintf("%x", sum)
96}
97
98// RandomString returns n bytes of entropy encoded as base32 (no padding).
99func RandomString(n int) string {
100 b := make([]byte, n)
101 if _, err := rand.Read(b); err != nil {
102 return strings.Repeat("A", n*2)
103 }
104 return strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b))
105}
106
107// --- TOTP (RFC 6238) -------------------------------------------------------
108
109var b32 = base32.StdEncoding.WithPadding(base32.NoPadding)
110
111// NewTOTPSecret returns a 160 bit secret in base32.
112func NewTOTPSecret() string {
113 b := make([]byte, 20)
114 if _, err := rand.Read(b); err != nil {
115 return "JBSWY3DPEHPK3PXP"
116 }
117 return b32.EncodeToString(b)
118}
119
120// TOTPCode computes the 6 digit code for a given counter.
121func TOTPCode(secret string, counter uint64) (string, error) {
122 key, err := b32.DecodeString(strings.ToUpper(strings.TrimSpace(secret)))
123 if err != nil {
124 return "", fmt.Errorf("无效的动态口令密钥: %w", err)
125 }
126 var buf [8]byte
127 binary.BigEndian.PutUint64(buf[:], counter)
128 mac := hmac.New(sha1.New, key)
129 mac.Write(buf[:])
130 sum := mac.Sum(nil)
131 off := sum[len(sum)-1] & 0x0f
132 code := (uint32(sum[off]&0x7f) << 24) |
133 (uint32(sum[off+1]) << 16) |
134 (uint32(sum[off+2]) << 8) |
135 uint32(sum[off+3])
136 return fmt.Sprintf("%06d", code%1000000), nil
137}
138
139// VerifyTOTP accepts the current step plus one step of clock drift in each
140// direction.
141func VerifyTOTP(secret, code string, now time.Time) bool {
142 code = strings.TrimSpace(code)
143 if len(code) != 6 {
144 return false
145 }
146 step := uint64(now.Unix() / 30)
147 for _, d := range []int64{0, -1, 1} {
148 var c uint64
149 if d < 0 {
150 if step == 0 {
151 continue
152 }
153 c = step - 1
154 } else {
155 c = step + uint64(d)
156 }
157 want, err := TOTPCode(secret, c)
158 if err != nil {
159 return false
160 }
161 if subtle.ConstantTimeCompare([]byte(want), []byte(code)) == 1 {
162 return true
163 }
164 }
165 return false
166}
167
168// OTPAuthURL builds the provisioning URI for authenticator apps.
169func OTPAuthURL(issuer, account, secret string) string {
170 return fmt.Sprintf("otpauth://totp/%s:%s?secret=%s&issuer=%s&algorithm=SHA1&digits=6&period=30",
171 urlEscape(issuer), urlEscape(account), secret, urlEscape(issuer))
172}
173
174func urlEscape(s string) string {
175 return strings.NewReplacer(" ", "%20", ":", "%3A", "/", "%2F").Replace(s)
176}
177
178// NumericCode returns a cryptographically random numeric string of length n.
179func NumericCode(n int) string {
180 buf := make([]byte, n)
181 out := make([]byte, n)
182 if _, err := rand.Read(buf); err != nil {
183 return strings.Repeat("0", n)
184 }
185 for i, b := range buf {
186 out[i] = '0' + b%10
187 }
188 return string(out)
189}
190
191// RecoveryCodes generates n one-time recovery codes.
192func RecoveryCodes(n int) []string {
193 if n <= 0 {
194 n = 8
195 }
196 codes := make([]string, 0, n)
197 for i := 0; i < n; i++ {
198 raw := RandomString(10)
199 raw = strings.ToUpper(raw)
200 codes = append(codes, raw[:5]+"-"+raw[5:10])
201 }
202 return codes
203}
204
205// SecondsUntil returns a human readable expiry hint.
206func SecondsUntil(t time.Time) string {
207 d := time.Until(t)
208 if d < 0 {
209 return "已过期"
210 }
211 return strconv.Itoa(int(d.Seconds())) + "s"
212}