-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurecookie.go
More file actions
359 lines (333 loc) · 9.68 KB
/
securecookie.go
File metadata and controls
359 lines (333 loc) · 9.68 KB
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
// Copyright 2012 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package securecookie
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/gob"
"fmt"
"strconv"
"time"
"golang.org/x/crypto/chacha20poly1305"
)
func init() {
gob.Register([]any{})
}
var (
ErrKeyLength = fmt.Errorf("the key must be %d bytes", chacha20poly1305.KeySize)
ErrDecryptionFailed = fmt.Errorf("the value could not be decrypted")
ErrNoCodecs = fmt.Errorf("no codecs provided")
ErrValueNotByte = fmt.Errorf("the value is not a []byte")
ErrValueNotBytePtr = fmt.Errorf("the value is not a *[]byte")
ErrValueTooLong = fmt.Errorf("the value is too long")
ErrTimestampInvalid = fmt.Errorf("the timestamp is invalid")
ErrTimestampTooNew = fmt.Errorf("the timestamp is too new")
ErrTimestampExpired = fmt.Errorf("the timestamp is expired")
)
var DefaultOptions = &Options{
MinAge: 0,
MaxAge: 86400 * 30,
MaxLength: 4096,
Serializer: JSONEncoder{},
TimeFunc: func() int64 {
return time.Now().UTC().Unix()
},
}
// Codec defines an interface to encode and decode cookie values.
type Codec interface {
Encode(name string, value any) (string, error)
Decode(name, value string, dst any) (int64, error)
}
// New returns a new SecureCookie.
//
// Key is required and must be 32 bytes, used to authenticate and
// encrypt cookie values.
//
// Note that keys created using GenerateRandomKey() are not automatically
// persisted. New keys will be created when the application is restarted, and
// previously issued cookies will not be able to be decoded.
func New(key []byte, options *Options) (*SecureCookie, error) {
if len(key) != chacha20poly1305.KeySize {
return nil, ErrKeyLength
}
if options == nil {
options = DefaultOptions
}
if options.Serializer == nil {
options.Serializer = DefaultOptions.Serializer
}
if options.TimeFunc == nil {
options.TimeFunc = func() int64 {
return time.Now().UTC().Unix()
}
}
s := &SecureCookie{
key: key,
rotatedKeys: options.RotatedKeys,
minAge: options.MinAge,
maxAge: options.MaxAge,
maxLength: options.MaxLength,
sz: options.Serializer,
timeFunc: options.TimeFunc,
}
return s, nil
}
type Options struct {
RotatedKeys [][]byte
MinAge int64
MaxAge int64
MaxLength int
Serializer Serializer
TimeFunc func() int64
}
// SecureCookie encodes and decodes authenticated and optionally encrypted
// cookie values.
type SecureCookie struct {
key []byte
rotatedKeys [][]byte
maxLength int
maxAge int64
minAge int64
sz Serializer
// For testing purposes, the function that returns the current timestamp.
// If not set, it will use time.Now().UTC().Unix().
timeFunc func() int64
}
// Encode encodes a cookie value.
//
// It serializes, optionally encrypts, signs with a message authentication code,
// and finally encodes the value.
//
// The name argument is the cookie name. It is used to authenticate the cookie.
// The value argument is the value to be encoded. It can be any value that can
// be encoded using the currently selected serializer.
//
// It is the client's responsibility to ensure that value, when encoded using
// the current serialization/encryption settings on s and then base64-encoded,
// is shorter than the maximum permissible length.
func (s *SecureCookie) Encode(name string, value any) (string, error) {
var err error
var errors MultiError
var b []byte
// 1. Serialize.
if b, err = s.sz.Serialize(value); err != nil {
return "", err
}
// 2. Encrypt.
key := s.key
index := -1
walk:
// We can't directly use 'b' here because if the encryption fails, we need
// to retry with a different key.
enc, err := s.encrypt([]byte(name), key, b)
if err != nil {
errors = append(errors, err)
if index++; index < len(s.rotatedKeys) {
key = s.rotatedKeys[index]
goto walk
} else {
return "", errors
}
}
b = encode(enc)
// 3. Check length.
if s.maxLength != 0 && len(b) > s.maxLength {
return "", ErrValueTooLong
}
// Done.
return string(b), nil
}
// Decode decodes a cookie value.
//
// It decodes, verifies a message authentication code, optionally decrypts and
// finally deserializes the value.
//
// The name argument is the cookie name. It must be the same name used when
// it was encoded. The value argument is the encoded cookie value. The dst
// argument is where the cookie will be decoded. It must be a pointer.
func (s *SecureCookie) Decode(name, value string, dst any) (int64, error) {
var err error
var errors MultiError
// 1. Check length.
if s.maxLength != 0 && len(value) > s.maxLength {
return 0, ErrValueTooLong
}
// 2. Decode from base64.
b, err := decode([]byte(value))
if err != nil {
return 0, err
}
// 3. Decrypt.
key := s.key
index := -1
walk:
// We can't directly use 'b' here because if the decryption fails, we need
// to retry with a different key.
dec, err := s.decrypt([]byte(name), key, b)
if err != nil {
errors = append(errors, err)
if index++; index < len(s.rotatedKeys) {
key = s.rotatedKeys[index]
goto walk
} else {
return 0, errors
}
}
parts := bytes.SplitN(dec, []byte("|"), 2)
if len(parts) != 2 {
return 0, ErrDecryptionFailed
}
ts, err := strconv.ParseInt(string(parts[0]), 10, 64)
if err != nil {
return 0, ErrTimestampInvalid
}
now := s.timestamp()
if s.minAge != 0 && ts > now-s.minAge {
return ts, ErrTimestampTooNew
}
if s.maxAge != 0 && ts < now-s.maxAge {
return ts, ErrTimestampExpired
}
// 4. Deserialize.
if err = s.sz.Deserialize(parts[1], dst); err != nil {
return ts, err
}
// Done.
return ts, nil
}
// timestamp returns the current timestamp, in seconds.
//
// For testing purposes, the function that generates the timestamp can be
// overridden. If not set, it will return time.Now().UTC().Unix().
func (s *SecureCookie) timestamp() int64 {
return s.timeFunc()
}
// encrypt encrypts a value using the given key, nonce will be generated
// and prepended to the ciphertext.
func (s *SecureCookie) encrypt(name, key, value []byte) ([]byte, error) {
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
}
nonce := GenerateRandomKey(aead.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return nil, err
}
// We create a buffer of "timestamp|ciphertext" so that we can verify
// the validity of the timestamp after decrypting, but before deserializing.
buf := new(bytes.Buffer)
buf.WriteString(strconv.FormatInt(s.timestamp(), 10) + "|")
buf.Write(value)
value = aead.Seal(nonce, nonce, buf.Bytes(), name)
return value, nil
}
// decrypt decrypts a value using the given key, nonce will be extracted from
// the ciphertext.
func (s *SecureCookie) decrypt(name, key, value []byte) ([]byte, error) {
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
}
if len(value) < aead.NonceSize() {
return nil, ErrDecryptionFailed
}
nonce, ciphertext := value[:aead.NonceSize()], value[aead.NonceSize():]
return aead.Open(nil, nonce, ciphertext, name)
}
// Encoding -------------------------------------------------------------------
// encode encodes a value using base64.
func encode(value []byte) []byte {
encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value)))
base64.URLEncoding.Encode(encoded, value)
return encoded
}
// decode decodes a cookie using base64.
func decode(value []byte) ([]byte, error) {
decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value)))
b, err := base64.URLEncoding.Decode(decoded, value)
if err != nil {
return nil, err
}
return decoded[:b], nil
}
// Helpers --------------------------------------------------------------------
// GenerateRandomKey creates a random key with the given length in bytes.
// On failure, returns nil.
//
// Note that keys created using `GenerateRandomKey()` are not automatically
// persisted. New keys will be created when the application is restarted, and
// previously issued cookies will not be able to be decoded.
//
// Callers should explicitly check for the possibility of a nil return, treat
// it as a failure of the system random number generator, and not continue.
func GenerateRandomKey(length int) []byte {
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
panic(fmt.Sprintf("securecookie: error generating random key: %v", err))
}
return b
}
// EncodeMulti encodes a cookie value using a group of codecs.
//
// The codecs are tried in order. Multiple codecs are accepted to allow
// key rotation.
//
// On error, may return a MultiError.
func EncodeMulti(name string, value any, codecs ...Codec) (string, error) {
if len(codecs) == 0 {
return "", ErrNoCodecs
}
var errors MultiError
for _, codec := range codecs {
encoded, err := codec.Encode(name, value)
if err == nil {
return encoded, nil
}
errors = append(errors, err)
}
return "", errors
}
// DecodeMulti decodes a cookie value using a group of codecs.
//
// The codecs are tried in order. Multiple codecs are accepted to allow
// key rotation.
//
// On error, may return a MultiError.
func DecodeMulti(name string, value string, dst any, codecs ...Codec) error {
if len(codecs) == 0 {
return ErrNoCodecs
}
var errors MultiError
for _, codec := range codecs {
_, err := codec.Decode(name, value, dst)
if err == nil {
return nil
}
errors = append(errors, err)
}
return errors
}
// MultiError groups multiple errors.
type MultiError []error
func (m MultiError) Error() string {
s, n := "", 0
for _, e := range m {
if e != nil {
if n == 0 {
s = e.Error()
}
n++
}
}
switch n {
case 0:
return "(0 errors)"
case 1:
return s
case 2:
return s + " (and 1 other error)"
}
return fmt.Sprintf("%s (and %d other errors)", s, n-1)
}