-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashauth.go
535 lines (447 loc) · 12.4 KB
/
hashauth.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/*
Package hashauth provides a means of creating a cookie- and url-friendly token
containing arbitrary encoded information, with an embedded authentication code
that ensures that it was created by you (not forged) and is in its original
form (not tampered with).
Primary use-cases are login sessions, password reset tokens, and the like. Any
situation where you need to provide to the user a token they can present back
to you which contains a small amount of data and authentication guarantees.
The package provides methods for Encoding, Validating, and Decoding tokens,
and also a higher-level API for interacting with HTTP request and response
cookies for sessions.
Login session example:
var Signer = hashauth.New([]byte("secret key"), nil)
type LoginSession struct {
UserID int
Expiration time.Time
}
// implementing this method causes hashauth to set the Expires cookie attr
func (sess *LoginSession) Expires() time.Time {
return sess.Expiration
}
func AuthRequired(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sess := new(LoginSession)
err := Signer.Authenticate(r, sess)
if err != nil {
http.Error(w, "Login Required", http.StatusForbidden)
} else {
h.ServeHTTP(w, r)
}
})
}
func LogUserIn(w http.ResponseWriter, uid int) error {
return Signer.SetCookie(w, &LoginSession{
UserID: uid,
Expiration: time.Now().UTC().Add(7*24*time.Hour),
})
}
func LogUserOut(w http.ResponseWriter) {
Signer.ClearCookie(w)
}
*/
package hashauth
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"hash"
"io"
"math"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/ugorji/go/codec"
)
const (
oldPadChar = '.'
padChar = '~'
)
var (
// ErrInvalid is returned when an authentication check fails.
ErrInvalid = errors.New("hashauth: token validation failed")
// ErrExpired is returned when an Expirer session indicates that
// an authentication token's expiration time has passed.
ErrExpired = errors.New("hashauth: expiration time has passed")
)
var (
defaultHasher = sha256.New
defaultCookieName = "_ha"
defaultPinLength = 5
mh codec.MsgpackHandle
)
// Options is a simple container for various HashAuth options.
type Options struct {
// The hash implementation to use. Defaults to sha256.New.
Hash func() hash.Hash
// A separate signing key to use for PIN codes (Pin() and CheckPin()
// methods). Defaults to the main signing key.
PINSignKey []byte
// The length of PIN codes generated by this HashAuth. Defaults to 5,
// has a maximum value of 18.
PINLength int
// The name of the cookie to use for Authenticate(), SetCookie(), and
// ClearCookie(). Defaults to "_ha".
CookieName string
// The 'path' attribute to use for the cookie. Defaults to none/empty.
CookiePath string
// The 'domain' attribute for the cookie. Defaults to none/empty.
CookieDomain string
// Whether to include the 'secure' cookie attribute. Defaults to false.
CookieSecure bool
// Whether to include the 'httponly' cookie attribute. Defaults to false.
CookieHTTPOnly bool
}
// HashAuth is an Encoder and Decoder of tokens.
type HashAuth struct {
key []byte
hasher func() hash.Hash
pinKey []byte
pinLength int
cookieName string
cookiePath string
cookieDomain string
cookieSecure bool
cookieHTTPOnly bool
}
// Expirer can be implemented by session data types, in which case their
// expiration time will be set as the cookie expiration time in
// HashAuth.SetCookie.
type Expirer interface {
Expires() time.Time
}
// MaxAger can be implemented by session data types, in which case the
// HashAuth.SetCookie method will set a max-age attribute (unless it
// also implements Expirer, which takes precedence).
type MaxAger interface {
MaxAge() time.Duration
}
// New creates a new HashAuth En/Decoder.
// key should be a carefully guarded secret, with it anyone could forge a token.
// opts can be nil, in which case a sha256 hasher, a default cookie name, and
// no cookie attributes will be used.
func New(key []byte, opts *Options) *HashAuth {
if opts == nil {
opts = &Options{}
}
hasher := opts.Hash
if hasher == nil {
hasher = defaultHasher
}
pinKey := opts.PINSignKey
if len(pinKey) == 0 {
pinKey = key
}
pinLen := opts.PINLength
if pinLen == 0 {
pinLen = defaultPinLength
}
if pinLen > 18 {
panic("hashauth: can't handle a length > 18")
}
cname := opts.CookieName
if cname == "" {
cname = defaultCookieName
}
return &HashAuth{
key: key,
hasher: hasher,
pinKey: pinKey,
pinLength: pinLen,
cookieName: cname,
cookiePath: opts.CookiePath,
cookieDomain: opts.CookieDomain,
cookieSecure: opts.CookieSecure,
cookieHTTPOnly: opts.CookieHTTPOnly,
}
}
// Encode produces a signed token with session data.
func (ha *HashAuth) Encode(session interface{}) ([]byte, error) {
buf := &bytes.Buffer{}
err := encodeKeyless(buf, session)
if err != nil {
return nil, err
}
hasher := hmac.New(ha.hasher, ha.key)
hasher.Write(buf.Bytes())
mac := hasher.Sum(nil)
_, err = buf.Write(mac)
if err != nil {
return nil, err
}
return b64encode(buf.Bytes()), nil
}
// Validate tests a token's signature and returns whether it it valid.
func (ha *HashAuth) Validate(token []byte) bool {
token, err := b64decode(token)
if err != nil {
return false
}
return ha.validate(token)
}
func (ha *HashAuth) validate(token []byte) bool {
hashSize := ha.hasher().Size()
length := len(token)
if length < hashSize+1 {
return false
}
hasher := hmac.New(ha.hasher, ha.key)
hasher.Write(token[:length-hasher.Size()])
mac1 := token[length-hasher.Size():]
mac2 := hasher.Sum(nil)
if !hmac.Equal(mac1, mac2) {
return false
}
return true
}
// Decode checks a token's validity and extracts the data encoded in it.
// May return ErrInvalid if the validity check fails. If the container
// is an Expirer and the token contains an expired session, it will
// return ErrExpired but still populate the container with token data.
func (ha *HashAuth) Decode(token []byte, container interface{}) error {
token, err := b64decode(token)
if err != nil {
return err
}
if !ha.validate(token) {
return ErrInvalid
}
buf := bytes.NewBuffer(token[:len(token)-ha.hasher().Size()])
if err := decodeKeyless(container, buf); err != nil {
return err
}
if expirer, ok := container.(Expirer); ok {
if expirer.Expires().Before(time.Now()) {
return ErrExpired
}
}
return nil
}
// Pin generates a PIN code (string of a decimal number) from a token.
func (ha *HashAuth) Pin(token []byte) (string, error) {
// use the pinKey to get an hmac of the token
hasher := hmac.New(ha.hasher, ha.pinKey)
hasher.Write(token)
num := readInt(hasher.Sum(nil))
// cut it off at the length and pad with 0s if necessary
form := fmt.Sprintf("%%0%dd", ha.pinLength)
num = num % uint64(math.Pow10(ha.pinLength))
return fmt.Sprintf(form, int(num)), nil
}
// CheckPin validates a PIN code for a given token.
func (ha *HashAuth) CheckPin(pin string, token []byte) bool {
if len(pin) != ha.pinLength {
return false
}
realPin, err := ha.Pin(token)
if err != nil {
return false
}
return subtle.ConstantTimeCompare([]byte(pin), []byte(realPin)) == 1
}
// Authenticate finds and decodes the auth token from a request, populating
// the container with the session data.
// It will return nil on success, or:
// - http.ErrNoCookie if there is no auth header at all
// - a decoding error if it is malformed
// - ErrInvalid if there is a properly formatted token that is invalid
// - ErrExpired if the session has expired
func (ha *HashAuth) Authenticate(r *http.Request, container interface{}) error {
cookie, err := r.Cookie(ha.cookieName)
if err != nil {
return err
}
return ha.Decode([]byte(cookie.Value), container)
}
// SetCookie adds an encoded token as a cookie on an HTTP response.
// If the provided session data object implements the Expirer or MaxAger
// interfaces, then the corresponding cookie attribute will also be set.
// Other cookie attributes will be set according to the *Options with
// which the HashAuth was created.
func (ha *HashAuth) SetCookie(w http.ResponseWriter, session interface{}) error {
token, err := ha.Encode(session)
if err != nil {
return err
}
cookie := &http.Cookie{
Name: ha.cookieName,
Value: string(token),
Path: ha.cookiePath,
Domain: ha.cookieDomain,
Secure: ha.cookieSecure,
HttpOnly: ha.cookieHTTPOnly,
}
augmentCookie(cookie, session)
w.Header().Add("Set-Cookie", fmtCookie(cookie))
return nil
}
// ClearCookie adds a Set-Cookie header to a response that will remove
// the auth cookie.
func (ha *HashAuth) ClearCookie(w http.ResponseWriter) {
w.Header().Add("Set-Cookie", fmtCookie(&http.Cookie{
Name: ha.cookieName,
Value: "",
Path: ha.cookiePath,
Domain: ha.cookieDomain,
Secure: ha.cookieSecure,
HttpOnly: ha.cookieHTTPOnly,
MaxAge: -1,
}))
}
func augmentCookie(cookie *http.Cookie, session interface{}) {
var (
expire time.Time
maxage time.Duration
)
if sess, ok := session.(Expirer); ok {
expire = sess.Expires().UTC()
}
if !expire.IsZero() {
s := expire.Format(time.RFC1123)
if strings.HasSuffix(s, "UTC") {
//TODO: find out exactly: for which browsers is this necessary?
s = s[:len(s)-3] + "GMT"
}
cookie.RawExpires = s
return
}
if sess, ok := session.(MaxAger); ok {
maxage = sess.MaxAge()
}
if maxage != 0 {
cookie.MaxAge = int(maxage / time.Second)
}
}
func fmtCookie(cookie *http.Cookie) string {
cookie.Expires = time.Time{}
if len(cookie.RawExpires) > 0 {
return fmt.Sprintf("%s; Expires=%s", cookie.String(), cookie.RawExpires)
}
return cookie.String()
}
func b64encode(plain []byte) []byte {
enc := make([]byte, base64.URLEncoding.EncodedLen(len(plain)))
base64.URLEncoding.Encode(enc, plain)
return bytes.Replace(enc, []byte{'='}, []byte{padChar}, -1)
}
func b64decode(enc []byte) ([]byte, error) {
plain := make([]byte, base64.URLEncoding.DecodedLen(len(enc)))
var padder byte = padChar
if enc[len(enc)-1] == oldPadChar {
padder = oldPadChar
}
enc = bytes.Replace(enc, []byte{padder}, []byte{'='}, -1)
n, err := base64.URLEncoding.Decode(plain, enc)
if err != nil {
return nil, err
}
return plain[:n], nil
}
func deref(val reflect.Value) reflect.Value {
kind := val.Kind()
for kind == reflect.Ptr || kind == reflect.Interface {
val = val.Elem()
kind = val.Kind()
}
return val
}
type keyDescriptor struct {
key string
version int
}
type keyDescriptors []keyDescriptor
func (kds keyDescriptors) Len() int {
return len(kds)
}
func (kds keyDescriptors) Less(i, j int) bool {
if kds[i].version != kds[j].version {
return kds[i].version < kds[j].version
}
return kds[i].key < kds[j].key
}
func (kds keyDescriptors) Swap(i, j int) {
kds[i], kds[j] = kds[j], kds[i]
}
func getKeys(t reflect.Type) []string {
if t.Kind() != reflect.Struct {
return nil
}
num := t.NumField()
kds := make(keyDescriptors, 0, num)
for i := 0; i < num; i++ {
field := t.Field(i)
key := field.Name
if key[0:1] != strings.ToUpper(key[0:1]) {
continue
}
var version int
v, err := strconv.Atoi(field.Tag.Get("version"))
if err == nil {
version = v
}
kds = append(kds, keyDescriptor{
key: key,
version: version,
})
}
sort.Sort(kds)
keys := make([]string, len(kds))
for i, kd := range kds {
keys[i] = kd.key
}
return keys
}
func encodeKeyless(w io.Writer, obj interface{}) error {
enc := codec.NewEncoder(w, &mh)
val := deref(reflect.ValueOf(obj))
var keys []string
if val.IsValid() && (val.Kind() == reflect.Struct || !val.IsNil()) {
keys = getKeys(val.Type())
}
if keys == nil {
return enc.Encode(obj)
}
for _, key := range keys {
err := enc.Encode(val.FieldByName(key).Interface())
if err != nil {
return err
}
}
return nil
}
func decodeKeyless(dest interface{}, r io.Reader) error {
dec := codec.NewDecoder(r, &mh)
val := deref(reflect.ValueOf(dest))
var keys []string
if val.IsValid() && (val.Kind() == reflect.Struct || !val.IsNil()) {
keys = getKeys(val.Type())
}
if keys == nil {
return dec.Decode(dest)
}
for _, key := range keys {
dest = val.FieldByName(key).Addr().Interface()
err := dec.Decode(&dest)
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return nil
}
func readInt(buf []byte) uint64 {
var result uint64
for _, b := range buf[:8] {
result = (result << 8) | uint64(b)
}
return result
}