简介

cookie 是用于在 Web 客户端(一般是浏览器)和服务器之间传输少量数据的一种机制。由服务器生成,发送到客户端保存,客户端后续的每次请求都会将 cookie 带上。cookie 现在已经被多多少少地滥用了。很多公司使用 cookie 来收集用户信息、投放广告等。

cookie 有两大缺点:

  • 每次请求都需要传输,故不能用来存放大量数据;
  • 安全性较低,通过浏览器工具,很容易看到由网站服务器设置的 cookie。

gorilla/securecookie提供了一种安全的 cookie,通过在服务端给 cookie 加密,让其内容不可读,也不可伪造。当然,敏感信息还是强烈建议不要放在 cookie 中。

快速使用

本文代码使用 Go Modules。

创建目录并初始化:

  1. $ mkdir -p gorilla/securecookie && cd gorilla/securecookie
  2. $ go mod init github.com/go-quiz/go-daily-lib/gorilla/securecookie

安装gorilla/securecookie库:

  1. $ go get github.com/gorilla/securecookie
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gorilla/mux"
  5. "github.com/gorilla/securecookie"
  6. "log"
  7. "net/http"
  8. )
  9. type User struct {
  10. Name string
  11. Age int
  12. }
  13. var (
  14. hashKey = securecookie.GenerateRandomKey(16)
  15. blockKey = securecookie.GenerateRandomKey(16)
  16. s = securecookie.New(hashKey, blockKey)
  17. )
  18. func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
  19. u := &User {
  20. Name: "dj",
  21. Age: 18,
  22. }
  23. if encoded, err := s.Encode("user", u); err == nil {
  24. cookie := &http.Cookie{
  25. Name: "user",
  26. Value: encoded,
  27. Path: "/",
  28. Secure: true,
  29. HttpOnly: true,
  30. }
  31. http.SetCookie(w, cookie)
  32. }
  33. fmt.Fprintln(w, "Hello World")
  34. }
  35. func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
  36. if cookie, err := r.Cookie("user"); err == nil {
  37. u := &User{}
  38. if err = s.Decode("user", cookie.Value, u); err == nil {
  39. fmt.Fprintf(w, "name:%s age:%d", u.Name, u.Age)
  40. }
  41. }
  42. }
  43. func main() {
  44. r := mux.NewRouter()
  45. r.HandleFunc("/set_cookie", SetCookieHandler)
  46. r.HandleFunc("/read_cookie", ReadCookieHandler)
  47. http.Handle("/", r)
  48. log.Fatal(http.ListenAndServe(":8080", nil))
  49. }

首先需要创建一个SecureCookie对象:

  1. var s = securecookie.New(hashKey, blockKey)

其中hashKey是必填的,它用来验证 cookie 是否是伪造的,底层使用 HMAC(Hash-based message authentication code)算法。推荐hashKey使用 32/64 字节的 Key。

blockKey是可选的,它用来加密 cookie,如不需要加密,可以传nil。如果设置了,它的长度必须与对应的加密算法的块大小(block size)一致。例如对于 AES 系列算法,AES-128/AES-192/AES-256 对应的块大小分别为 16/24/32 字节。

为了方便也可以使用GenerateRandomKey()函数生成一个安全性足够强的随机 key。每次调用该函数都会返回不同的 key。上面代码就是通过这种方式创建 key 的。

调用s.Encode("user", u)将对象u编码成字符串,内部实际上使用了标准库encoding/gob。所以gob支持的类型都可以编码。

调用s.Decode("user", cookie.Value, u)将 cookie 值解码到对应的u对象中。

运行:

  1. $ go run main.go

首先使用浏览器访问localhost:8080/set_cookie,这时可以在 Chrome 开发者工具的 Application 页签中看到 cookie 内容:

每日一库之76:gorilla-securecookie - 图1

访问localhost:8080/read_cookie,页面显示name: dj age: 18

使用 JSON

securecookie默认使用encoding/gob编码 cookie 值,我们也可以改用encoding/jsonsecurecookie将编解码器封装成一个Serializer接口:

  1. type Serializer interface {
  2. Serialize(src interface{}) ([]byte, error)
  3. Deserialize(src []byte, dst interface{}) error
  4. }

