-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathauthcookie.go
181 lines (166 loc) · 5.68 KB
/
authcookie.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
// Package authcookie implements creation and verification of signed
// authentication cookies.
//
// Cookie is a Base64 encoded (using URLEncoding, from RFC 4648) string, which
// consists of concatenation of expiration time, login, and signature:
//
// expiration time || login || signature
//
// where expiration time is the number of seconds since Unix epoch UTC
// indicating when this cookie must expire (4 bytes, big-endian, uint32), login
// is a byte string of arbitrary length (at least 1 byte, not null-terminated),
// and signature is 32 bytes of HMAC-SHA256(expiration_time || login, k), where
// k = HMAC-SHA256(expiration_time || login, secret key).
//
// Example:
//
// secret := []byte("my secret key")
//
// // Generate cookie valid for 24 hours for user "bender"
// cookie := authcookie.NewSinceNow("bender", 24 * time.Hour, secret)
//
// // cookie is now:
// // Tajh02JlbmRlcskYMxowgwPj5QZ94jaxhDoh3n0Yp4hgGtUpeO0YbMTY
// // send it to user's browser..
//
// // To authenticate a user later, receive cookie and:
// login := authcookie.Login(cookie, secret)
// if login != "" {
// // access for login granted
// } else {
// // access denied
// }
//
// Note that login and expiration time are not encrypted, they are only signed
// and Base64 encoded.
//
// For safety, the maximum length of base64-decoded cookie is limited to 1024
// bytes.
package authcookie
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/binary"
"errors"
"strings"
"time"
)
const (
decodedMinLength = 4 /*expiration*/ + 1 /*login*/ + 32 /*signature*/
decodedMaxLength = 1024 /* maximum decoded length, for safety */
)
// MinLength is the minimum allowed length of cookie string.
//
// It is useful for avoiding DoS attacks with too long cookies: before passing
// a cookie to Parse or Login functions, check that it has length less than the
// [maximum login length allowed in your application] + MinLength.
var MinLength = base64.URLEncoding.EncodedLen(decodedMinLength)
// MinLengthNoPadding is like MinLength for tokens without base64 padding.
var MinLengthNoPadding = base64.RawURLEncoding.EncodedLen(decodedMinLength)
func getSignature(b []byte, secret []byte) []byte {
keym := hmac.New(sha256.New, secret)
keym.Write(b)
m := hmac.New(sha256.New, keym.Sum(nil))
m.Write(b)
return m.Sum(nil)
}
var (
ErrMalformedCookie = errors.New("malformed cookie")
ErrWrongSignature = errors.New("wrong cookie signature")
)
// New returns a signed authentication cookie for the given login,
// expiration time, and secret key.
// If the login is empty, the function returns an empty string.
func New(login string, expires time.Time, secret []byte) string {
return newCookie(login, expires, secret, false)
}
// NewNoPadding is like New but returns cookie encoded without base64 padding characters.
func NewNoPadding(login string, expires time.Time, secret []byte) string {
return newCookie(login, expires, secret, true)
}
func newCookie(login string, expires time.Time, secret []byte, noPadding bool) string {
if login == "" {
return ""
}
llen := len(login)
b := make([]byte, llen+4+32)
// Put expiration time.
binary.BigEndian.PutUint32(b, uint32(expires.Unix()))
// Put login.
copy(b[4:], []byte(login))
// Calculate and put signature.
sig := getSignature([]byte(b[:4+llen]), secret)
copy(b[4+llen:], sig)
// Base64-encode.
if noPadding {
return base64.RawURLEncoding.EncodeToString(b)
}
return base64.URLEncoding.EncodeToString(b)
}
// NewSinceNow returns a signed authetication cookie for the given login,
// duration since current time, and secret key.
func NewSinceNow(login string, dur time.Duration, secret []byte) string {
return newCookie(login, time.Now().Add(dur), secret, false)
}
// NewSinceNowNoPadding is like NewSinceNow but returns a cookie without base64 padding characters.
func NewSinceNowNoPadding(login string, dur time.Duration, secret []byte) string {
return newCookie(login, time.Now().Add(dur), secret, true)
}
// Parse verifies the given cookie with the secret key and returns login and
// expiration time extracted from the cookie. If the cookie fails verification
// or is not well-formed, the function returns an error.
//
// Callers must:
//
// 1. Check for the returned error and deny access if it's present.
//
// 2. Check the returned expiration time and deny access if it's in the past.
//
func Parse(cookie string, secret []byte) (login string, expires time.Time, err error) {
var b []byte
encoding := base64.RawURLEncoding
// If we have padding, use URLEncoding instead of RawURLEncoding.
if strings.LastIndexByte(cookie, '=') != -1 {
encoding = base64.URLEncoding
}
blen := encoding.DecodedLen(len(cookie))
// Avoid allocation if cookie is too short or too long.
if blen < decodedMinLength || blen > decodedMaxLength {
err = ErrMalformedCookie
return
}
b, err = encoding.DecodeString(cookie)
if err != nil {
return
}
// Decoded length may be different from max length, which
// we allocated, so check it, and set new length for b.
blen = len(b)
if blen < decodedMinLength {
err = ErrMalformedCookie
return
}
b = b[:blen]
sig := b[blen-32:]
data := b[:blen-32]
realSig := getSignature(data, secret)
if subtle.ConstantTimeCompare(realSig, sig) != 1 {
err = ErrWrongSignature
return
}
expires = time.Unix(int64(binary.BigEndian.Uint32(data[:4])), 0)
login = string(data[4:])
return
}
// Login returns a valid login extracted from the given cookie and verified
// using the given secret key. If verification fails or the cookie expired,
// the function returns an empty string.
func Login(cookie string, secret []byte) string {
l, exp, err := Parse(cookie, secret)
if err != nil || exp.Before(time.Now()) {
return ""
}
return l
}