api_auth.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. )
  20. var (
  21. sessions = make(map[string]bool)
  22. sessionsMut = sync.NewMutex()
  23. )
  24. func emitLoginAttempt(success bool, username, address string, evLogger events.Logger) {
  25. evLogger.Log(events.LoginAttempt, map[string]interface{}{
  26. "success": success,
  27. "username": username,
  28. "remoteAddress": address,
  29. })
  30. if !success {
  31. l.Infof("Wrong credentials supplied during API authorization from %s", address)
  32. }
  33. }
  34. func basicAuthAndSessionMiddleware(cookieName string, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration, next http.Handler, evLogger events.Logger) http.Handler {
  35. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  36. if guiCfg.IsValidAPIKey(r.Header.Get("X-API-Key")) {
  37. next.ServeHTTP(w, r)
  38. return
  39. }
  40. // Exception for REST calls that don't require authentication.
  41. if strings.HasPrefix(r.URL.Path, "/rest/noauth") {
  42. next.ServeHTTP(w, r)
  43. return
  44. }
  45. cookie, err := r.Cookie(cookieName)
  46. if err == nil && cookie != nil {
  47. sessionsMut.Lock()
  48. _, ok := sessions[cookie.Value]
  49. sessionsMut.Unlock()
  50. if ok {
  51. next.ServeHTTP(w, r)
  52. return
  53. }
  54. }
  55. l.Debugln("Sessionless HTTP request with authentication; this is expensive.")
  56. error := func() {
  57. time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
  58. w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
  59. http.Error(w, "Not Authorized", http.StatusUnauthorized)
  60. }
  61. username, password, ok := r.BasicAuth()
  62. if !ok {
  63. error()
  64. return
  65. }
  66. authOk := auth(username, password, guiCfg, ldapCfg)
  67. if !authOk {
  68. usernameIso := string(iso88591ToUTF8([]byte(username)))
  69. passwordIso := string(iso88591ToUTF8([]byte(password)))
  70. authOk = auth(usernameIso, passwordIso, guiCfg, ldapCfg)
  71. if authOk {
  72. username = usernameIso
  73. }
  74. }
  75. if !authOk {
  76. emitLoginAttempt(false, username, r.RemoteAddr, evLogger)
  77. error()
  78. return
  79. }
  80. sessionid := rand.String(32)
  81. sessionsMut.Lock()
  82. sessions[sessionid] = true
  83. sessionsMut.Unlock()
  84. // Best effort detection of whether the connection is HTTPS --
  85. // either directly to us, or as used by the client towards a reverse
  86. // proxy who sends us headers.
  87. connectionIsHTTPS := r.TLS != nil ||
  88. strings.ToLower(r.Header.Get("x-forwarded-proto")) == "https" ||
  89. strings.Contains(strings.ToLower(r.Header.Get("forwarded")), "proto=https")
  90. // If the connection is HTTPS, or *should* be HTTPS, set the Secure
  91. // bit in cookies.
  92. useSecureCookie := connectionIsHTTPS || guiCfg.UseTLS()
  93. http.SetCookie(w, &http.Cookie{
  94. Name: cookieName,
  95. Value: sessionid,
  96. MaxAge: 0,
  97. Secure: useSecureCookie,
  98. })
  99. emitLoginAttempt(true, username, r.RemoteAddr, evLogger)
  100. next.ServeHTTP(w, r)
  101. })
  102. }
  103. func auth(username string, password string, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration) bool {
  104. if guiCfg.AuthMode == config.AuthModeLDAP {
  105. return authLDAP(username, password, ldapCfg)
  106. } else {
  107. return authStatic(username, password, guiCfg)
  108. }
  109. }
  110. func authStatic(username string, password string, guiCfg config.GUIConfiguration) bool {
  111. return guiCfg.CompareHashedPassword(password) == nil && username == guiCfg.User
  112. }
  113. func authLDAP(username string, password string, cfg config.LDAPConfiguration) bool {
  114. address := cfg.Address
  115. hostname, _, err := net.SplitHostPort(address)
  116. if err != nil {
  117. hostname = address
  118. }
  119. var connection *ldap.Conn
  120. if cfg.Transport == config.LDAPTransportTLS {
  121. connection, err = ldap.DialTLS("tcp", address, &tls.Config{
  122. ServerName: hostname,
  123. InsecureSkipVerify: cfg.InsecureSkipVerify,
  124. })
  125. } else {
  126. connection, err = ldap.Dial("tcp", address)
  127. }
  128. if err != nil {
  129. l.Warnln("LDAP Dial:", err)
  130. return false
  131. }
  132. if cfg.Transport == config.LDAPTransportStartTLS {
  133. err = connection.StartTLS(&tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify})
  134. if err != nil {
  135. l.Warnln("LDAP Start TLS:", err)
  136. return false
  137. }
  138. }
  139. defer connection.Close()
  140. err = connection.Bind(fmt.Sprintf(cfg.BindDN, username), password)
  141. if err != nil {
  142. l.Warnln("LDAP Bind:", err)
  143. return false
  144. }
  145. if cfg.SearchFilter == "" && cfg.SearchBaseDN == "" {
  146. // We're done here.
  147. return true
  148. }
  149. if cfg.SearchFilter == "" || cfg.SearchBaseDN == "" {
  150. l.Warnln("LDAP configuration: both searchFilter and searchBaseDN must be set, or neither.")
  151. return false
  152. }
  153. // If a search filter and search base is set we do an LDAP search for
  154. // the user. If this matches precisely one user then we are good to go.
  155. // The search filter uses the same %s interpolation as the bind DN.
  156. searchString := fmt.Sprintf(cfg.SearchFilter, username)
  157. const sizeLimit = 2 // we search for up to two users -- we only want to match one, so getting any number >1 is a failure.
  158. const timeLimit = 60 // Search for up to a minute...
  159. searchReq := ldap.NewSearchRequest(cfg.SearchBaseDN, ldap.ScopeWholeSubtree, ldap.DerefFindingBaseObj, sizeLimit, timeLimit, false, searchString, nil, nil)
  160. res, err := connection.Search(searchReq)
  161. if err != nil {
  162. l.Warnln("LDAP Search:", err)
  163. return false
  164. }
  165. if len(res.Entries) != 1 {
  166. l.Infof("Wrong number of LDAP search results, %d != 1", len(res.Entries))
  167. return false
  168. }
  169. return true
  170. }
  171. // Convert an ISO-8859-1 encoded byte string to UTF-8. Works by the
  172. // principle that ISO-8859-1 bytes are equivalent to unicode code points,
  173. // that a rune slice is a list of code points, and that stringifying a slice
  174. // of runes generates UTF-8 in Go.
  175. func iso88591ToUTF8(s []byte) []byte {
  176. runes := make([]rune, len(s))
  177. for i := range s {
  178. runes[i] = rune(s[i])
  179. }
  180. return []byte(string(runes))
  181. }