api_auth.go 6.4 KB

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