Fix non-constant-time string != comparison

Signed-off-by: Bryan Frimin <bryan@getprobo.com>
This commit is contained in:
Bryan Frimin
2026-04-19 15:00:32 +02:00
parent 80a4d44e6d
commit 685e9d2e69
3 changed files with 6 additions and 3 deletions

View File

@@ -17,6 +17,7 @@ package securecookie
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
@@ -143,7 +144,7 @@ func Verify(signedValue, secret string) (string, error) {
return "", fmt.Errorf("cannot sign value: %w", err)
}
if signedValue != expectedSignedValue {
if subtle.ConstantTimeCompare([]byte(signedValue), []byte(expectedSignedValue)) != 1 {
return "", ErrInvalidSignature
}

View File

@@ -17,6 +17,7 @@ package securetoken
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
@@ -83,7 +84,7 @@ func Verify(signedValue, secret string) (string, error) {
return "", fmt.Errorf("cannot sign value: %w", err)
}
if signedValue != expectedSignedValue {
if subtle.ConstantTimeCompare([]byte(signedValue), []byte(expectedSignedValue)) != 1 {
return "", ErrInvalidSignature
}

View File

@@ -17,6 +17,7 @@ package statelesstoken
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"fmt"
@@ -133,7 +134,7 @@ func ValidateToken[T any](secret string, tokenType string, tokenString string) (
h.Write([]byte(encodedPayload))
expectedSignature := base64.RawURLEncoding.EncodeToString(h.Sum(nil))
if providedSignature != expectedSignature {
if subtle.ConstantTimeCompare([]byte(providedSignature), []byte(expectedSignature)) != 1 {
return nil, &ErrInvalidToken{message: "invalid token signature"}
}