1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2026-05-22 10:15:21 +02:00
Files
oauth2-proxy/htpasswd.go
T

73 lines
1.8 KiB
Go
Raw Normal View History

2012-12-10 20:59:23 -05:00
package main
import (
"crypto/sha1"
"encoding/base64"
"encoding/csv"
2012-12-17 13:38:33 -05:00
"io"
2012-12-10 20:59:23 -05:00
"os"
2018-02-16 02:14:41 -06:00
2019-05-24 17:08:48 +01:00
"github.com/pusher/oauth2_proxy/pkg/logger"
2018-02-16 02:14:41 -06:00
"golang.org/x/crypto/bcrypt"
2012-12-10 20:59:23 -05:00
)
2018-02-16 02:14:41 -06:00
// Lookup passwords in a htpasswd file
// Passwords must be generated with -B for bcrypt or -s for SHA1.
2012-12-10 20:59:23 -05:00
// HtpasswdFile represents the structure of an htpasswd file
2012-12-10 20:59:23 -05:00
type HtpasswdFile struct {
Users map[string]string
}
// NewHtpasswdFromFile constructs an HtpasswdFile from the file at the path given
2012-12-17 13:38:33 -05:00
func NewHtpasswdFromFile(path string) (*HtpasswdFile, error) {
2012-12-10 20:59:23 -05:00
r, err := os.Open(path)
if err != nil {
2012-12-17 13:38:33 -05:00
return nil, err
2012-12-10 20:59:23 -05:00
}
defer r.Close()
2012-12-17 13:38:33 -05:00
return NewHtpasswd(r)
}
// NewHtpasswd consctructs an HtpasswdFile from an io.Reader (opened file)
2012-12-17 13:38:33 -05:00
func NewHtpasswd(file io.Reader) (*HtpasswdFile, error) {
2018-11-29 14:26:41 +00:00
csvReader := csv.NewReader(file)
csvReader.Comma = ':'
csvReader.Comment = '#'
csvReader.TrimLeadingSpace = true
2012-12-10 20:59:23 -05:00
2018-11-29 14:26:41 +00:00
records, err := csvReader.ReadAll()
2012-12-10 20:59:23 -05:00
if err != nil {
2012-12-17 13:38:33 -05:00
return nil, err
2012-12-10 20:59:23 -05:00
}
h := &HtpasswdFile{Users: make(map[string]string)}
for _, record := range records {
h.Users[record[0]] = record[1]
}
2012-12-17 13:38:33 -05:00
return h, nil
2012-12-10 20:59:23 -05:00
}
// Validate checks a users password against the HtpasswdFile entries
2012-12-10 20:59:23 -05:00
func (h *HtpasswdFile) Validate(user string, password string) bool {
realPassword, exists := h.Users[user]
if !exists {
return false
}
2018-02-16 02:14:41 -06:00
shaPrefix := realPassword[:5]
if shaPrefix == "{SHA}" {
shaValue := realPassword[5:]
2012-12-10 20:59:23 -05:00
d := sha1.New()
d.Write([]byte(password))
2018-02-16 02:14:41 -06:00
return shaValue == base64.StdEncoding.EncodeToString(d.Sum(nil))
2012-12-10 20:59:23 -05:00
}
2018-02-16 02:14:41 -06:00
bcryptPrefix := realPassword[:4]
if bcryptPrefix == "$2a$" || bcryptPrefix == "$2b$" || bcryptPrefix == "$2x$" || bcryptPrefix == "$2y$" {
return bcrypt.CompareHashAndPassword([]byte(realPassword), []byte(password)) == nil
}
2019-02-10 08:37:45 -08:00
logger.Printf("Invalid htpasswd entry for %s. Must be a SHA or bcrypt entry.", user)
2012-12-10 20:59:23 -05:00
return false
}