securecookie提供了GobEncoderJSONEncoder的实现:

  1. func (e GobEncoder) Serialize(src interface{}) ([]byte, error) {
  2. buf := new(bytes.Buffer)
  3. enc := gob.NewEncoder(buf)
  4. if err := enc.Encode(src); err != nil {
  5. return nil, cookieError{cause: err, typ: usageError}
  6. }
  7. return buf.Bytes(), nil
  8. }
  9. func (e GobEncoder) Deserialize(src []byte, dst interface{}) error {
  10. dec := gob.NewDecoder(bytes.NewBuffer(src))
  11. if err := dec.Decode(dst); err != nil {
  12. return cookieError{cause: err, typ: decodeError}
  13. }
  14. return nil
  15. }
  16. func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) {
  17. buf := new(bytes.Buffer)
  18. enc := json.NewEncoder(buf)
  19. if err := enc.Encode(src); err != nil {
  20. return nil, cookieError{cause: err, typ: usageError}
  21. }
  22. return buf.Bytes(), nil
  23. }
  24. func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error {
  25. dec := json.NewDecoder(bytes.NewReader(src))
  26. if err := dec.Decode(dst); err != nil {
  27. return cookieError{cause: err, typ: decodeError}
  28. }
  29. return nil
  30. }

我们可以调用securecookie.SetSerializer(JSONEncoder{})设置使用 JSON 编码:

  1. var (
  2. hashKey = securecookie.GenerateRandomKey(16)
  3. blockKey = securecookie.GenerateRandomKey(16)
  4. s = securecookie.New(hashKey, blockKey)
  5. )
  6. func init() {
  7. s.SetSerializer(securecookie.JSONEncoder{})
  8. }

自定义编解码

我们可以定义一个类型实现Serializer接口,那么该类型的对象可以用作securecookie的编解码器。我们实现一个简单的 XML 编解码器:

  1. package main
  2. type XMLEncoder struct{}
  3. func (x XMLEncoder) Serialize(src interface{}) ([]byte, error) {
  4. buf := &bytes.Buffer{}
  5. encoder := xml.NewEncoder(buf)
  6. if err := encoder.Encode(buf); err != nil {
  7. return nil, err
  8. }
  9. return buf.Bytes(), nil
  10. }
  11. func (x XMLEncoder) Deserialize(src []byte, dst interface{}) error {
  12. dec := xml.NewDecoder(bytes.NewBuffer(src))
  13. if err := dec.Decode(dst); err != nil {
  14. return err
  15. }
  16. return nil
  17. }
  18. func init() {
  19. s.SetSerializer(XMLEncoder{})
  20. }

由于securecookie.cookieError未导出,XMLEncoderGobEncoder/JSONEncoder返回的错误有些不一致,不过不影响使用。

Hash/Block 函数

securecookie默认使用sha256.New作为 Hash 函数(用于 HMAC 算法),使用aes.NewCipher作为 Block 函数(用于加解密):

  1. // securecookie.go
  2. func New(hashKey, blockKey []byte) *SecureCookie {
  3. s := &SecureCookie{
  4. hashKey: hashKey,
  5. blockKey: blockKey,
  6. // 这里设置 Hash 函数
  7. hashFunc: sha256.New,
  8. maxAge: 86400 * 30,
  9. maxLength: 4096,
  10. sz: GobEncoder{},
  11. }
  12. if hashKey == nil {
  13. s.err = errHashKeyNotSet
  14. }
  15. if blockKey != nil {
  16. // 这里设置 Block 函数
  17. s.BlockFunc(aes.NewCipher)
  18. }
  19. return s
  20. }

