api_auth.go 5.7 KB

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