From 1714bf5ed6b8a32aa8a260e648051f2b0c8a579d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Thu, 13 Oct 2022 13:08:54 +0200 Subject: [PATCH] basicAuthMiddleware: Protect against timing attacks Compare strings of equal length (hashed with SHA-512) with ConstantTimeCompare. Closes: https://todo.xenrox.net/~xenrox/ntfy-alertmanager/1 --- main.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 9d58cf2..9d46c1d 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,8 @@ package main import ( + "crypto/sha512" + "crypto/subtle" "encoding/base64" "encoding/json" "flag" @@ -169,7 +171,15 @@ func (rcv *receiver) basicAuthMiddleware(handler http.HandlerFunc) http.HandlerF return } - if user != rcv.cfg.User || pass != rcv.cfg.Password { + inputUserHash := sha512.Sum512([]byte(user)) + inputPassHash := sha512.Sum512([]byte(pass)) + configUserHash := sha512.Sum512([]byte(rcv.cfg.User)) + configPassHash := sha512.Sum512([]byte(rcv.cfg.Password)) + + validUser := subtle.ConstantTimeCompare(inputUserHash[:], configUserHash[:]) + validPass := subtle.ConstantTimeCompare(inputPassHash[:], configPassHash[:]) + + if validUser != 1 || validPass != 1 { http.Error(w, "Unauthorized", http.StatusUnauthorized) rcv.logger.Debug("basic auth: wrong user or password") return