You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xsrf.go 3.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2012 Google Inc. All Rights Reserved.
  2. // Copyright 2014 The Macaron Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package csrf
  16. import (
  17. "bytes"
  18. "crypto/hmac"
  19. "crypto/sha1"
  20. "crypto/subtle"
  21. "encoding/base64"
  22. "fmt"
  23. "strconv"
  24. "strings"
  25. "time"
  26. )
  27. // The duration that XSRF tokens are valid.
  28. // It is exported so clients may set cookie timeouts that match generated tokens.
  29. const TIMEOUT = 24 * time.Hour
  30. // clean sanitizes a string for inclusion in a token by replacing all ":"s.
  31. func clean(s string) string {
  32. return strings.Replace(s, ":", "_", -1)
  33. }
  34. // GenerateToken returns a URL-safe secure XSRF token that expires in 24 hours.
  35. //
  36. // key is a secret key for your application.
  37. // userID is a unique identifier for the user.
  38. // actionID is the action the user is taking (e.g. POSTing to a particular path).
  39. func GenerateToken(key, userID, actionID string) string {
  40. return generateTokenAtTime(key, userID, actionID, time.Now())
  41. }
  42. // generateTokenAtTime is like Generate, but returns a token that expires 24 hours from now.
  43. func generateTokenAtTime(key, userID, actionID string, now time.Time) string {
  44. h := hmac.New(sha1.New, []byte(key))
  45. fmt.Fprintf(h, "%s:%s:%d", clean(userID), clean(actionID), now.UnixNano())
  46. tok := fmt.Sprintf("%s:%d", h.Sum(nil), now.UnixNano())
  47. return base64.RawURLEncoding.EncodeToString([]byte(tok))
  48. }
  49. // Valid returns true if token is a valid, unexpired token returned by Generate.
  50. func ValidToken(token, key, userID, actionID string) bool {
  51. return validTokenAtTime(token, key, userID, actionID, time.Now())
  52. }
  53. // validTokenAtTime is like Valid, but it uses now to check if the token is expired.
  54. func validTokenAtTime(token, key, userID, actionID string, now time.Time) bool {
  55. // Decode the token.
  56. data, err := base64.RawURLEncoding.DecodeString(token)
  57. if err != nil {
  58. return false
  59. }
  60. // Extract the issue time of the token.
  61. sep := bytes.LastIndex(data, []byte{':'})
  62. if sep < 0 {
  63. return false
  64. }
  65. nanos, err := strconv.ParseInt(string(data[sep+1:]), 10, 64)
  66. if err != nil {
  67. return false
  68. }
  69. issueTime := time.Unix(0, nanos)
  70. // Check that the token is not expired.
  71. if now.Sub(issueTime) >= TIMEOUT {
  72. return false
  73. }
  74. // Check that the token is not from the future.
  75. // Allow 1 minute grace period in case the token is being verified on a
  76. // machine whose clock is behind the machine that issued the token.
  77. if issueTime.After(now.Add(1 * time.Minute)) {
  78. return false
  79. }
  80. expected := generateTokenAtTime(key, userID, actionID, issueTime)
  81. // Check that the token matches the expected value.
  82. // Use constant time comparison to avoid timing attacks.
  83. return subtle.ConstantTimeCompare([]byte(token), []byte(expected)) == 1
  84. }