1
0

api_auth.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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/http"
  13. "strings"
  14. "time"
  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. "golang.org/x/crypto/bcrypt"
  20. ldap "gopkg.in/ldap.v2"
  21. )
  22. var (
  23. sessions = make(map[string]bool)
  24. sessionsMut = sync.NewMutex()
  25. )
  26. func emitLoginAttempt(success bool, username string, evLogger events.Logger) {
  27. evLogger.Log(events.LoginAttempt, map[string]interface{}{
  28. "success": success,
  29. "username": username,
  30. })
  31. }
  32. func basicAuthAndSessionMiddleware(cookieName string, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration, next http.Handler, evLogger events.Logger) http.Handler {
  33. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  34. if guiCfg.IsValidAPIKey(r.Header.Get("X-API-Key")) {
  35. next.ServeHTTP(w, r)
  36. return
  37. }
  38. cookie, err := r.Cookie(cookieName)
  39. if err == nil && cookie != nil {
  40. sessionsMut.Lock()
  41. _, ok := sessions[cookie.Value]
  42. sessionsMut.Unlock()
  43. if ok {
  44. next.ServeHTTP(w, r)
  45. return
  46. }
  47. }
  48. l.Debugln("Sessionless HTTP request with authentication; this is expensive.")
  49. error := func() {
  50. time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
  51. w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
  52. http.Error(w, "Not Authorized", http.StatusUnauthorized)
  53. }
  54. hdr := r.Header.Get("Authorization")
  55. if !strings.HasPrefix(hdr, "Basic ") {
  56. error()
  57. return
  58. }
  59. hdr = hdr[6:]
  60. bs, err := base64.StdEncoding.DecodeString(hdr)
  61. if err != nil {
  62. error()
  63. return
  64. }
  65. fields := bytes.SplitN(bs, []byte(":"), 2)
  66. if len(fields) != 2 {
  67. error()
  68. return
  69. }
  70. username := string(fields[0])
  71. password := string(fields[1])
  72. authOk := auth(username, password, guiCfg, ldapCfg)
  73. if !authOk {
  74. usernameIso := string(iso88591ToUTF8([]byte(username)))
  75. passwordIso := string(iso88591ToUTF8([]byte(password)))
  76. authOk = auth(usernameIso, passwordIso, guiCfg, ldapCfg)
  77. if authOk {
  78. username = usernameIso
  79. }
  80. }
  81. if !authOk {
  82. emitLoginAttempt(false, username, evLogger)
  83. error()
  84. return
  85. }
  86. sessionid := rand.String(32)
  87. sessionsMut.Lock()
  88. sessions[sessionid] = true
  89. sessionsMut.Unlock()
  90. http.SetCookie(w, &http.Cookie{
  91. Name: cookieName,
  92. Value: sessionid,
  93. MaxAge: 0,
  94. })
  95. emitLoginAttempt(true, username, evLogger)
  96. next.ServeHTTP(w, r)
  97. })
  98. }
  99. func auth(username string, password string, guiCfg config.GUIConfiguration, ldapCfg config.LDAPConfiguration) bool {
  100. if guiCfg.AuthMode == config.AuthModeLDAP {
  101. return authLDAP(username, password, ldapCfg)
  102. } else {
  103. return authStatic(username, password, guiCfg.User, guiCfg.Password)
  104. }
  105. }
  106. func authStatic(username string, password string, configUser string, configPassword string) bool {
  107. configPasswordBytes := []byte(configPassword)
  108. passwordBytes := []byte(password)
  109. return bcrypt.CompareHashAndPassword(configPasswordBytes, passwordBytes) == nil && username == configUser
  110. }
  111. func authLDAP(username string, password string, cfg config.LDAPConfiguration) bool {
  112. address := cfg.Address
  113. var connection *ldap.Conn
  114. var err error
  115. if cfg.Transport == config.LDAPTransportTLS {
  116. connection, err = ldap.DialTLS("tcp", address, &tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify})
  117. } else {
  118. connection, err = ldap.Dial("tcp", address)
  119. }
  120. if err != nil {
  121. l.Warnln("LDAP Dial:", err)
  122. return false
  123. }
  124. if cfg.Transport == config.LDAPTransportStartTLS {
  125. err = connection.StartTLS(&tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify})
  126. if err != nil {
  127. l.Warnln("LDAP Start TLS:", err)
  128. return false
  129. }
  130. }
  131. defer connection.Close()
  132. err = connection.Bind(fmt.Sprintf(cfg.BindDN, username), password)
  133. if err != nil {
  134. l.Warnln("LDAP Bind:", err)
  135. return false
  136. }
  137. return true
  138. }
  139. // Convert an ISO-8859-1 encoded byte string to UTF-8. Works by the
  140. // principle that ISO-8859-1 bytes are equivalent to unicode code points,
  141. // that a rune slice is a list of code points, and that stringifying a slice
  142. // of runes generates UTF-8 in Go.
  143. func iso88591ToUTF8(s []byte) []byte {
  144. runes := make([]rune, len(s))
  145. for i := range s {
  146. runes[i] = rune(s[i])
  147. }
  148. return []byte(string(runes))
  149. }