api_auth.go 5.8 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. "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. }
  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. hdr := r.Header.Get("Authorization")
  57. if !strings.HasPrefix(hdr, "Basic ") {
  58. error()
  59. return
  60. }
  61. hdr = hdr[6:]
  62. bs, err := base64.StdEncoding.DecodeString(hdr)
  63. if err != nil {
  64. error()
  65. return
  66. }
  67. fields := bytes.SplitN(bs, []byte(":"), 2)
  68. if len(fields) != 2 {
  69. error()
  70. return
  71. }
  72. username := string(fields[0])
  73. password := string(fields[1])
  74. authOk := auth(username, password, guiCfg, ldapCfg)
  75. if !authOk {
  76. usernameIso := string(iso88591ToUTF8([]byte(username)))
  77. passwordIso := string(iso88591ToUTF8([]byte(password)))
  78. authOk = auth(usernameIso, passwordIso, guiCfg, ldapCfg)
  79. if authOk {
  80. username = usernameIso
  81. }
  82. }
  83. if !authOk {
  84. emitLoginAttempt(false, username, r.RemoteAddr, evLogger)
  85. error()
  86. return
  87. }
  88. sessionid := rand.String(32)
  89. sessionsMut.Lock()
  90. sessions[sessionid] = true
  91. sessionsMut.Unlock()
  92. http.SetCookie(w, &http.Cookie{
  93. Name: cookieName,
  94. Value: sessionid,
  95. MaxAge: 0,
  96. })
  97. emitLoginAttempt(true, username, r.RemoteAddr, evLogger)
  98. next.ServeHTTP(w, r)
  99. })
  100. }
  101. func auth(username string, password string, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration) bool {
  102. if guiCfg.AuthMode == config.AuthModeLDAP {
  103. return authLDAP(username, password, ldapCfg)
  104. } else {
  105. return authStatic(username, password, guiCfg.User, guiCfg.Password)
  106. }
  107. }
  108. func authStatic(username string, password string, configUser string, configPassword string) bool {
  109. configPasswordBytes := []byte(configPassword)
  110. passwordBytes := []byte(password)
  111. return bcrypt.CompareHashAndPassword(configPasswordBytes, passwordBytes) == nil && username == configUser
  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. }