-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
258 lines (214 loc) · 6.74 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package optauth
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base32"
"encoding/binary"
"errors"
"fmt"
"hash"
"math"
"net/url"
"sort"
"strconv"
"time"
"math/rand"
)
var src = rand.NewSource(time.Now().UnixNano())
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
// ComputeCode computes the response code for a 64-bit challenge 'value' using the secret 'secret'.
// To avoid breaking compatibility with the previous API, it returns an invalid code (-1) when an error occurs,
// but does not silently ignore them (it forces a mismatch so the code will be rejected).
func ComputeCode(secret string, value int64) int {
key, err := base32.StdEncoding.DecodeString(secret)
if err != nil {
return -1
}
hash := hmac.New(sha1.New, key)
err = binary.Write(hash, binary.BigEndian, value)
if err != nil {
return -1
}
h := hash.Sum(nil)
offset := h[19] & 0x0f
truncated := binary.BigEndian.Uint32(h[offset : offset+4])
truncated &= 0x7fffffff
code := truncated % 1000000
return int(code)
}
func GetTs() int64 {
un := float64(time.Now().UnixNano()) / float64(1000) / float64(30)
return int64(math.Floor(un))
}
// GenSecret secret key
func GenSecretKey() (string, error) {
hmacHash := sha1.New()
buf := bytes.Buffer{}
err := binary.Write(&buf, binary.BigEndian, GetTs())
if err != nil {
return "", err
}
h := hmac.New(func() hash.Hash { return hmacHash }, buf.Bytes())
hSum := fmt.Sprintf("%x", h.Sum(nil)) + RandStringBytesMaskImprSrc(5)
secKey := base32.StdEncoding.EncodeToString([]byte(hSum))
return secKey, nil
}
func RandStringBytesMaskImprSrc(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// ErrInvalidCode indicate the supplied one-time code was not valid
var (
ErrInvalidCode = errors.New("invalid code")
ErrCipherNotFound = errors.New("cipher not supported")
)
// OTPConfig is a one-time-password configuration. This object will be modified by calls to
// Authenticate and should be saved to ensure the codes are in fact only used
// once.
type OTPConfig struct {
Secret string // 80-bit base32 encoded string of the user's secret
WindowSize int // valid range: technically 0..100 or so, but beyond 3-5 is probably bad security
HotpCounter int // the current otp counter. 0 if the user uses time-based codes instead.
DisallowReuse []int // timestamps in the current window unavailable for re-use
ScratchCodes []int // an array of 8-digit numeric codes that can be used to log in
UTC bool // use UTC for the timestamp instead of local time
}
func InitOTPConfig(secret string) OTPConfig {
return OTPConfig{
Secret: secret,
WindowSize: 5,
HotpCounter: 0,
DisallowReuse: nil,
ScratchCodes: nil,
UTC: false,
}
}
// Authenticate a one-time-password against the given OTPConfig
// Returns true/false if the authentication was successful.
// Returns error if the password is incorrectly formatted (not a zero-padded 6 or non-zero-padded 8 digit number).
func (c *OTPConfig) Authenticate(password string) (bool, error) {
var scratch bool
switch {
case len(password) == 6 && password[0] >= '0' && password[0] <= '9':
break
case len(password) == 8 && password[0] >= '1' && password[0] <= '9':
scratch = true
break
default:
return false, ErrInvalidCode
}
code, err := strconv.Atoi(password)
if err != nil {
return false, ErrInvalidCode
}
if scratch {
return c.checkScratchCodes(code), nil
}
// we have a counter value we can use
if c.HotpCounter > 0 {
return c.checkHotpCode(code), nil
}
var t0 int
// assume we're on Time-based OTP
if c.UTC {
t0 = int(time.Now().UTC().Unix() / 30)
} else {
t0 = int(time.Now().Unix() / 30)
}
return c.checkTotpCode(t0, code), nil
}
func (c *OTPConfig) checkScratchCodes(code int) bool {
for i, v := range c.ScratchCodes {
if code == v {
// remove this code from the list of valid ones
l := len(c.ScratchCodes) - 1
c.ScratchCodes[i] = c.ScratchCodes[l] // copy last element over this element
c.ScratchCodes = c.ScratchCodes[0:l] // and trim the list length by 1
return true
}
}
return false
}
func (c *OTPConfig) checkHotpCode(code int) bool {
for i := 0; i < c.WindowSize; i++ {
if ComputeCode(c.Secret, int64(c.HotpCounter+i)) == code {
c.HotpCounter += i + 1
// We don't check for overflow here, which means you can only authenticate 2^63 times
// After that, the counter is negative and the above 'if' test will fail.
// This matches the behaviour of the PAM module.
return true
}
}
// we must always advance the counter if we tried to authenticate with it
c.HotpCounter++
return false
}
func (c *OTPConfig) checkTotpCode(t0, code int) bool {
minT := t0 - (c.WindowSize / 2)
maxT := t0 + (c.WindowSize / 2)
for t := minT; t <= maxT; t++ {
if ComputeCode(c.Secret, int64(t)) == code {
if c.DisallowReuse != nil {
for _, timeCode := range c.DisallowReuse {
if timeCode == t {
return false
}
}
// code hasn't been used before
c.DisallowReuse = append(c.DisallowReuse, t)
// remove all time codes outside of the valid window
sort.Ints(c.DisallowReuse)
min := 0
for c.DisallowReuse[min] < minT {
min++
}
// FIXME: check we don't have an off-by-one error here
c.DisallowReuse = c.DisallowReuse[min:]
}
return true
}
}
return false
}
// ProvisionURI generates a URI that can be turned into a QR code to configure
// a Google Authenticator mobile app.
func (c *OTPConfig) ProvisionURI(user string) string {
return c.ProvisionURIWithIssuer(user, "")
}
// ProvisionURIWithIssuer generates a URI that can be turned into a QR code
// to configure a Google Authenticator mobile app. It respects the recommendations
// on how to avoid conflicting accounts.
//
// Sttps://code.google.com/p/google-authenticator/wiki/ConflictingAccountsee h
func (c *OTPConfig) ProvisionURIWithIssuer(user string, issuer string) string {
auth := "totp/"
q := make(url.Values)
if c.HotpCounter > 0 {
auth = "hotp/"
q.Add("counter", strconv.Itoa(c.HotpCounter))
}
q.Add("secret", c.Secret)
if issuer != "" {
q.Add("issuer", issuer)
auth += issuer + ":"
}
return "otpauth://" + auth + user + "?" + q.Encode()
}