xsrf.go 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package xsrftoken provides methods for generating and validating secure XSRF tokens.
  5. package xsrftoken // import "golang.org/x/net/xsrftoken"
  6. import (
  7. "crypto/hmac"
  8. "crypto/sha1"
  9. "crypto/subtle"
  10. "encoding/base64"
  11. "fmt"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. // Timeout is the duration for which XSRF tokens are valid.
  17. // It is exported so clients may set cookie timeouts that match generated tokens.
  18. const Timeout = 24 * time.Hour
  19. // clean sanitizes a string for inclusion in a token by replacing all ":"s.
  20. func clean(s string) string {
  21. return strings.Replace(s, ":", "_", -1)
  22. }
  23. // Generate returns a URL-safe secure XSRF token that expires in 24 hours.
  24. //
  25. // key is a secret key for your application.
  26. // userID is a unique identifier for the user.
  27. // actionID is the action the user is taking (e.g. POSTing to a particular path).
  28. func Generate(key, userID, actionID string) string {
  29. return generateTokenAtTime(key, userID, actionID, time.Now())
  30. }
  31. // generateTokenAtTime is like Generate, but returns a token that expires 24 hours from now.
  32. func generateTokenAtTime(key, userID, actionID string, now time.Time) string {
  33. // Round time up and convert to milliseconds.
  34. milliTime := (now.UnixNano() + 1e6 - 1) / 1e6
  35. h := hmac.New(sha1.New, []byte(key))
  36. fmt.Fprintf(h, "%s:%s:%d", clean(userID), clean(actionID), milliTime)
  37. // Get the padded base64 string then removing the padding.
  38. tok := string(h.Sum(nil))
  39. tok = base64.URLEncoding.EncodeToString([]byte(tok))
  40. tok = strings.TrimRight(tok, "=")
  41. return fmt.Sprintf("%s:%d", tok, milliTime)
  42. }
  43. // Valid reports whether a token is a valid, unexpired token returned by Generate.
  44. func Valid(token, key, userID, actionID string) bool {
  45. return validTokenAtTime(token, key, userID, actionID, time.Now())
  46. }
  47. // validTokenAtTime reports whether a token is valid at the given time.
  48. func validTokenAtTime(token, key, userID, actionID string, now time.Time) bool {
  49. // Extract the issue time of the token.
  50. sep := strings.LastIndex(token, ":")
  51. if sep < 0 {
  52. return false
  53. }
  54. millis, err := strconv.ParseInt(token[sep+1:], 10, 64)
  55. if err != nil {
  56. return false
  57. }
  58. issueTime := time.Unix(0, millis*1e6)
  59. // Check that the token is not expired.
  60. if now.Sub(issueTime) >= Timeout {
  61. return false
  62. }
  63. // Check that the token is not from the future.
  64. // Allow 1 minute grace period in case the token is being verified on a
  65. // machine whose clock is behind the machine that issued the token.
  66. if issueTime.After(now.Add(1 * time.Minute)) {
  67. return false
  68. }
  69. expected := generateTokenAtTime(key, userID, actionID, issueTime)
  70. // Check that the token matches the expected value.
  71. // Use constant time comparison to avoid timing attacks.
  72. return subtle.ConstantTimeCompare([]byte(token), []byte(expected)) == 1
  73. }