api_csrf.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. unique: unique,
  42. prefix: prefix,
  43. apiKeyValidator: apiKeyValidator,
  44. next: next,
  45. saveLocation: saveLocation,
  46. }
  47. m.load()
  48. return m
  49. }
  50. func (m *csrfManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  51. // Allow requests carrying a valid API key
  52. if m.apiKeyValidator.IsValidAPIKey(r.Header.Get("X-API-Key")) {
  53. // Set the access-control-allow-origin header for CORS requests
  54. // since a valid API key has been provided
  55. w.Header().Add("Access-Control-Allow-Origin", "*")
  56. m.next.ServeHTTP(w, r)
  57. return
  58. }
  59. if strings.HasPrefix(r.URL.Path, "/rest/debug") {
  60. // Debugging functions are only available when explicitly
  61. // enabled, and can be accessed without a CSRF token
  62. m.next.ServeHTTP(w, r)
  63. return
  64. }
  65. // Allow requests for anything not under the protected path prefix,
  66. // and set a CSRF cookie if there isn't already a valid one.
  67. if !strings.HasPrefix(r.URL.Path, m.prefix) {
  68. cookie, err := r.Cookie("CSRF-Token-" + m.unique)
  69. if err != nil || !m.validToken(cookie.Value) {
  70. l.Debugln("new CSRF cookie in response to request for", r.URL)
  71. cookie = &http.Cookie{
  72. Name: "CSRF-Token-" + m.unique,
  73. Value: m.newToken(),
  74. }
  75. http.SetCookie(w, cookie)
  76. }
  77. m.next.ServeHTTP(w, r)
  78. return
  79. }
  80. // Verify the CSRF token
  81. token := r.Header.Get("X-CSRF-Token-" + m.unique)
  82. if !m.validToken(token) {
  83. http.Error(w, "CSRF Error", http.StatusForbidden)
  84. return
  85. }
  86. m.next.ServeHTTP(w, r)
  87. }
  88. func (m *csrfManager) validToken(token string) bool {
  89. m.tokensMut.Lock()
  90. defer m.tokensMut.Unlock()
  91. for i, t := range m.tokens {
  92. if t == token {
  93. if i > 0 {
  94. // Move this token to the head of the list. Copy the tokens at
  95. // the front one step to the right and then replace the token
  96. // at the head.
  97. copy(m.tokens[1:], m.tokens[:i+1])
  98. m.tokens[0] = token
  99. }
  100. return true
  101. }
  102. }
  103. return false
  104. }
  105. func (m *csrfManager) newToken() string {
  106. token := rand.String(32)
  107. m.tokensMut.Lock()
  108. m.tokens = append([]string{token}, m.tokens...)
  109. if len(m.tokens) > maxCsrfTokens {
  110. m.tokens = m.tokens[:maxCsrfTokens]
  111. }
  112. defer m.tokensMut.Unlock()
  113. m.save()
  114. return token
  115. }
  116. func (m *csrfManager) save() {
  117. // We're ignoring errors in here. It's not super critical and there's
  118. // nothing relevant we can do about them anyway...
  119. if m.saveLocation == "" {
  120. return
  121. }
  122. f, err := osutil.CreateAtomic(m.saveLocation)
  123. if err != nil {
  124. return
  125. }
  126. for _, t := range m.tokens {
  127. fmt.Fprintln(f, t)
  128. }
  129. f.Close()
  130. }
  131. func (m *csrfManager) load() {
  132. if m.saveLocation == "" {
  133. return
  134. }
  135. f, err := os.Open(m.saveLocation)
  136. if err != nil {
  137. return
  138. }
  139. defer f.Close()
  140. s := bufio.NewScanner(f)
  141. for s.Scan() {
  142. m.tokens = append(m.tokens, s.Text())
  143. }
  144. }