api_auth.go 10 KB

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