mirror of
https://github.com/VictoriaMetrics/VictoriaMetrics.git
synced 2026-05-17 08:36:55 +03:00
victoria-metrics: constant-time comparison of credentials like authkeys and basic auth credentials (#6423)
Changes for constant-time comparison of credentials like authkeys and basic auth credentials. See: https://github.com/VictoriaMetrics/VictoriaMetrics/issues/6392 --------- Signed-off-by: Syed Nihal <syed.nihal@nokia.com>
This commit is contained in:
@@ -2,6 +2,7 @@ package httpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"crypto/tls"
|
||||
_ "embed"
|
||||
"errors"
|
||||
@@ -442,7 +443,7 @@ func CheckAuthFlag(w http.ResponseWriter, r *http.Request, flagValue string, fla
|
||||
if flagValue == "" {
|
||||
return CheckBasicAuth(w, r)
|
||||
}
|
||||
if r.FormValue("authKey") != flagValue {
|
||||
if !constantTimeEqual(r.FormValue("authKey"), flagValue) {
|
||||
authKeyRequestErrors.Inc()
|
||||
http.Error(w, fmt.Sprintf("The provided authKey doesn't match -%s", flagName), http.StatusUnauthorized)
|
||||
return false
|
||||
@@ -459,7 +460,7 @@ func CheckBasicAuth(w http.ResponseWriter, r *http.Request) bool {
|
||||
}
|
||||
username, password, ok := r.BasicAuth()
|
||||
if ok {
|
||||
if username == *httpAuthUsername && password == httpAuthPassword.Get() {
|
||||
if constantTimeEqual(username, *httpAuthUsername) && constantTimeEqual(password, httpAuthPassword.Get()) {
|
||||
return true
|
||||
}
|
||||
authBasicRequestErrors.Inc()
|
||||
@@ -712,3 +713,16 @@ func LogError(req *http.Request, errStr string) {
|
||||
remoteAddr := GetQuotedRemoteAddr(req)
|
||||
logger.Errorf("uri: %s, remote address: %q: %s", uri, remoteAddr, errStr)
|
||||
}
|
||||
|
||||
// constantTimeEqual compares two strings in constant-time.
|
||||
//
|
||||
// It returns true if they are equal, else it returns false.
|
||||
func constantTimeEqual(s1, s2 string) bool {
|
||||
a := []byte(s1)
|
||||
b := []byte(s2)
|
||||
// check length explicitly because ConstantTimeCompare doesn't spend time on comparing length
|
||||
if subtle.ConstantTimeEq(int32(len(a)), int32(len(b))) == 0 {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare(a, b) == 1
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user