api_auth.go 5.9 KB

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