auth.go 3.6 KB

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