sess_utils.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package session
  15. import (
  16. "bytes"
  17. "crypto/cipher"
  18. "crypto/hmac"
  19. "crypto/rand"
  20. "crypto/sha1"
  21. "crypto/subtle"
  22. "encoding/base64"
  23. "encoding/gob"
  24. "errors"
  25. "fmt"
  26. "io"
  27. "strconv"
  28. "time"
  29. "github.com/astaxie/beego/utils"
  30. )
  31. func init() {
  32. gob.Register([]interface{}{})
  33. gob.Register(map[int]interface{}{})
  34. gob.Register(map[string]interface{}{})
  35. gob.Register(map[interface{}]interface{}{})
  36. gob.Register(map[string]string{})
  37. gob.Register(map[int]string{})
  38. gob.Register(map[int]int{})
  39. gob.Register(map[int]int64{})
  40. }
  41. // EncodeGob encode the obj to gob
  42. func EncodeGob(obj map[interface{}]interface{}) ([]byte, error) {
  43. for _, v := range obj {
  44. gob.Register(v)
  45. }
  46. buf := bytes.NewBuffer(nil)
  47. enc := gob.NewEncoder(buf)
  48. err := enc.Encode(obj)
  49. if err != nil {
  50. return []byte(""), err
  51. }
  52. return buf.Bytes(), nil
  53. }
  54. // DecodeGob decode data to map
  55. func DecodeGob(encoded []byte) (map[interface{}]interface{}, error) {
  56. buf := bytes.NewBuffer(encoded)
  57. dec := gob.NewDecoder(buf)
  58. var out map[interface{}]interface{}
  59. err := dec.Decode(&out)
  60. if err != nil {
  61. return nil, err
  62. }
  63. return out, nil
  64. }
  65. // generateRandomKey creates a random key with the given strength.
  66. func generateRandomKey(strength int) []byte {
  67. k := make([]byte, strength)
  68. if n, err := io.ReadFull(rand.Reader, k); n != strength || err != nil {
  69. return utils.RandomCreateBytes(strength)
  70. }
  71. return k
  72. }
  73. // Encryption -----------------------------------------------------------------
  74. // encrypt encrypts a value using the given block in counter mode.
  75. //
  76. // A random initialization vector (http://goo.gl/zF67k) with the length of the
  77. // block size is prepended to the resulting ciphertext.
  78. func encrypt(block cipher.Block, value []byte) ([]byte, error) {
  79. iv := generateRandomKey(block.BlockSize())
  80. if iv == nil {
  81. return nil, errors.New("encrypt: failed to generate random iv")
  82. }
  83. // Encrypt it.
  84. stream := cipher.NewCTR(block, iv)
  85. stream.XORKeyStream(value, value)
  86. // Return iv + ciphertext.
  87. return append(iv, value...), nil
  88. }
  89. // decrypt decrypts a value using the given block in counter mode.
  90. //
  91. // The value to be decrypted must be prepended by a initialization vector
  92. // (http://goo.gl/zF67k) with the length of the block size.
  93. func decrypt(block cipher.Block, value []byte) ([]byte, error) {
  94. size := block.BlockSize()
  95. if len(value) > size {
  96. // Extract iv.
  97. iv := value[:size]
  98. // Extract ciphertext.
  99. value = value[size:]
  100. // Decrypt it.
  101. stream := cipher.NewCTR(block, iv)
  102. stream.XORKeyStream(value, value)
  103. return value, nil
  104. }
  105. return nil, errors.New("decrypt: the value could not be decrypted")
  106. }
  107. func encodeCookie(block cipher.Block, hashKey, name string, value map[interface{}]interface{}) (string, error) {
  108. var err error
  109. var b []byte
  110. // 1. EncodeGob.
  111. if b, err = EncodeGob(value); err != nil {
  112. return "", err
  113. }
  114. // 2. Encrypt (optional).
  115. if b, err = encrypt(block, b); err != nil {
  116. return "", err
  117. }
  118. b = encode(b)
  119. // 3. Create MAC for "name|date|value". Extra pipe to be used later.
  120. b = []byte(fmt.Sprintf("%s|%d|%s|", name, time.Now().UTC().Unix(), b))
  121. h := hmac.New(sha1.New, []byte(hashKey))
  122. h.Write(b)
  123. sig := h.Sum(nil)
  124. // Append mac, remove name.
  125. b = append(b, sig...)[len(name)+1:]
  126. // 4. Encode to base64.
  127. b = encode(b)
  128. // Done.
  129. return string(b), nil
  130. }
  131. func decodeCookie(block cipher.Block, hashKey, name, value string, gcmaxlifetime int64) (map[interface{}]interface{}, error) {
  132. // 1. Decode from base64.
  133. b, err := decode([]byte(value))
  134. if err != nil {
  135. return nil, err
  136. }
  137. // 2. Verify MAC. Value is "date|value|mac".
  138. parts := bytes.SplitN(b, []byte("|"), 3)
  139. if len(parts) != 3 {
  140. return nil, errors.New("Decode: invalid value %v")
  141. }
  142. b = append([]byte(name+"|"), b[:len(b)-len(parts[2])]...)
  143. h := hmac.New(sha1.New, []byte(hashKey))
  144. h.Write(b)
  145. sig := h.Sum(nil)
  146. if len(sig) != len(parts[2]) || subtle.ConstantTimeCompare(sig, parts[2]) != 1 {
  147. return nil, errors.New("Decode: the value is not valid")
  148. }
  149. // 3. Verify date ranges.
  150. var t1 int64
  151. if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil {
  152. return nil, errors.New("Decode: invalid timestamp")
  153. }
  154. t2 := time.Now().UTC().Unix()
  155. if t1 > t2 {
  156. return nil, errors.New("Decode: timestamp is too new")
  157. }
  158. if t1 < t2-gcmaxlifetime {
  159. return nil, errors.New("Decode: expired timestamp")
  160. }
  161. // 4. Decrypt (optional).
  162. b, err = decode(parts[1])
  163. if err != nil {
  164. return nil, err
  165. }
  166. if b, err = decrypt(block, b); err != nil {
  167. return nil, err
  168. }
  169. // 5. DecodeGob.
  170. dst, err := DecodeGob(b)
  171. if err != nil {
  172. return nil, err
  173. }
  174. return dst, nil
  175. }
  176. // Encoding -------------------------------------------------------------------
  177. // encode encodes a value using base64.
  178. func encode(value []byte) []byte {
  179. encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value)))
  180. base64.URLEncoding.Encode(encoded, value)
  181. return encoded
  182. }
  183. // decode decodes a cookie using base64.
  184. func decode(value []byte) ([]byte, error) {
  185. decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value)))
  186. b, err := base64.URLEncoding.Decode(decoded, value)
  187. if err != nil {
  188. return nil, err
  189. }
  190. return decoded[:b], nil
  191. }