api_auth.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. "crypto/tls"
  9. "fmt"
  10. "net"
  11. "net/http"
  12. "slices"
  13. "strings"
  14. "time"
  15. ldap "github.com/go-ldap/ldap/v3"
  16. "github.com/syncthing/syncthing/lib/config"
  17. "github.com/syncthing/syncthing/lib/events"
  18. "github.com/syncthing/syncthing/lib/rand"
  19. )
  20. const (
  21. maxSessionLifetime = 7 * 24 * time.Hour
  22. maxActiveSessions = 25
  23. randomTokenLength = 64
  24. )
  25. func emitLoginAttempt(success bool, username, address string, evLogger events.Logger) {
  26. evLogger.Log(events.LoginAttempt, map[string]interface{}{
  27. "success": success,
  28. "username": username,
  29. "remoteAddress": address,
  30. })
  31. if !success {
  32. l.Infof("Wrong credentials supplied during API authorization from %s", address)
  33. }
  34. }
  35. func antiBruteForceSleep() {
  36. time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
  37. }
  38. func unauthorized(w http.ResponseWriter, shortID string) {
  39. w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="Authorization Required (%s)"`, shortID))
  40. http.Error(w, "Not Authorized", http.StatusUnauthorized)
  41. }
  42. func forbidden(w http.ResponseWriter) {
  43. http.Error(w, "Forbidden", http.StatusForbidden)
  44. }
  45. func isNoAuthPath(path string) bool {
  46. // Local variable instead of module var to prevent accidental mutation
  47. noAuthPaths := []string{
  48. "/",
  49. "/index.html",
  50. "/modal.html",
  51. "/rest/svc/lang", // Required to load language settings on login page
  52. }
  53. // Local variable instead of module var to prevent accidental mutation
  54. noAuthPrefixes := []string{
  55. // Static assets
  56. "/assets/",
  57. "/syncthing/",
  58. "/vendor/",
  59. "/theme-assets/", // This leaks information from config, but probably not sensitive
  60. // No-auth API endpoints
  61. "/rest/noauth",
  62. }
  63. return slices.Contains(noAuthPaths, path) ||
  64. slices.ContainsFunc(noAuthPrefixes, func(prefix string) bool {
  65. return strings.HasPrefix(path, prefix)
  66. })
  67. }
  68. type basicAuthAndSessionMiddleware struct {
  69. tokenCookieManager *tokenCookieManager
  70. guiCfg config.GUIConfiguration
  71. ldapCfg config.LDAPConfiguration
  72. next http.Handler
  73. evLogger events.Logger
  74. }
  75. func newBasicAuthAndSessionMiddleware(tokenCookieManager *tokenCookieManager, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration, next http.Handler, evLogger events.Logger) *basicAuthAndSessionMiddleware {
  76. return &basicAuthAndSessionMiddleware{
  77. tokenCookieManager: tokenCookieManager,
  78. guiCfg: guiCfg,
  79. ldapCfg: ldapCfg,
  80. next: next,
  81. evLogger: evLogger,
  82. }
  83. }
  84. func (m *basicAuthAndSessionMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  85. if hasValidAPIKeyHeader(r, m.guiCfg) {
  86. m.next.ServeHTTP(w, r)
  87. return
  88. }
  89. if m.tokenCookieManager.hasValidSession(r) {
  90. m.next.ServeHTTP(w, r)
  91. return
  92. }
  93. // Fall back to Basic auth if provided
  94. if username, ok := attemptBasicAuth(r, m.guiCfg, m.ldapCfg, m.evLogger); ok {
  95. m.tokenCookieManager.createSession(username, false, w, r)
  96. m.next.ServeHTTP(w, r)
  97. return
  98. }
  99. // Exception for static assets and REST calls that don't require authentication.
  100. if isNoAuthPath(r.URL.Path) {
  101. m.next.ServeHTTP(w, r)
  102. return
  103. }
  104. // Some browsers don't send the Authorization request header unless prompted by a 401 response.
  105. // This enables https://user:pass@localhost style URLs to keep working.
  106. if m.guiCfg.SendBasicAuthPrompt {
  107. unauthorized(w, m.tokenCookieManager.shortID)
  108. return
  109. }
  110. forbidden(w)
  111. }
  112. func (m *basicAuthAndSessionMiddleware) passwordAuthHandler(w http.ResponseWriter, r *http.Request) {
  113. var req struct {
  114. Username string
  115. Password string
  116. StayLoggedIn bool
  117. }
  118. if err := unmarshalTo(r.Body, &req); err != nil {
  119. l.Debugln("Failed to parse username and password:", err)
  120. http.Error(w, "Failed to parse username and password.", http.StatusBadRequest)
  121. return
  122. }
  123. if auth(req.Username, req.Password, m.guiCfg, m.ldapCfg) {
  124. m.tokenCookieManager.createSession(req.Username, req.StayLoggedIn, w, r)
  125. w.WriteHeader(http.StatusNoContent)
  126. return
  127. }
  128. emitLoginAttempt(false, req.Username, r.RemoteAddr, m.evLogger)
  129. antiBruteForceSleep()
  130. forbidden(w)
  131. }
  132. func attemptBasicAuth(r *http.Request, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration, evLogger events.Logger) (string, bool) {
  133. username, password, ok := r.BasicAuth()
  134. if !ok {
  135. return "", false
  136. }
  137. l.Debugln("Sessionless HTTP request with authentication; this is expensive.")
  138. if auth(username, password, guiCfg, ldapCfg) {
  139. return username, true
  140. }
  141. usernameFromIso := string(iso88591ToUTF8([]byte(username)))
  142. passwordFromIso := string(iso88591ToUTF8([]byte(password)))
  143. if auth(usernameFromIso, passwordFromIso, guiCfg, ldapCfg) {
  144. return usernameFromIso, true
  145. }
  146. emitLoginAttempt(false, username, r.RemoteAddr, evLogger)
  147. antiBruteForceSleep()
  148. return "", false
  149. }
  150. func (m *basicAuthAndSessionMiddleware) handleLogout(w http.ResponseWriter, r *http.Request) {
  151. m.tokenCookieManager.destroySession(w, r)
  152. w.WriteHeader(http.StatusNoContent)
  153. }
  154. func auth(username string, password string, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration) bool {
  155. if guiCfg.AuthMode == config.AuthModeLDAP {
  156. return authLDAP(username, password, ldapCfg)
  157. } else {
  158. return authStatic(username, password, guiCfg)
  159. }
  160. }
  161. func authStatic(username string, password string, guiCfg config.GUIConfiguration) bool {
  162. return guiCfg.CompareHashedPassword(password) == nil && username == guiCfg.User
  163. }
  164. func authLDAP(username string, password string, cfg config.LDAPConfiguration) bool {
  165. address := cfg.Address
  166. hostname, _, err := net.SplitHostPort(address)
  167. if err != nil {
  168. hostname = address
  169. }
  170. var connection *ldap.Conn
  171. if cfg.Transport == config.LDAPTransportTLS {
  172. connection, err = ldap.DialTLS("tcp", address, &tls.Config{
  173. ServerName: hostname,
  174. InsecureSkipVerify: cfg.InsecureSkipVerify,
  175. })
  176. } else {
  177. connection, err = ldap.Dial("tcp", address)
  178. }
  179. if err != nil {
  180. l.Warnln("LDAP Dial:", err)
  181. return false
  182. }
  183. if cfg.Transport == config.LDAPTransportStartTLS {
  184. err = connection.StartTLS(&tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify})
  185. if err != nil {
  186. l.Warnln("LDAP Start TLS:", err)
  187. return false
  188. }
  189. }
  190. defer connection.Close()
  191. bindDN := formatOptionalPercentS(cfg.BindDN, escapeForLDAPDN(username))
  192. err = connection.Bind(bindDN, password)
  193. if err != nil {
  194. l.Warnln("LDAP Bind:", err)
  195. return false
  196. }
  197. if cfg.SearchFilter == "" && cfg.SearchBaseDN == "" {
  198. // We're done here.
  199. return true
  200. }
  201. if cfg.SearchFilter == "" || cfg.SearchBaseDN == "" {
  202. l.Warnln("LDAP configuration: both searchFilter and searchBaseDN must be set, or neither.")
  203. return false
  204. }
  205. // If a search filter and search base is set we do an LDAP search for
  206. // the user. If this matches precisely one user then we are good to go.
  207. // The search filter uses the same %s interpolation as the bind DN.
  208. searchString := formatOptionalPercentS(cfg.SearchFilter, escapeForLDAPFilter(username))
  209. const sizeLimit = 2 // we search for up to two users -- we only want to match one, so getting any number >1 is a failure.
  210. const timeLimit = 60 // Search for up to a minute...
  211. searchReq := ldap.NewSearchRequest(cfg.SearchBaseDN, ldap.ScopeWholeSubtree, ldap.DerefFindingBaseObj, sizeLimit, timeLimit, false, searchString, nil, nil)
  212. res, err := connection.Search(searchReq)
  213. if err != nil {
  214. l.Warnln("LDAP Search:", err)
  215. return false
  216. }
  217. if len(res.Entries) != 1 {
  218. l.Infof("Wrong number of LDAP search results, %d != 1", len(res.Entries))
  219. return false
  220. }
  221. return true
  222. }
  223. // escapeForLDAPFilter escapes a value that will be used in a filter clause
  224. func escapeForLDAPFilter(value string) string {
  225. // https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx#Special_Characters
  226. // Backslash must always be first in the list so we don't double escape them.
  227. return escapeRunes(value, []rune{'\\', '*', '(', ')', 0})
  228. }
  229. // escapeForLDAPDN escapes a value that will be used in a bind DN
  230. func escapeForLDAPDN(value string) string {
  231. // https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx
  232. // Backslash must always be first in the list so we don't double escape them.
  233. return escapeRunes(value, []rune{'\\', ',', '#', '+', '<', '>', ';', '"', '=', ' ', 0})
  234. }
  235. func escapeRunes(value string, runes []rune) string {
  236. for _, e := range runes {
  237. value = strings.ReplaceAll(value, string(e), fmt.Sprintf("\\%X", e))
  238. }
  239. return value
  240. }
  241. func formatOptionalPercentS(template string, username string) string {
  242. var replacements []any
  243. nReps := strings.Count(template, "%s") - strings.Count(template, "%%s")
  244. if nReps < 0 {
  245. nReps = 0
  246. }
  247. for i := 0; i < nReps; i++ {
  248. replacements = append(replacements, username)
  249. }
  250. return fmt.Sprintf(template, replacements...)
  251. }
  252. // Convert an ISO-8859-1 encoded byte string to UTF-8. Works by the
  253. // principle that ISO-8859-1 bytes are equivalent to unicode code points,
  254. // that a rune slice is a list of code points, and that stringifying a slice
  255. // of runes generates UTF-8 in Go.
  256. func iso88591ToUTF8(s []byte) []byte {
  257. runes := make([]rune, len(s))
  258. for i := range s {
  259. runes[i] = rune(s[i])
  260. }
  261. return []byte(string(runes))
  262. }