关于golang:Go-每日一库之-gorillasecurecookie

简介

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

cookie 有两大毛病:

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

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

疾速应用

本文代码应用 Go Modules。

创立目录并初始化:

$ mkdir gorilla/securecookie && cd gorilla/securecookie
$ go mod init github.com/darjun/go-daily-lib/gorilla/securecookie

装置gorilla/securecookie库:

$ go get github.com/gorilla/securecookie
package main

import (
  "fmt"
  "github.com/gorilla/mux"
  "github.com/gorilla/securecookie"
  "log"
  "net/http"
)

type User struct {
  Name string
  Age int
}

var (
  hashKey = securecookie.GenerateRandomKey(16)
  blockKey = securecookie.GenerateRandomKey(16)
  s = securecookie.New(hashKey, blockKey)
)

func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
  u := &User {
    Name: "dj",
    Age: 18,
  }
  if encoded, err := s.Encode("user", u); err == nil {
    cookie := &http.Cookie{
      Name: "user",
      Value: encoded,
      Path: "/",
      Secure: true,
      HttpOnly: true,
    }
    http.SetCookie(w, cookie)
  }
  fmt.Fprintln(w, "Hello World")
}

func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
  if cookie, err := r.Cookie("user"); err == nil {
    u := &User{}
    if err = s.Decode("user", cookie.Value, u); err == nil {
      fmt.Fprintf(w, "name:%s age:%d", u.Name, u.Age)
    }
  }
}

func main() {
  r := mux.NewRouter()
  r.HandleFunc("/set_cookie", SetCookieHandler)
  r.HandleFunc("/read_cookie", ReadCookieHandler)
  http.Handle("/", r)
  log.Fatal(http.ListenAndServe(":8080", nil))
}

首先须要创立一个SecureCookie对象:

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对象中。

运行:

$ go run main.go

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

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

应用 JSON

securecookie默认应用encoding/gob编码 cookie 值,咱们也能够改用encoding/jsonsecurecookie将编解码器封装成一个Serializer接口:

type Serializer interface {
  Serialize(src interface{}) ([]byte, error)
  Deserialize(src []byte, dst interface{}) error
}

securecookie提供了GobEncoderJSONEncoder的实现:

func (e GobEncoder) Serialize(src interface{}) ([]byte, error) {
  buf := new(bytes.Buffer)
  enc := gob.NewEncoder(buf)
  if err := enc.Encode(src); err != nil {
    return nil, cookieError{cause: err, typ: usageError}
  }
  return buf.Bytes(), nil
}

func (e GobEncoder) Deserialize(src []byte, dst interface{}) error {
  dec := gob.NewDecoder(bytes.NewBuffer(src))
  if err := dec.Decode(dst); err != nil {
    return cookieError{cause: err, typ: decodeError}
  }
  return nil
}

func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) {
  buf := new(bytes.Buffer)
  enc := json.NewEncoder(buf)
  if err := enc.Encode(src); err != nil {
    return nil, cookieError{cause: err, typ: usageError}
  }
  return buf.Bytes(), nil
}

func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error {
  dec := json.NewDecoder(bytes.NewReader(src))
  if err := dec.Decode(dst); err != nil {
    return cookieError{cause: err, typ: decodeError}
  }
  return nil
}

咱们能够调用securecookie.SetSerializer(JSONEncoder{})设置应用 JSON 编码:

var (
  hashKey = securecookie.GenerateRandomKey(16)
  blockKey = securecookie.GenerateRandomKey(16)
  s = securecookie.New(hashKey, blockKey)
)

func init() {
  s.SetSerializer(securecookie.JSONEncoder{})
}

自定义编解码

咱们能够定义一个类型实现Serializer接口,那么该类型的对象能够用作securecookie的编解码器。咱们实现一个简略的 XML 编解码器:

package main

type XMLEncoder struct{}

func (x XMLEncoder) Serialize(src interface{}) ([]byte, error) {
  buf := &bytes.Buffer{}
  encoder := xml.NewEncoder(buf)
  if err := encoder.Encode(buf); err != nil {
    return nil, err
  }
  return buf.Bytes(), nil
}

func (x XMLEncoder) Deserialize(src []byte, dst interface{}) error {
  dec := xml.NewDecoder(bytes.NewBuffer(src))
  if err := dec.Decode(dst); err != nil {
    return err
  }
  return nil
}

func init() {
  s.SetSerializer(XMLEncoder{})
}

因为securecookie.cookieError未导出,XMLEncoderGobEncoder/JSONEncoder返回的谬误有些不统一,不过不影响应用。

Hash/Block 函数

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

