git.iko.soy/typeable/oauth2-proxy
on master help sign in
Add HTPasswdValidator to basic authentication package
commit7d8ee6125421e2cf033f6d6c89ea59e6fd061ccf authorJoel Speed <joel.speed@hotmail.co.uk> dateSat 18 Jul 2020, 00:41 (6 years ago) parent895403c
7 files changed+239
pkg/authentication/basic/basic_suite_test.go+16 pkg/authentication/basic/htpasswd.go+96 pkg/authentication/basic/htpasswd_test.go+96 pkg/authentication/basic/test/htpasswd-bcrypt.txt+8 pkg/authentication/basic/test/htpasswd-mixed.txt+8 pkg/authentication/basic/test/htpasswd-sha1.txt+8 pkg/authentication/basic/validator.go+7
pkg/authentication/basic/basic_suite_test.gonew file+16
@@ -0,0 +1,16 @@
1+package basic
2+
3+import (
4+ "testing"
5+
6+ "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
7+ . "github.com/onsi/ginkgo"
8+ . "github.com/onsi/gomega"
9+)
10+
11+func TestBasicSuite(t *testing.T) {
12+ logger.SetOutput(GinkgoWriter)
13+
14+ RegisterFailHandler(Fail)
15+ RunSpecs(t, "Basic")
16+}
pkg/authentication/basic/htpasswd.gonew file+96
@@ -0,0 +1,96 @@
1+package basic
2+
3+import (
4+ "crypto/sha1"
5+ "encoding/base64"
6+ "encoding/csv"
7+ "fmt"
8+ "io"
9+ "os"
10+
11+ "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
12+ "golang.org/x/crypto/bcrypt"
13+)
14+
15+// htpasswdMap represents the structure of an htpasswd file.
16+// Passwords must be generated with -B for bcrypt or -s for SHA1.
17+type htpasswdMap struct {
18+ users map[string]interface{}
19+}
20+
21+// bcryptPass is used to identify bcrypt passwords in the
22+// htpasswdMap users.
23+type bcryptPass string
24+
25+// sha1Pass os used to identify sha1 passwords in the
26+// htpasswdMap users.
27+type sha1Pass string
28+
29+// NewHTPasswdValidator constructs an httpasswd based validator from the file
30+// at the path given.
31+func NewHTPasswdValidator(path string) (Validator, error) {
32+ r, err := os.Open(path)
33+ if err != nil {
34+ return nil, fmt.Errorf("could not open htpasswd file: %v", err)
35+ }
36+ defer r.Close()
37+ return newHtpasswd(r)
38+}
39+
40+// newHtpasswd consctructs an htpasswd from an io.Reader (an opened file).
41+func newHtpasswd(file io.Reader) (*htpasswdMap, error) {
42+ csvReader := csv.NewReader(file)
43+ csvReader.Comma = ':'
44+ csvReader.Comment = '#'
45+ csvReader.TrimLeadingSpace = true
46+
47+ records, err := csvReader.ReadAll()
48+ if err != nil {
49+ return nil, fmt.Errorf("could not read htpasswd file: %v", err)
50+ }
51+
52+ return createHtpasswdMap(records)
53+}
54+
55+// createHtasswdMap constructs an htpasswdMap from the given records
56+func createHtpasswdMap(records [][]string) (*htpasswdMap, error) {
57+ h := &htpasswdMap{users: make(map[string]interface{})}
58+ for _, record := range records {
59+ user, realPassword := record[0], record[1]
60+ shaPrefix := realPassword[:5]
61+ if shaPrefix == "{SHA}" {
62+ h.users[user] = sha1Pass(realPassword[5:])
63+ continue
64+ }
65+
66+ bcryptPrefix := realPassword[:4]
67+ if bcryptPrefix == "$2a$" || bcryptPrefix == "$2b$" || bcryptPrefix == "$2x$" || bcryptPrefix == "$2y$" {
68+ h.users[user] = bcryptPass(realPassword)
69+ continue
70+ }
71+
72+ // Password is neither sha1 or bcrypt
73+ // TODO(JoelSpeed): In the next breaking release, make this return an error.
74+ logger.Printf("Invalid htpasswd entry for %s. Must be a SHA or bcrypt entry.", user)
75+ }
76+ return h, nil
77+}
78+
79+// Validate checks a users password against the htpasswd entries
80+func (h *htpasswdMap) Validate(user string, password string) bool {
81+ realPassword, exists := h.users[user]
82+ if !exists {
83+ return false
84+ }
85+
86+ switch real := realPassword.(type) {
87+ case sha1Pass:
88+ d := sha1.New()
89+ d.Write([]byte(password))
90+ return string(real) == base64.StdEncoding.EncodeToString(d.Sum(nil))
91+ case bcryptPass:
92+ return bcrypt.CompareHashAndPassword([]byte(real), []byte(password)) == nil
93+ default:
94+ return false
95+ }
96+}
pkg/authentication/basic/htpasswd_test.gonew file+96
@@ -0,0 +1,96 @@
1+package basic
2+
3+import (
4+ . "github.com/onsi/ginkgo"
5+ . "github.com/onsi/gomega"
6+)
7+
8+const (
9+ adminUser = "admin"
10+ adminPassword = "Adm1n1str$t0r"
11+ user1 = "user1"
12+ user1Password = "UsErOn3P455"
13+ user2 = "user2"
14+ user2Password = "us3r2P455W0Rd!"
15+)
16+
17+var _ = Describe("HTPasswd Suite", func() {
18+ Context("with an HTPassword Validator", func() {
19+ assertHtpasswdMapFromFile := func(filePath string) {
20+ var htpasswd *htpasswdMap
21+ var err error
22+
23+ BeforeEach(func() {
24+ var validator Validator
25+ validator, err = NewHTPasswdValidator(filePath)
26+
27+ var ok bool
28+ htpasswd, ok = validator.(*htpasswdMap)
29+ Expect(ok).To(BeTrue())
30+ })
31+
32+ It("does not return an error", func() {
33+ Expect(err).ToNot(HaveOccurred())
34+ })
35+
36+ It("has the correct number of users", func() {
37+ Expect(htpasswd.users).To(HaveLen(3))
38+ })
39+
40+ It("accepts the correct passwords", func() {
41+ Expect(htpasswd.Validate(adminUser, adminPassword)).To(BeTrue())
42+ Expect(htpasswd.Validate(user1, user1Password)).To(BeTrue())
43+ Expect(htpasswd.Validate(user2, user2Password)).To(BeTrue())
44+ })
45+
46+ It("rejects incorrect passwords", func() {
47+ Expect(htpasswd.Validate(adminUser, "asvdfda")).To(BeFalse())
48+ Expect(htpasswd.Validate(user1, "BHEdgbtr")).To(BeFalse())
49+ Expect(htpasswd.Validate(user2, "12345")).To(BeFalse())
50+ })
51+
52+ It("rejects a non existent user", func() {
53+ // Users are case sensitive
54+ Expect(htpasswd.Validate("ADMIN", adminPassword)).To(BeFalse())
55+ })
56+ }
57+
58+ Context("load from file", func() {
59+ Context("with sha1 entries", func() {
60+ const filePath = "./test/htpasswd-sha1.txt"
61+
62+ assertHtpasswdMapFromFile(filePath)
63+ })
64+
65+ Context("with bcrypt entries", func() {
66+ const filePath = "./test/htpasswd-bcrypt.txt"
67+
68+ assertHtpasswdMapFromFile(filePath)
69+ })
70+
71+ Context("with mixed entries", func() {
72+ const filePath = "./test/htpasswd-mixed.txt"
73+
74+ assertHtpasswdMapFromFile(filePath)
75+ })
76+
77+ Context("with a non existent file", func() {
78+ const filePath = "./test/htpasswd-doesnt-exist.txt"
79+ var validator Validator
80+ var err error
81+
82+ BeforeEach(func() {
83+ validator, err = NewHTPasswdValidator(filePath)
84+ })
85+
86+ It("returns an error", func() {
87+ Expect(err).To(MatchError("could not open htpasswd file: open ./test/htpasswd-doesnt-exist.txt: no such file or directory"))
88+ })
89+
90+ It("returns a nil validator", func() {
91+ Expect(validator).To(BeNil())
92+ })
93+ })
94+ })
95+ })
96+})
pkg/authentication/basic/test/htpasswd-bcrypt.txtnew file+8
@@ -0,0 +1,8 @@
1+# admin:Adm1n1str$t0r
2+admin:$2y$05$SXWrNM7ldtbRzBvUC3VXyOvUeiUcP45XPwM93P5eeGOEPIiAZmJjC
3+
4+# user1:UsErOn3P455
5+user1:$2y$05$/sZYJOk8.3Etg4V6fV7puuXfCJLmV5Q7u3xvKpjBSJUka.t2YtmmG
6+
7+# user2: us3r2P455W0Rd!
8+user2:$2y$05$l22MubgKTZFTjTs8TNg5k.YKvcnM2.bA/.iwl0idef5CbekdvBxva
pkg/authentication/basic/test/htpasswd-mixed.txtnew file+8
@@ -0,0 +1,8 @@
1+# admin:Adm1n1str$t0r
2+admin:$2y$05$SXWrNM7ldtbRzBvUC3VXyOvUeiUcP45XPwM93P5eeGOEPIiAZmJjC
3+
4+# user1:UsErOn3P455
5+user1:{SHA}Dvs/L78raajL4jEAHPkwflQXJzI=
6+
7+# user2: us3r2P455W0Rd!
8+user2:{SHA}MoN9/JCJEcYUb6GCQ+2buDvn9pI=
pkg/authentication/basic/test/htpasswd-sha1.txtnew file+8
@@ -0,0 +1,8 @@
1+# admin:Adm1n1str$t0r
2+admin:{SHA}gXQeRH0bcaCfhAk2gOLm1uaePMA=
3+
4+# user1:UsErOn3P455
5+user1:{SHA}Dvs/L78raajL4jEAHPkwflQXJzI=
6+
7+# user2: us3r2P455W0Rd!
8+user2:{SHA}MoN9/JCJEcYUb6GCQ+2buDvn9pI=
pkg/authentication/basic/validator.gonew file+7
@@ -0,0 +1,7 @@
1+package basic
2+
3+// Validator is a minimal interface for something that can validate a
4+// username and password combination.
5+type Validator interface {
6+ Validate(user, password string) bool
7+}