From 68bed96054714a4db18c910c32c5470952a5983a Mon Sep 17 00:00:00 2001 From: Till! Date: Sun, 9 Jun 2024 17:33:47 +0200 Subject: [PATCH] Fix(auth): use crypto/subtle to compare strings (#39) * Fix(auth): use crypto/subtle to compare strings Related: #37 Signed-off-by: till * Remove empty line --------- Signed-off-by: till Co-authored-by: Friedrich Gonzalez <1517449+friedrichg@users.noreply.github.com> --- gateway/middleware.go | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/gateway/middleware.go b/gateway/middleware.go index d6b2469..f4fcbc6 100644 --- a/gateway/middleware.go +++ b/gateway/middleware.go @@ -1,6 +1,7 @@ package gateway import ( + "crypto/subtle" "net/http" "github.com/cortexproject/auth-gateway/middleware" @@ -53,14 +54,20 @@ func (tenant *Tenant) basicAuth(w http.ResponseWriter, r *http.Request) bool { return false } - if tenant.Username == username { - if tenant.Password == password { - r.Header.Set("X-Scope-OrgID", tenant.ID) - return true - } else { - return false - } + if !tenant.saveCompare(username, password) { + return false } + r.Header.Set("X-Scope-OrgID", tenant.ID) + return true +} + +// attempt to mitigate timing attacks +func (tenant *Tenant) saveCompare(username, password string) bool { + userNameCheck := subtle.ConstantTimeCompare([]byte(tenant.Username), []byte(username)) + passwordCheck := subtle.ConstantTimeCompare([]byte(tenant.Password), []byte(password)) + if userNameCheck == 1 && passwordCheck == 1 { + return true + } return false }