可以通过securecookie.HashFunc()修改 Hash 函数,传入一个func () hash.Hash类型:

  1. func (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie {
  2. s.hashFunc = f
  3. return s
  4. }

通过securecookie.BlockFunc()修改 Block 函数,传入一个f func([]byte) (cipher.Block, error)

  1. func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie {
  2. if s.blockKey == nil {
  3. s.err = errBlockKeyNotSet
  4. } else if block, err := f(s.blockKey); err == nil {
  5. s.block = block
  6. } else {
  7. s.err = cookieError{cause: err, typ: usageError}
  8. }
  9. return s
  10. }

更换这两个函数更多的是处于安全性的考虑,例如选用更安全的sha512算法:

  1. s.HashFunc(sha512.New512_256)

更换 Key

为了防止 cookie 泄露造成安全风险,有个常用的安全策略:定期更换 Key。更换 Key,让之前获得的 cookie 失效。对应securecookie库,就是更换SecureCookie对象:

  1. var (
  2. prevCookie unsafe.Pointer
  3. currentCookie unsafe.Pointer
  4. )
  5. func init() {
  6. prevCookie = unsafe.Pointer(securecookie.New(
  7. securecookie.GenerateRandomKey(64),
  8. securecookie.GenerateRandomKey(32),
  9. ))
  10. currentCookie = unsafe.Pointer(securecookie.New(
  11. securecookie.GenerateRandomKey(64),
  12. securecookie.GenerateRandomKey(32),
  13. ))
  14. }

程序启动时,我们先生成两个SecureCookie对象,然后每隔一段时间就生成一个新的对象替换旧的。

由于每个请求都是在一个独立的 goroutine 中处理的(读),更换 key 也是在一个单独的 goroutine(写)。为了并发安全,我们必须增加同步措施。但是这种情况下使用锁又太重了,毕竟这里更新的频率很低。我这里将securecookie.SecureCookie对象存储为unsafe.Pointer类型,然后就可以使用atomic原子操作来同步读取和更新了:

  1. func rotateKey() {
  2. newcookie := securecookie.New(
  3. securecookie.GenerateRandomKey(64),
  4. securecookie.GenerateRandomKey(32),
  5. )
  6. atomic.StorePointer(&prevCookie, currentCookie)
  7. atomic.StorePointer(&currentCookie, unsafe.Pointer(newcookie))
  8. }

rotateKey()需要在一个新的 goroutine 中定期调用,我们在main函数中启动这个 goroutine

  1. func main() {
  2. ctx, cancel := context.WithCancel(context.Background())
  3. defer cancel()
  4. go RotateKey(ctx)
  5. }
  6. func RotateKey(ctx context.Context) {
  7. ticker := time.NewTicker(30 * time.Second)
  8. defer ticker.Stop()
  9. for {
  10. select {
  11. case <-ctx.Done():
  12. break
  13. case <-ticker.C:
  14. }
  15. rotateKey()
  16. }
  17. }

这里为了方便测试,我设置每隔 30s 就轮换一次。同时为了防止 goroutine 泄漏,我们传入了一个可取消的Context。还需要注意time.NewTicker()创建的*time.Ticker对象不使用时需要手动调用Stop()关闭,否则会造成资源泄漏。

使用两个SecureCookie对象之后,我们编解码可以调用EncodeMulti/DecodeMulti这组方法,它们可以接受多个SecureCookie对象:

  1. func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
  2. u := &User{
  3. Name: "dj",
  4. Age: 18,
  5. }
  6. if encoded, err := securecookie.EncodeMulti(
  7. "user", u,
  8. // 看这里 🐒
  9. (*securecookie.SecureCookie)(atomic.LoadPointer(&currentCookie)),
  10. ); err == nil {
  11. cookie := &http.Cookie{
  12. Name: "user",
  13. Value: encoded,
  14. Path: "/",
  15. Secure: true,
  16. HttpOnly: true,
  17. }
  18. http.SetCookie(w, cookie)
  19. }
  20. fmt.Fprintln(w, "Hello World")
  21. }

使用unsafe.Pointer保存SecureCookie对象后,使用时需要类型转换。并且由于并发问题,需要使用atomic.LoadPointer()访问。

解码时调用DecodeMulti依次传入currentCookieprevCookie,让prevCookie不会立刻失效:

  1. func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
  2. if cookie, err := r.Cookie("user"); err == nil {
  3. u := &User{}
  4. if err = securecookie.DecodeMulti(
  5. "user", cookie.Value, u,
  6. // 看这里 🐒
  7. (*securecookie.SecureCookie)(atomic.LoadPointer(&currentCookie)),
  8. (*securecookie.SecureCookie)(atomic.LoadPointer(&prevCookie)),
  9. ); err == nil {
  10. fmt.Fprintf(w, "name:%s age:%d", u.Name, u.Age)
  11. } else {
  12. fmt.Fprintf(w, "read cookie error:%v", err)
  13. }
  14. }
  15. }

运行程序:

  1. $ go run main.go

先请求localhost:8080/set_cookie,然后请求localhost:8080/read_cookie读取 cookie。等待 1 分钟后,再次请求,发现之前的 cookie 失效了:

  1. read cookie error:securecookie: the value is not valid (and 1 other error)

总结

securecookie为 cookie 添加了一层保护罩,让 cookie 不能轻易地被读取和伪造。还是需要强调一下:

敏感数据不要放在 cookie 中!敏感数据不要放在 cookie 中!敏感数据不要放在 cookie 中!敏感数据不要放在 cookie 中!

重要的事情说 4 遍。在使用 cookie 存放数据时需要仔细权衡。

大家如果发现好玩、好用的 Go 语言库,欢迎到 Go 每日一库 GitHub 上提交 issue😄

参考

  1. gorilla/securecookie GitHub:github.com/gorilla/securecookie
  2. Go 每日一库 GitHub:https://github.com/go-quiz/go-daily-lib