4 // We support SHA1 & bcrypt in HTPasswd
5 "crypto/sha1" // #nosec G505
12 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
13 "golang.org/x/crypto/bcrypt"
16// htpasswdMap represents the structure of an htpasswd file.
17// Passwords must be generated with -B for bcrypt or -s for SHA1.
18type htpasswdMap struct {
19 users map[string]interface{}
22// bcryptPass is used to identify bcrypt passwords in the
26// sha1Pass os used to identify sha1 passwords in the
30// NewHTPasswdValidator constructs an httpasswd based validator from the file
32func NewHTPasswdValidator(path string) (Validator, error) {
33 // We allow HTPasswd location via config options
34 r, err := os.Open(path) // #nosec G304
36 return nil, fmt.Errorf("could not open htpasswd file: %v", err)
38 defer func(c io.Closer) {
41 logger.Fatalf("error closing the htpasswd file: %v", cerr)
47// newHtpasswd consctructs an htpasswd from an io.Reader (an opened file).
48func newHtpasswd(file io.Reader) (*htpasswdMap, error) {
49 csvReader := csv.NewReader(file)
51 csvReader.Comment = '#'
52 csvReader.TrimLeadingSpace = true
54 records, err := csvReader.ReadAll()
56 return nil, fmt.Errorf("could not read htpasswd file: %v", err)
59 return createHtpasswdMap(records)
62// createHtasswdMap constructs an htpasswdMap from the given records
63func createHtpasswdMap(records [][]string) (*htpasswdMap, error) {
64 h := &htpasswdMap{users: make(map[string]interface{})}
65 for _, record := range records {
66 user, realPassword := record[0], record[1]
67 shaPrefix := realPassword[:5]
68 if shaPrefix == "{SHA}" {
69 h.users[user] = sha1Pass(realPassword[5:])
73 bcryptPrefix := realPassword[:4]
74 if bcryptPrefix == "$2a$" || bcryptPrefix == "$2b$" || bcryptPrefix == "$2x$" || bcryptPrefix == "$2y$" {
75 h.users[user] = bcryptPass(realPassword)
79 // Password is neither sha1 or bcrypt
80 // TODO(JoelSpeed): In the next breaking release, make this return an error.
81 logger.Errorf("Invalid htpasswd entry for %s. Must be a SHA or bcrypt entry.", user)
86// Validate checks a users password against the htpasswd entries
87func (h *htpasswdMap) Validate(user string, password string) bool {
88 realPassword, exists := h.users[user]
93 switch rp := realPassword.(type) {
95 // We support SHA1 HTPasswd entries
96 d := sha1.New() // #nosec G401
97 _, err := d.Write([]byte(password))
101 return string(rp) == base64.StdEncoding.EncodeToString(d.Sum(nil))
103 return bcrypt.CompareHashAndPassword([]byte(rp), []byte(password)) == nil
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list