Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 25 additions & 18 deletions web/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,24 +65,31 @@ func (u *userAuthRoundtrip) ServeHTTP(w http.ResponseWriter, r *http.Request) {

user, pass, auth := r.BasicAuth()
if auth {
if hashedPassword, ok := c.Users[user]; ok {
cacheKey := hex.EncodeToString(append(append([]byte(user), []byte(hashedPassword)...), []byte(pass)...))
authOk, ok := u.cache.get(cacheKey)

if !ok {
// This user, hashedPassword, password is not cached.
u.bcryptMtx.Lock()
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(pass))
u.bcryptMtx.Unlock()

authOk = err == nil
u.cache.set(cacheKey, authOk)
}

if authOk {
u.handler.ServeHTTP(w, r)
return
}
hashedPassword, validUser := c.Users[user]

if !validUser {
// The user is not found. Use a fixed password hash to
// prevent user enumeration by timing requests.
// This is a bcrypt-hashed version of "fakepassword".
hashedPassword = "$2y$10$QOauhQNbBCuQDKes6eFzPeMqBSjb7Mr5DUmpZ/VcEd00UAV/LDeSi"
}

cacheKey := hex.EncodeToString(append(append([]byte(user), []byte(hashedPassword)...), []byte(pass)...))
authOk, ok := u.cache.get(cacheKey)

if !ok {
// This user, hashedPassword, password is not cached.
u.bcryptMtx.Lock()
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(pass))
u.bcryptMtx.Unlock()

authOk = err == nil
u.cache.set(cacheKey, authOk)
}

if authOk && validUser {
u.handler.ServeHTTP(w, r)
return
}
}

Expand Down
45 changes: 45 additions & 0 deletions web/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,48 @@ func TestBasicAuthCache(t *testing.T) {
close(start)
wg.Wait()
}

// TestBasicAuthWithFakePassword validates that we can't login the "fakepassword" used in
// to prevent user enumeration.
func TestBasicAuthWithFakepassword(t *testing.T) {
server := &http.Server{
Addr: port,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World!"))
}),
}

done := make(chan struct{})
t.Cleanup(func() {
if err := server.Shutdown(context.Background()); err != nil {
t.Fatal(err)
}
<-done
})

go func() {
ListenAndServe(server, "testdata/tls_config_users_noTLS.good.yml", testlogger)
close(done)
}()

login := func() {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://localhost"+port, nil)
if err != nil {
t.Fatal(err)
}
req.SetBasicAuth("fakeuser", "fakepassword")
r, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
if r.StatusCode != 401 {
t.Fatalf("bad return code, expected %d, got %d", 401, r.StatusCode)
}
}

// Login with a cold cache.
login()
// Login with the response cached.
login()
}