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.

csrf.go 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // Copyright 2013 Martini Authors
  2. // Copyright 2014 The Macaron Authors
  3. // Copyright 2021 The Gitea Authors
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  6. // not use this file except in compliance with the License. You may obtain
  7. // 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, WITHOUT
  13. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. // License for the specific language governing permissions and limitations
  15. // under the License.
  16. // SPDX-License-Identifier: Apache-2.0
  17. // a middleware that generates and validates CSRF tokens.
  18. package context
  19. import (
  20. "encoding/base32"
  21. "fmt"
  22. "net/http"
  23. "strconv"
  24. "time"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/util"
  28. "code.gitea.io/gitea/modules/web/middleware"
  29. )
  30. // CSRFProtector represents a CSRF protector and is used to get the current token and validate the token.
  31. type CSRFProtector interface {
  32. // GetHeaderName returns HTTP header to search for token.
  33. GetHeaderName() string
  34. // GetFormName returns form value to search for token.
  35. GetFormName() string
  36. // GetToken returns the token.
  37. GetToken() string
  38. // Validate validates the token in http context.
  39. Validate(ctx *Context)
  40. // DeleteCookie deletes the cookie
  41. DeleteCookie(ctx *Context)
  42. }
  43. type csrfProtector struct {
  44. opt CsrfOptions
  45. // Token generated to pass via header, cookie, or hidden form value.
  46. Token string
  47. // This value must be unique per user.
  48. ID string
  49. }
  50. // GetHeaderName returns the name of the HTTP header for csrf token.
  51. func (c *csrfProtector) GetHeaderName() string {
  52. return c.opt.Header
  53. }
  54. // GetFormName returns the name of the form value for csrf token.
  55. func (c *csrfProtector) GetFormName() string {
  56. return c.opt.Form
  57. }
  58. // GetToken returns the current token. This is typically used
  59. // to populate a hidden form in an HTML template.
  60. func (c *csrfProtector) GetToken() string {
  61. return c.Token
  62. }
  63. // CsrfOptions maintains options to manage behavior of Generate.
  64. type CsrfOptions struct {
  65. // The global secret value used to generate Tokens.
  66. Secret string
  67. // HTTP header used to set and get token.
  68. Header string
  69. // Form value used to set and get token.
  70. Form string
  71. // Cookie value used to set and get token.
  72. Cookie string
  73. // Cookie domain.
  74. CookieDomain string
  75. // Cookie path.
  76. CookiePath string
  77. CookieHTTPOnly bool
  78. // SameSite set the cookie SameSite type
  79. SameSite http.SameSite
  80. // Key used for getting the unique ID per user.
  81. SessionKey string
  82. // oldSessionKey saves old value corresponding to SessionKey.
  83. oldSessionKey string
  84. // If true, send token via X-Csrf-Token header.
  85. SetHeader bool
  86. // If true, send token via _csrf cookie.
  87. SetCookie bool
  88. // Set the Secure flag to true on the cookie.
  89. Secure bool
  90. // Disallow Origin appear in request header.
  91. Origin bool
  92. // Cookie lifetime. Default is 0
  93. CookieLifeTime int
  94. }
  95. func prepareDefaultCsrfOptions(opt CsrfOptions) CsrfOptions {
  96. if opt.Secret == "" {
  97. randBytes, err := util.CryptoRandomBytes(8)
  98. if err != nil {
  99. // this panic can be handled by the recover() in http handlers
  100. panic(fmt.Errorf("failed to generate random bytes: %w", err))
  101. }
  102. opt.Secret = base32.StdEncoding.EncodeToString(randBytes)
  103. }
  104. if opt.Header == "" {
  105. opt.Header = "X-Csrf-Token"
  106. }
  107. if opt.Form == "" {
  108. opt.Form = "_csrf"
  109. }
  110. if opt.Cookie == "" {
  111. opt.Cookie = "_csrf"
  112. }
  113. if opt.CookiePath == "" {
  114. opt.CookiePath = "/"
  115. }
  116. if opt.SessionKey == "" {
  117. opt.SessionKey = "uid"
  118. }
  119. if opt.CookieLifeTime == 0 {
  120. opt.CookieLifeTime = int(CsrfTokenTimeout.Seconds())
  121. }
  122. opt.oldSessionKey = "_old_" + opt.SessionKey
  123. return opt
  124. }
  125. func newCsrfCookie(c *csrfProtector, value string) *http.Cookie {
  126. return &http.Cookie{
  127. Name: c.opt.Cookie,
  128. Value: value,
  129. Path: c.opt.CookiePath,
  130. Domain: c.opt.CookieDomain,
  131. MaxAge: c.opt.CookieLifeTime,
  132. Secure: c.opt.Secure,
  133. HttpOnly: c.opt.CookieHTTPOnly,
  134. SameSite: c.opt.SameSite,
  135. }
  136. }
  137. // PrepareCSRFProtector returns a CSRFProtector to be used for every request.
  138. // Additionally, depending on options set, generated tokens will be sent via Header and/or Cookie.
  139. func PrepareCSRFProtector(opt CsrfOptions, ctx *Context) CSRFProtector {
  140. opt = prepareDefaultCsrfOptions(opt)
  141. x := &csrfProtector{opt: opt}
  142. if opt.Origin && len(ctx.Req.Header.Get("Origin")) > 0 {
  143. return x
  144. }
  145. x.ID = "0"
  146. uidAny := ctx.Session.Get(opt.SessionKey)
  147. if uidAny != nil {
  148. switch uidVal := uidAny.(type) {
  149. case string:
  150. x.ID = uidVal
  151. case int64:
  152. x.ID = strconv.FormatInt(uidVal, 10)
  153. default:
  154. log.Error("invalid uid type in session: %T", uidAny)
  155. }
  156. }
  157. oldUID := ctx.Session.Get(opt.oldSessionKey)
  158. uidChanged := oldUID == nil || oldUID.(string) != x.ID
  159. cookieToken := ctx.GetSiteCookie(opt.Cookie)
  160. needsNew := true
  161. if uidChanged {
  162. _ = ctx.Session.Set(opt.oldSessionKey, x.ID)
  163. } else if cookieToken != "" {
  164. // If cookie token presents, re-use existing unexpired token, else generate a new one.
  165. if issueTime, ok := ParseCsrfToken(cookieToken); ok {
  166. dur := time.Since(issueTime) // issueTime is not a monotonic-clock, the server time may change a lot to an early time.
  167. if dur >= -CsrfTokenRegenerationInterval && dur <= CsrfTokenRegenerationInterval {
  168. x.Token = cookieToken
  169. needsNew = false
  170. }
  171. }
  172. }
  173. if needsNew {
  174. // FIXME: actionId.
  175. x.Token = GenerateCsrfToken(x.opt.Secret, x.ID, "POST", time.Now())
  176. if opt.SetCookie {
  177. cookie := newCsrfCookie(x, x.Token)
  178. ctx.Resp.Header().Add("Set-Cookie", cookie.String())
  179. }
  180. }
  181. if opt.SetHeader {
  182. ctx.Resp.Header().Add(opt.Header, x.Token)
  183. }
  184. return x
  185. }
  186. func (c *csrfProtector) validateToken(ctx *Context, token string) {
  187. if !ValidCsrfToken(token, c.opt.Secret, c.ID, "POST", time.Now()) {
  188. c.DeleteCookie(ctx)
  189. if middleware.IsAPIPath(ctx.Req) {
  190. // currently, there should be no access to the APIPath with CSRF token. because templates shouldn't use the `/api/` endpoints.
  191. http.Error(ctx.Resp, "Invalid CSRF token.", http.StatusBadRequest)
  192. } else {
  193. ctx.Flash.Error(ctx.Tr("error.invalid_csrf"))
  194. ctx.Redirect(setting.AppSubURL + "/")
  195. }
  196. }
  197. }
  198. // Validate should be used as a per route middleware. It attempts to get a token from an "X-Csrf-Token"
  199. // HTTP header and then a "_csrf" form value. If one of these is found, the token will be validated.
  200. // If this validation fails, custom Error is sent in the reply.
  201. // If neither a header nor form value is found, http.StatusBadRequest is sent.
  202. func (c *csrfProtector) Validate(ctx *Context) {
  203. if token := ctx.Req.Header.Get(c.GetHeaderName()); token != "" {
  204. c.validateToken(ctx, token)
  205. return
  206. }
  207. if token := ctx.Req.FormValue(c.GetFormName()); token != "" {
  208. c.validateToken(ctx, token)
  209. return
  210. }
  211. c.validateToken(ctx, "") // no csrf token, use an empty token to respond error
  212. }
  213. func (c *csrfProtector) DeleteCookie(ctx *Context) {
  214. if c.opt.SetCookie {
  215. cookie := newCsrfCookie(c, "")
  216. cookie.MaxAge = -1
  217. ctx.Resp.Header().Add("Set-Cookie", cookie.String())
  218. }
  219. }