api_auth.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. "strings"
  13. "time"
  14. ldap "github.com/go-ldap/ldap/v3"
  15. "github.com/syncthing/syncthing/lib/config"
  16. "github.com/syncthing/syncthing/lib/events"
  17. "github.com/syncthing/syncthing/lib/rand"
  18. "github.com/syncthing/syncthing/lib/sync"
  19. "golang.org/x/exp/slices"
  20. )
  21. var (
  22. sessions = make(map[string]bool)
  23. sessionsMut = sync.NewMutex()
  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) {
  39. w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
  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. func basicAuthAndSessionMiddleware(cookieName string, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration, next http.Handler, evLogger events.Logger) http.Handler {
  69. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  70. if hasValidAPIKeyHeader(r, guiCfg) {
  71. next.ServeHTTP(w, r)
  72. return
  73. }
  74. cookie, err := r.Cookie(cookieName)
  75. if err == nil && cookie != nil {
  76. sessionsMut.Lock()
  77. _, ok := sessions[cookie.Value]
  78. sessionsMut.Unlock()
  79. if ok {
  80. next.ServeHTTP(w, r)
  81. return
  82. }
  83. }
  84. // Fall back to Basic auth if provided
  85. if username, ok := attemptBasicAuth(r, guiCfg, ldapCfg, evLogger); ok {
  86. createSession(cookieName, username, guiCfg, evLogger, w, r)
  87. next.ServeHTTP(w, r)
  88. return
  89. }
  90. // Exception for static assets and REST calls that don't require authentication.
  91. if isNoAuthPath(r.URL.Path) {
  92. next.ServeHTTP(w, r)
  93. return
  94. }
  95. // Some browsers don't send the Authorization request header unless prompted by a 401 response.
  96. // This enables https://user:pass@localhost style URLs to keep working.
  97. if guiCfg.SendBasicAuthPrompt {
  98. unauthorized(w)
  99. return
  100. }
  101. forbidden(w)
  102. })
  103. }
  104. func passwordAuthHandler(cookieName string, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration, evLogger events.Logger) http.Handler {
  105. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  106. var req struct {
  107. Username string
  108. Password string
  109. }
  110. if err := unmarshalTo(r.Body, &req); err != nil {
  111. l.Debugln("Failed to parse username and password:", err)
  112. http.Error(w, "Failed to parse username and password.", http.StatusBadRequest)
  113. return
  114. }
  115. if auth(req.Username, req.Password, guiCfg, ldapCfg) {
  116. createSession(cookieName, req.Username, guiCfg, evLogger, w, r)
  117. w.WriteHeader(http.StatusNoContent)
  118. return
  119. }
  120. emitLoginAttempt(false, req.Username, r.RemoteAddr, evLogger)
  121. antiBruteForceSleep()
  122. forbidden(w)
  123. })
  124. }
  125. func attemptBasicAuth(r *http.Request, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration, evLogger events.Logger) (string, bool) {
  126. username, password, ok := r.BasicAuth()
  127. if !ok {
  128. return "", false
  129. }
  130. l.Debugln("Sessionless HTTP request with authentication; this is expensive.")
  131. if auth(username, password, guiCfg, ldapCfg) {
  132. return username, true
  133. }
  134. usernameFromIso := string(iso88591ToUTF8([]byte(username)))
  135. passwordFromIso := string(iso88591ToUTF8([]byte(password)))
  136. if auth(usernameFromIso, passwordFromIso, guiCfg, ldapCfg) {
  137. return usernameFromIso, true
  138. }
  139. emitLoginAttempt(false, username, r.RemoteAddr, evLogger)
  140. antiBruteForceSleep()
  141. return "", false
  142. }
  143. func createSession(cookieName string, username string, guiCfg config.GUIConfiguration, evLogger events.Logger, w http.ResponseWriter, r *http.Request) {
  144. sessionid := rand.String(32)
  145. sessionsMut.Lock()
  146. sessions[sessionid] = true
  147. sessionsMut.Unlock()
  148. // Best effort detection of whether the connection is HTTPS --
  149. // either directly to us, or as used by the client towards a reverse
  150. // proxy who sends us headers.
  151. connectionIsHTTPS := r.TLS != nil ||
  152. strings.ToLower(r.Header.Get("x-forwarded-proto")) == "https" ||
  153. strings.Contains(strings.ToLower(r.Header.Get("forwarded")), "proto=https")
  154. // If the connection is HTTPS, or *should* be HTTPS, set the Secure
  155. // bit in cookies.
  156. useSecureCookie := connectionIsHTTPS || guiCfg.UseTLS()
  157. http.SetCookie(w, &http.Cookie{
  158. Name: cookieName,
  159. Value: sessionid,
  160. // In HTTP spec Max-Age <= 0 means delete immediately,
  161. // but in http.Cookie MaxAge = 0 means unspecified (session) and MaxAge < 0 means delete immediately
  162. MaxAge: 0,
  163. Secure: useSecureCookie,
  164. Path: "/",
  165. })
  166. emitLoginAttempt(true, username, r.RemoteAddr, evLogger)
  167. }
  168. func handleLogout(cookieName string) http.Handler {
  169. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  170. cookie, err := r.Cookie(cookieName)
  171. if err == nil && cookie != nil {
  172. sessionsMut.Lock()
  173. delete(sessions, cookie.Value)
  174. sessionsMut.Unlock()
  175. }
  176. // else: If there is no session cookie, that's also a successful logout in terms of user experience.
  177. http.SetCookie(w, &http.Cookie{
  178. Name: cookieName,
  179. Value: "",
  180. MaxAge: -1,
  181. Secure: true,
  182. Path: "/",
  183. })
  184. w.WriteHeader(http.StatusNoContent)
  185. })
  186. }
  187. func auth(username string, password string, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration) bool {
  188. if guiCfg.AuthMode == config.AuthModeLDAP {
  189. return authLDAP(username, password, ldapCfg)
  190. } else {
  191. return authStatic(username, password, guiCfg)
  192. }
  193. }
  194. func authStatic(username string, password string, guiCfg config.GUIConfiguration) bool {
  195. return guiCfg.CompareHashedPassword(password) == nil && username == guiCfg.User
  196. }
  197. func authLDAP(username string, password string, cfg config.LDAPConfiguration) bool {
  198. address := cfg.Address
  199. hostname, _, err := net.SplitHostPort(address)
  200. if err != nil {
  201. hostname = address
  202. }
  203. var connection *ldap.Conn
  204. if cfg.Transport == config.LDAPTransportTLS {
  205. connection, err = ldap.DialTLS("tcp", address, &tls.Config{
  206. ServerName: hostname,
  207. InsecureSkipVerify: cfg.InsecureSkipVerify,
  208. })
  209. } else {
  210. connection, err = ldap.Dial("tcp", address)
  211. }
  212. if err != nil {
  213. l.Warnln("LDAP Dial:", err)
  214. return false
  215. }
  216. if cfg.Transport == config.LDAPTransportStartTLS {
  217. err = connection.StartTLS(&tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify})
  218. if err != nil {
  219. l.Warnln("LDAP Start TLS:", err)
  220. return false
  221. }
  222. }
  223. defer connection.Close()
  224. bindDN := formatOptionalPercentS(cfg.BindDN, escapeForLDAPDN(username))
  225. err = connection.Bind(bindDN, password)
  226. if err != nil {
  227. l.Warnln("LDAP Bind:", err)
  228. return false
  229. }
  230. if cfg.SearchFilter == "" && cfg.SearchBaseDN == "" {
  231. // We're done here.
  232. return true
  233. }
  234. if cfg.SearchFilter == "" || cfg.SearchBaseDN == "" {
  235. l.Warnln("LDAP configuration: both searchFilter and searchBaseDN must be set, or neither.")
  236. return false
  237. }
  238. // If a search filter and search base is set we do an LDAP search for
  239. // the user. If this matches precisely one user then we are good to go.
  240. // The search filter uses the same %s interpolation as the bind DN.
  241. searchString := formatOptionalPercentS(cfg.SearchFilter, escapeForLDAPFilter(username))
  242. const sizeLimit = 2 // we search for up to two users -- we only want to match one, so getting any number >1 is a failure.
  243. const timeLimit = 60 // Search for up to a minute...
  244. searchReq := ldap.NewSearchRequest(cfg.SearchBaseDN, ldap.ScopeWholeSubtree, ldap.DerefFindingBaseObj, sizeLimit, timeLimit, false, searchString, nil, nil)
  245. res, err := connection.Search(searchReq)
  246. if err != nil {
  247. l.Warnln("LDAP Search:", err)
  248. return false
  249. }
  250. if len(res.Entries) != 1 {
  251. l.Infof("Wrong number of LDAP search results, %d != 1", len(res.Entries))
  252. return false
  253. }
  254. return true
  255. }
  256. // escapeForLDAPFilter escapes a value that will be used in a filter clause
  257. func escapeForLDAPFilter(value string) string {
  258. // https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx#Special_Characters
  259. // Backslash must always be first in the list so we don't double escape them.
  260. return escapeRunes(value, []rune{'\\', '*', '(', ')', 0})
  261. }
  262. // escapeForLDAPDN escapes a value that will be used in a bind DN
  263. func escapeForLDAPDN(value string) string {
  264. // https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx
  265. // Backslash must always be first in the list so we don't double escape them.
  266. return escapeRunes(value, []rune{'\\', ',', '#', '+', '<', '>', ';', '"', '=', ' ', 0})
  267. }
  268. func escapeRunes(value string, runes []rune) string {
  269. for _, e := range runes {
  270. value = strings.ReplaceAll(value, string(e), fmt.Sprintf("\\%X", e))
  271. }
  272. return value
  273. }
  274. func formatOptionalPercentS(template string, username string) string {
  275. var replacements []any
  276. nReps := strings.Count(template, "%s") - strings.Count(template, "%%s")
  277. if nReps < 0 {
  278. nReps = 0
  279. }
  280. for i := 0; i < nReps; i++ {
  281. replacements = append(replacements, username)
  282. }
  283. return fmt.Sprintf(template, replacements...)
  284. }
  285. // Convert an ISO-8859-1 encoded byte string to UTF-8. Works by the
  286. // principle that ISO-8859-1 bytes are equivalent to unicode code points,
  287. // that a rune slice is a list of code points, and that stringifying a slice
  288. // of runes generates UTF-8 in Go.
  289. func iso88591ToUTF8(s []byte) []byte {
  290. runes := make([]rune, len(s))
  291. for i := range s {
  292. runes[i] = rune(s[i])
  293. }
  294. return []byte(string(runes))
  295. }