// securecookie.go
func New(hashKey, blockKey []byte) *SecureCookie {
  s := &SecureCookie{
    hashKey:   hashKey,
    blockKey:  blockKey,
    // 这里设置 Hash 函数
    hashFunc:  sha256.New,
    maxAge:    86400 * 30,
    maxLength: 4096,
    sz:        GobEncoder{},
  }
  if hashKey == nil {
    s.err = errHashKeyNotSet
  }
  if blockKey != nil {
    // 这里设置 Block 函数
    s.BlockFunc(aes.NewCipher)
  }
  return s
}

能够通过securecookie.HashFunc()批改 Hash 函数,传入一个func () hash.Hash类型:

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

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

func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie {
  if s.blockKey == nil {
    s.err = errBlockKeyNotSet
  } else if block, err := f(s.blockKey); err == nil {
    s.block = block
  } else {
    s.err = cookieError{cause: err, typ: usageError}
  }
  return s
}

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

s.HashFunc(sha512.New512_256)

更换 Key

为了避免 cookie 泄露造成平安危险,有个罕用的安全策略:定期更换 Key。更换 Key,让之前取得的 cookie 生效。对应securecookie库,就是更换SecureCookie对象:

var (
  prevCookie    unsafe.Pointer
  currentCookie unsafe.Pointer
)

func init() {
  prevCookie = unsafe.Pointer(securecookie.New(
    securecookie.GenerateRandomKey(64),
    securecookie.GenerateRandomKey(32),
  ))
  currentCookie = unsafe.Pointer(securecookie.New(
    securecookie.GenerateRandomKey(64),
    securecookie.GenerateRandomKey(32),
  ))
}

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

因为每个申请都是在一个独立的 goroutine 中解决的(读),更换 key 也是在一个独自的 goroutine(写)。为了并发平安,咱们必须减少同步措施。然而这种状况下应用锁又太重了,毕竟这里更新的频率很低。我这里将securecookie.SecureCookie对象存储为unsafe.Pointer类型,而后就能够应用atomic原子操作来同步读取和更新了:

func rotateKey() {
  newcookie := securecookie.New(
    securecookie.GenerateRandomKey(64),
    securecookie.GenerateRandomKey(32),
  )

  atomic.StorePointer(&prevCookie, currentCookie)
  atomic.StorePointer(&currentCookie, unsafe.Pointer(newcookie))
}

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

func main() {
  ctx, cancel := context.WithCancel(context.Background())
  defer cancel()
  go RotateKey(ctx)
}

func RotateKey(ctx context.Context) {
  ticker := time.NewTicker(30 * time.Second)
  defer ticker.Stop()

  for {
    select {
    case <-ctx.Done():
      break
    case <-ticker.C:
    }

    rotateKey()
  }
}

这里为了不便测试,我设置每隔 30s 就轮换一次。同时为了避免 goroutine 透露,咱们传入了一个可勾销的Context。还须要留神time.NewTicker()创立的*time.Ticker对象不应用时须要手动调用Stop()敞开,否则会造成资源透露。

应用两个SecureCookie对象之后,咱们编解码能够调用EncodeMulti/DecodeMulti这组办法,它们能够承受多个SecureCookie对象:

func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
  u := &User{
    Name: "dj",
    Age:  18,
  }

  if encoded, err := securecookie.EncodeMulti(
    "user", u,
    // 看这里 🐒
    (*securecookie.SecureCookie)(atomic.LoadPointer(&currentCookie)),
  ); err == nil {
    cookie := &http.Cookie{
      Name:     "user",
      Value:    encoded,
      Path:     "/",
      Secure:   true,
      HttpOnly: true,
    }
    http.SetCookie(w, cookie)
  }
  fmt.Fprintln(w, "Hello World")
}

应用unsafe.Pointer保留SecureCookie对象后,应用时须要类型转换。并且因为并发问题,须要应用atomic.LoadPointer()拜访。

解码时调用DecodeMulti顺次传入currentCookieprevCookie,让prevCookie不会立即生效:

func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
  if cookie, err := r.Cookie("user"); err == nil {
    u := &User{}
    if err = securecookie.DecodeMulti(
      "user", cookie.Value, u,
      // 看这里 🐒
      (*securecookie.SecureCookie)(atomic.LoadPointer(&currentCookie)),
      (*securecookie.SecureCookie)(atomic.LoadPointer(&prevCookie)),
    ); err == nil {
      fmt.Fprintf(w, "name:%s age:%d", u.Name, u.Age)
    } else {
      fmt.Fprintf(w, "read cookie error:%v", err)
    }
  }
}

运行程序:

$ go run main.go

先申请localhost:8080/set_cookie,而后申请localhost:8080/read_cookie读取 cookie。期待 1 分钟后,再次申请,发现之前的 cookie 生效了:

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/darjun/go-daily-lib

我的博客:https://darjun.github.io

欢送关注我的微信公众号【GoUpUp】,独特学习,一起提高~

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理