auth.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. package httpd
  2. import (
  3. "encoding/csv"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "sync"
  9. unixcrypt "github.com/nathanaelle/password/v2"
  10. "github.com/drakkan/sftpgo/ldapauthserver/logger"
  11. "github.com/drakkan/sftpgo/ldapauthserver/utils"
  12. "golang.org/x/crypto/bcrypt"
  13. )
  14. const (
  15. authenticationHeader = "WWW-Authenticate"
  16. authenticationRealm = "LDAP Auth Server"
  17. unauthResponse = "Unauthorized"
  18. )
  19. var (
  20. md5CryptPwdPrefixes = []string{"$1$", "$apr1$"}
  21. bcryptPwdPrefixes = []string{"$2a$", "$2$", "$2x$", "$2y$", "$2b$"}
  22. )
  23. type httpAuthProvider interface {
  24. getHashedPassword(username string) (string, bool)
  25. isEnabled() bool
  26. }
  27. type basicAuthProvider struct {
  28. Path string
  29. Info os.FileInfo
  30. Users map[string]string
  31. lock *sync.RWMutex
  32. }
  33. func newBasicAuthProvider(authUserFile string) (httpAuthProvider, error) {
  34. basicAuthProvider := basicAuthProvider{
  35. Path: authUserFile,
  36. Info: nil,
  37. Users: make(map[string]string),
  38. lock: new(sync.RWMutex),
  39. }
  40. return &basicAuthProvider, basicAuthProvider.loadUsers()
  41. }
  42. func (p *basicAuthProvider) isEnabled() bool {
  43. return len(p.Path) > 0
  44. }
  45. func (p *basicAuthProvider) isReloadNeeded(info os.FileInfo) bool {
  46. p.lock.RLock()
  47. defer p.lock.RUnlock()
  48. return p.Info == nil || p.Info.ModTime() != info.ModTime() || p.Info.Size() != info.Size()
  49. }
  50. func (p *basicAuthProvider) loadUsers() error {
  51. if !p.isEnabled() {
  52. return nil
  53. }
  54. info, err := os.Stat(p.Path)
  55. if err != nil {
  56. logger.Debug(logSender, "", "unable to stat basic auth users file: %v", err)
  57. return err
  58. }
  59. if p.isReloadNeeded(info) {
  60. r, err := os.Open(p.Path)
  61. if err != nil {
  62. logger.Debug(logSender, "", "unable to open basic auth users file: %v", err)
  63. return err
  64. }
  65. defer r.Close()
  66. reader := csv.NewReader(r)
  67. reader.Comma = ':'
  68. reader.Comment = '#'
  69. reader.TrimLeadingSpace = true
  70. records, err := reader.ReadAll()
  71. if err != nil {
  72. logger.Debug(logSender, "", "unable to parse basic auth users file: %v", err)
  73. return err
  74. }
  75. p.lock.Lock()
  76. defer p.lock.Unlock()
  77. p.Users = make(map[string]string)
  78. for _, record := range records {
  79. if len(record) == 2 {
  80. p.Users[record[0]] = record[1]
  81. }
  82. }
  83. logger.Debug(logSender, "", "number of users loaded for httpd basic auth: %v", len(p.Users))
  84. p.Info = info
  85. }
  86. return nil
  87. }
  88. func (p *basicAuthProvider) getHashedPassword(username string) (string, bool) {
  89. err := p.loadUsers()
  90. if err != nil {
  91. return "", false
  92. }
  93. p.lock.RLock()
  94. defer p.lock.RUnlock()
  95. pwd, ok := p.Users[username]
  96. return pwd, ok
  97. }
  98. func checkAuth(next http.Handler) http.Handler {
  99. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  100. if !validateCredentials(r) {
  101. w.Header().Set(authenticationHeader, fmt.Sprintf("Basic realm=\"%v\"", authenticationRealm))
  102. sendAPIResponse(w, r, errors.New(unauthResponse), "", http.StatusUnauthorized)
  103. return
  104. }
  105. next.ServeHTTP(w, r)
  106. })
  107. }
  108. func validateCredentials(r *http.Request) bool {
  109. if !httpAuth.isEnabled() {
  110. return true
  111. }
  112. username, password, ok := r.BasicAuth()
  113. if !ok {
  114. return false
  115. }
  116. if hashedPwd, ok := httpAuth.getHashedPassword(username); ok {
  117. if utils.IsStringPrefixInSlice(hashedPwd, bcryptPwdPrefixes) {
  118. err := bcrypt.CompareHashAndPassword([]byte(hashedPwd), []byte(password))
  119. return err == nil
  120. }
  121. if utils.IsStringPrefixInSlice(hashedPwd, md5CryptPwdPrefixes) {
  122. crypter, ok := unixcrypt.MD5.CrypterFound(hashedPwd)
  123. if !ok {
  124. err := errors.New("cannot found matching MD5 crypter")
  125. logger.Debug(logSender, "", "error comparing password with MD5 crypt hash: %v", err)
  126. return false
  127. }
  128. return crypter.Verify([]byte(password))
  129. }
  130. }
  131. return false
  132. }