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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Copyright 2012 Google Inc. All Rights Reserved.
  2. // Copyright 2014 The Macaron Authors
  3. // Copyright 2020 The Gitea Authors
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. // SPDX-License-Identifier: Apache-2.0
  17. package context
  18. import (
  19. "bytes"
  20. "crypto/hmac"
  21. "crypto/sha1"
  22. "crypto/subtle"
  23. "encoding/base64"
  24. "fmt"
  25. "strconv"
  26. "strings"
  27. "time"
  28. )
  29. // CsrfTokenTimeout represents the duration that XSRF tokens are valid.
  30. // It is exported so clients may set cookie timeouts that match generated tokens.
  31. const CsrfTokenTimeout = 24 * time.Hour
  32. // CsrfTokenRegenerationInterval is the interval between token generations, old tokens are still valid before CsrfTokenTimeout
  33. var CsrfTokenRegenerationInterval = 10 * time.Minute
  34. var csrfTokenSep = []byte(":")
  35. // GenerateCsrfToken returns a URL-safe secure XSRF token that expires in CsrfTokenTimeout hours.
  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 GenerateCsrfToken(key, userID, actionID string, now time.Time) string {
  40. nowUnixNano := now.UnixNano()
  41. nowUnixNanoStr := strconv.FormatInt(nowUnixNano, 10)
  42. h := hmac.New(sha1.New, []byte(key))
  43. h.Write([]byte(strings.ReplaceAll(userID, ":", "_")))
  44. h.Write(csrfTokenSep)
  45. h.Write([]byte(strings.ReplaceAll(actionID, ":", "_")))
  46. h.Write(csrfTokenSep)
  47. h.Write([]byte(nowUnixNanoStr))
  48. tok := fmt.Sprintf("%s:%s", h.Sum(nil), nowUnixNanoStr)
  49. return base64.RawURLEncoding.EncodeToString([]byte(tok))
  50. }
  51. func ParseCsrfToken(token string) (issueTime time.Time, ok bool) {
  52. data, err := base64.RawURLEncoding.DecodeString(token)
  53. if err != nil {
  54. return time.Time{}, false
  55. }
  56. pos := bytes.LastIndex(data, csrfTokenSep)
  57. if pos == -1 {
  58. return time.Time{}, false
  59. }
  60. nanos, err := strconv.ParseInt(string(data[pos+1:]), 10, 64)
  61. if err != nil {
  62. return time.Time{}, false
  63. }
  64. return time.Unix(0, nanos), true
  65. }
  66. // ValidCsrfToken returns true if token is a valid and unexpired token returned by Generate.
  67. func ValidCsrfToken(token, key, userID, actionID string, now time.Time) bool {
  68. issueTime, ok := ParseCsrfToken(token)
  69. if !ok {
  70. return false
  71. }
  72. // Check that the token is not expired.
  73. if now.Sub(issueTime) >= CsrfTokenTimeout {
  74. return false
  75. }
  76. // Check that the token is not from the future.
  77. // Allow 1-minute grace period in case the token is being verified on a
  78. // machine whose clock is behind the machine that issued the token.
  79. if issueTime.After(now.Add(1 * time.Minute)) {
  80. return false
  81. }
  82. expected := GenerateCsrfToken(key, userID, actionID, issueTime)
  83. // Check that the token matches the expected value.
  84. // Use constant time comparison to avoid timing attacks.
  85. return subtle.ConstantTimeCompare([]byte(token), []byte(expected)) == 1
  86. }