api_auth.go 11 KB

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