auth.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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. sync.RWMutex
  30. Info os.FileInfo
  31. Users map[string]string
  32. }
  33. func newBasicAuthProvider(authUserFile string) (httpAuthProvider, error) {
  34. basicAuthProvider := basicAuthProvider{
  35. Path: authUserFile,
  36. Info: nil,
  37. Users: make(map[string]string),
  38. }
  39. return &basicAuthProvider, basicAuthProvider.loadUsers()
  40. }
  41. func (p *basicAuthProvider) isEnabled() bool {
  42. return len(p.Path) > 0
  43. }
  44. func (p *basicAuthProvider) isReloadNeeded(info os.FileInfo) bool {
  45. p.RLock()
  46. defer p.RUnlock()
  47. return p.Info == nil || p.Info.ModTime() != info.ModTime() || p.Info.Size() != info.Size()
  48. }
  49. func (p *basicAuthProvider) loadUsers() error {
  50. if !p.isEnabled() {
  51. return nil
  52. }
  53. info, err := os.Stat(p.Path)
  54. if err != nil {
  55. logger.Debug(logSender, "", "unable to stat basic auth users file: %v", err)
  56. return err
  57. }
  58. if p.isReloadNeeded(info) {
  59. r, err := os.Open(p.Path)
  60. if err != nil {
  61. logger.Debug(logSender, "", "unable to open basic auth users file: %v", err)
  62. return err
  63. }
  64. defer r.Close()
  65. reader := csv.NewReader(r)
  66. reader.Comma = ':'
  67. reader.Comment = '#'
  68. reader.TrimLeadingSpace = true
  69. records, err := reader.ReadAll()
  70. if err != nil {
  71. logger.Debug(logSender, "", "unable to parse basic auth users file: %v", err)
  72. return err
  73. }
  74. p.Lock()
  75. defer p.Unlock()
  76. p.Users = make(map[string]string)
  77. for _, record := range records {
  78. if len(record) == 2 {
  79. p.Users[record[0]] = record[1]
  80. }
  81. }
  82. logger.Debug(logSender, "", "number of users loaded for httpd basic auth: %v", len(p.Users))
  83. p.Info = info
  84. }
  85. return nil
  86. }
  87. func (p *basicAuthProvider) getHashedPassword(username string) (string, bool) {
  88. err := p.loadUsers()
  89. if err != nil {
  90. return "", false
  91. }
  92. p.RLock()
  93. defer p.RUnlock()
  94. pwd, ok := p.Users[username]
  95. return pwd, ok
  96. }
  97. func checkAuth(next http.Handler) http.Handler {
  98. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  99. if !validateCredentials(r) {
  100. w.Header().Set(authenticationHeader, fmt.Sprintf("Basic realm=\"%v\"", authenticationRealm))
  101. sendAPIResponse(w, r, errors.New(unauthResponse), "", http.StatusUnauthorized)
  102. return
  103. }
  104. next.ServeHTTP(w, r)
  105. })
  106. }
  107. func validateCredentials(r *http.Request) bool {
  108. if !httpAuth.isEnabled() {
  109. return true
  110. }
  111. username, password, ok := r.BasicAuth()
  112. if !ok {
  113. return false
  114. }
  115. if hashedPwd, ok := httpAuth.getHashedPassword(username); ok {
  116. if utils.IsStringPrefixInSlice(hashedPwd, bcryptPwdPrefixes) {
  117. err := bcrypt.CompareHashAndPassword([]byte(hashedPwd), []byte(password))
  118. return err == nil
  119. }
  120. if utils.IsStringPrefixInSlice(hashedPwd, md5CryptPwdPrefixes) {
  121. crypter, ok := unixcrypt.MD5.CrypterFound(hashedPwd)
  122. if !ok {
  123. err := errors.New("cannot found matching MD5 crypter")
  124. logger.Debug(logSender, "", "error comparing password with MD5 crypt hash: %v", err)
  125. return false
  126. }
  127. return crypter.Verify([]byte(password))
  128. }
  129. }
  130. return false
  131. }