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
This commit is contained in:
Thorben Günther 2022-10-13 13:08:54 +02:00
parent 9d0772b436
commit 1714bf5ed6
No known key found for this signature in database
GPG key ID: 415CD778D8C5AFED

12
main.go
View file

@ -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