httpauth.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package common
  15. import (
  16. "encoding/csv"
  17. "os"
  18. "strings"
  19. "sync"
  20. "github.com/GehirnInc/crypt/apr1_crypt"
  21. "github.com/GehirnInc/crypt/md5_crypt"
  22. "golang.org/x/crypto/bcrypt"
  23. "github.com/drakkan/sftpgo/v2/internal/logger"
  24. "github.com/drakkan/sftpgo/v2/internal/util"
  25. )
  26. const (
  27. // HTTPAuthenticationHeader defines the HTTP authentication
  28. HTTPAuthenticationHeader = "WWW-Authenticate"
  29. md5CryptPwdPrefix = "$1$"
  30. apr1CryptPwdPrefix = "$apr1$"
  31. )
  32. var (
  33. bcryptPwdPrefixes = []string{"$2a$", "$2$", "$2x$", "$2y$", "$2b$"}
  34. )
  35. // HTTPAuthProvider defines the interface for HTTP auth providers
  36. type HTTPAuthProvider interface {
  37. ValidateCredentials(username, password string) bool
  38. IsEnabled() bool
  39. }
  40. type basicAuthProvider struct {
  41. Path string
  42. sync.RWMutex
  43. Info os.FileInfo
  44. Users map[string]string
  45. }
  46. // NewBasicAuthProvider returns an HTTPAuthProvider implementing Basic Auth
  47. func NewBasicAuthProvider(authUserFile string) (HTTPAuthProvider, error) {
  48. basicAuthProvider := basicAuthProvider{
  49. Path: authUserFile,
  50. Info: nil,
  51. Users: make(map[string]string),
  52. }
  53. return &basicAuthProvider, basicAuthProvider.loadUsers()
  54. }
  55. func (p *basicAuthProvider) IsEnabled() bool {
  56. return p.Path != ""
  57. }
  58. func (p *basicAuthProvider) isReloadNeeded(info os.FileInfo) bool {
  59. p.RLock()
  60. defer p.RUnlock()
  61. return p.Info == nil || p.Info.ModTime() != info.ModTime() || p.Info.Size() != info.Size()
  62. }
  63. func (p *basicAuthProvider) loadUsers() error {
  64. if !p.IsEnabled() {
  65. return nil
  66. }
  67. info, err := os.Stat(p.Path)
  68. if err != nil {
  69. logger.Debug(logSender, "", "unable to stat basic auth users file: %v", err)
  70. return err
  71. }
  72. if p.isReloadNeeded(info) {
  73. r, err := os.Open(p.Path)
  74. if err != nil {
  75. logger.Debug(logSender, "", "unable to open basic auth users file: %v", err)
  76. return err
  77. }
  78. defer r.Close()
  79. reader := csv.NewReader(r)
  80. reader.Comma = ':'
  81. reader.Comment = '#'
  82. reader.TrimLeadingSpace = true
  83. records, err := reader.ReadAll()
  84. if err != nil {
  85. logger.Debug(logSender, "", "unable to parse basic auth users file: %v", err)
  86. return err
  87. }
  88. p.Lock()
  89. defer p.Unlock()
  90. p.Users = make(map[string]string)
  91. for _, record := range records {
  92. if len(record) == 2 {
  93. p.Users[record[0]] = record[1]
  94. }
  95. }
  96. logger.Debug(logSender, "", "number of users loaded for httpd basic auth: %v", len(p.Users))
  97. p.Info = info
  98. }
  99. return nil
  100. }
  101. func (p *basicAuthProvider) getHashedPassword(username string) (string, bool) {
  102. err := p.loadUsers()
  103. if err != nil {
  104. return "", false
  105. }
  106. p.RLock()
  107. defer p.RUnlock()
  108. pwd, ok := p.Users[username]
  109. return pwd, ok
  110. }
  111. // ValidateCredentials returns true if the credentials are valid
  112. func (p *basicAuthProvider) ValidateCredentials(username, password string) bool {
  113. if hashedPwd, ok := p.getHashedPassword(username); ok {
  114. if util.IsStringPrefixInSlice(hashedPwd, bcryptPwdPrefixes) {
  115. err := bcrypt.CompareHashAndPassword([]byte(hashedPwd), []byte(password))
  116. return err == nil
  117. }
  118. if strings.HasPrefix(hashedPwd, md5CryptPwdPrefix) {
  119. crypter := md5_crypt.New()
  120. err := crypter.Verify(hashedPwd, []byte(password))
  121. return err == nil
  122. }
  123. if strings.HasPrefix(hashedPwd, apr1CryptPwdPrefix) {
  124. crypter := apr1_crypt.New()
  125. err := crypter.Verify(hashedPwd, []byte(password))
  126. return err == nil
  127. }
  128. }
  129. return false
  130. }