auth.go 3.7 KB

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