api_csrf.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package api
  7. import (
  8. "bufio"
  9. "fmt"
  10. "net/http"
  11. "os"
  12. "strings"
  13. "github.com/syncthing/syncthing/lib/osutil"
  14. "github.com/syncthing/syncthing/lib/rand"
  15. "github.com/syncthing/syncthing/lib/sync"
  16. )
  17. const maxCsrfTokens = 25
  18. type csrfManager struct {
  19. // tokens is a list of valid tokens. It is sorted so that the most
  20. // recently used token is first in the list. New tokens are added to the front
  21. // of the list (as it is the most recently used at that time). The list is
  22. // pruned to a maximum of maxCsrfTokens, throwing away the least recently used
  23. // tokens.
  24. tokens []string
  25. tokensMut sync.Mutex
  26. unique string
  27. prefix string
  28. apiKeyValidator apiKeyValidator
  29. next http.Handler
  30. saveLocation string
  31. }
  32. type apiKeyValidator interface {
  33. IsValidAPIKey(key string) bool
  34. }
  35. // Check for CSRF token on /rest/ URLs. If a correct one is not given, reject
  36. // the request with 403. For / and /index.html, set a new CSRF cookie if none
  37. // is currently set.
  38. func newCsrfManager(unique string, prefix string, apiKeyValidator apiKeyValidator, next http.Handler, saveLocation string) *csrfManager {
  39. m := &csrfManager{
  40. tokensMut: sync.NewMutex(),
  41. tokens: make([]string, 0, maxCsrfTokens),
  42. unique: unique,
  43. prefix: prefix,
  44. apiKeyValidator: apiKeyValidator,
  45. next: next,
  46. saveLocation: saveLocation,
  47. }
  48. m.load()
  49. return m
  50. }
  51. func (m *csrfManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  52. // Allow requests carrying a valid API key
  53. if hasValidAPIKeyHeader(r, m.apiKeyValidator) {
  54. // Set the access-control-allow-origin header for CORS requests
  55. // since a valid API key has been provided
  56. w.Header().Add("Access-Control-Allow-Origin", "*")
  57. m.next.ServeHTTP(w, r)
  58. return
  59. }
  60. if strings.HasPrefix(r.URL.Path, "/rest/debug") {
  61. // Debugging functions are only available when explicitly
  62. // enabled, and can be accessed without a CSRF token
  63. m.next.ServeHTTP(w, r)
  64. return
  65. }
  66. if strings.HasPrefix(r.URL.Path, "/rest/noauth") {
  67. // REST calls that don't require authentication also do not
  68. // need a CSRF token.
  69. m.next.ServeHTTP(w, r)
  70. return
  71. }
  72. // Allow requests for anything not under the protected path prefix,
  73. // and set a CSRF cookie if there isn't already a valid one.
  74. if !strings.HasPrefix(r.URL.Path, m.prefix) {
  75. cookie, err := r.Cookie("CSRF-Token-" + m.unique)
  76. if err != nil || !m.validToken(cookie.Value) {
  77. l.Debugln("new CSRF cookie in response to request for", r.URL)
  78. cookie = &http.Cookie{
  79. Name: "CSRF-Token-" + m.unique,
  80. Value: m.newToken(),
  81. }
  82. http.SetCookie(w, cookie)
  83. }
  84. m.next.ServeHTTP(w, r)
  85. return
  86. }
  87. // Verify the CSRF token
  88. token := r.Header.Get("X-CSRF-Token-" + m.unique)
  89. if !m.validToken(token) {
  90. http.Error(w, "CSRF Error", http.StatusForbidden)
  91. return
  92. }
  93. m.next.ServeHTTP(w, r)
  94. }
  95. func (m *csrfManager) validToken(token string) bool {
  96. m.tokensMut.Lock()
  97. defer m.tokensMut.Unlock()
  98. for i, t := range m.tokens {
  99. if t == token {
  100. if i > 0 {
  101. // Move this token to the head of the list. Copy the tokens at
  102. // the front one step to the right and then replace the token
  103. // at the head.
  104. copy(m.tokens[1:], m.tokens[:i])
  105. m.tokens[0] = token
  106. }
  107. return true
  108. }
  109. }
  110. return false
  111. }
  112. func (m *csrfManager) newToken() string {
  113. token := rand.String(32)
  114. m.tokensMut.Lock()
  115. defer m.tokensMut.Unlock()
  116. if len(m.tokens) < maxCsrfTokens {
  117. m.tokens = append(m.tokens, "")
  118. }
  119. copy(m.tokens[1:], m.tokens)
  120. m.tokens[0] = token
  121. m.save()
  122. return token
  123. }
  124. func (m *csrfManager) save() {
  125. // We're ignoring errors in here. It's not super critical and there's
  126. // nothing relevant we can do about them anyway...
  127. if m.saveLocation == "" {
  128. return
  129. }
  130. f, err := osutil.CreateAtomic(m.saveLocation)
  131. if err != nil {
  132. return
  133. }
  134. for _, t := range m.tokens {
  135. fmt.Fprintln(f, t)
  136. }
  137. f.Close()
  138. }
  139. func (m *csrfManager) load() {
  140. if m.saveLocation == "" {
  141. return
  142. }
  143. f, err := os.Open(m.saveLocation)
  144. if err != nil {
  145. return
  146. }
  147. defer f.Close()
  148. s := bufio.NewScanner(f)
  149. for s.Scan() {
  150. m.tokens = append(m.tokens, s.Text())
  151. }
  152. }
  153. func hasValidAPIKeyHeader(r *http.Request, validator apiKeyValidator) bool {
  154. if key := r.Header.Get("X-API-Key"); validator.IsValidAPIKey(key) {
  155. return true
  156. }
  157. if auth := r.Header.Get("Authorization"); strings.HasPrefix(strings.ToLower(auth), "bearer ") {
  158. bearerToken := auth[len("bearer "):]
  159. return validator.IsValidAPIKey(bearerToken)
  160. }
  161. return false
  162. }