diff --git a/internal/webhookguard/hmac.go b/internal/webhookguard/hmac.go index 1c36190c1..0233bb34a 100644 --- a/internal/webhookguard/hmac.go +++ b/internal/webhookguard/hmac.go @@ -9,16 +9,23 @@ import ( // VerifyHMAC checks a SHA-256 HMAC signature against body using secret, // accepting a signature with or without the "sha256=" prefix GitHub and -// similar senders use. An empty signature is never valid, even against an -// empty secret -- the absence of a signature must never be mistaken for one -// that happens to match. +// similar senders use. The digest is hex, which is case-insensitive by +// convention and by sender taste, so an uppercase signature verifies rather +// than masquerading as a wrong secret. An empty signature is never valid, even +// against an empty secret -- the absence of a signature must never be mistaken +// for one that happens to match. func VerifyHMAC(body []byte, signature, secret string) bool { if signature == "" { return false } - sigHex := strings.TrimPrefix(signature, "sha256=") + // Decode both sides to raw bytes and compare those: hex.DecodeString + // accepts either case, and comparing digests rather than their text + // keeps the comparison constant-time. + supplied, err := hex.DecodeString(strings.TrimPrefix(signature, "sha256=")) + if err != nil { + return false + } mac := hmac.New(sha256.New, []byte(secret)) mac.Write(body) - expected := hex.EncodeToString(mac.Sum(nil)) - return hmac.Equal([]byte(sigHex), []byte(expected)) + return hmac.Equal(supplied, mac.Sum(nil)) } diff --git a/internal/webhookguard/hmac_test.go b/internal/webhookguard/hmac_test.go index 85b32baa8..b8ef9d03d 100644 --- a/internal/webhookguard/hmac_test.go +++ b/internal/webhookguard/hmac_test.go @@ -4,6 +4,7 @@ import ( "crypto/hmac" "crypto/sha256" "encoding/hex" + "strings" "testing" "github.com/samcharles93/archie-core/internal/webhookguard" @@ -29,11 +30,17 @@ func TestVerifyHMAC(t *testing.T) { }{ {"valid signature", body, validSig, secret, true}, {"valid signature with sha256= prefix", body, "sha256=" + validSig, secret, true}, + {"uppercase hex signature", body, strings.ToUpper(validSig), secret, true}, + {"uppercase hex signature with sha256= prefix", body, "sha256=" + strings.ToUpper(validSig), secret, true}, {"wrong secret", body, validSig, "different-secret", false}, + {"uppercase hex signature for a different secret", body, strings.ToUpper(sign("different-secret", body)), secret, false}, {"tampered body", []byte(`{"issue":{"number":99}}`), validSig, secret, false}, {"empty signature", body, "", secret, false}, {"empty signature against empty secret", body, "", "", false}, + {"sha256= with no digest", body, "sha256=", secret, false}, {"garbage signature", body, "not-a-hex-signature", secret, false}, + {"odd-length hex", body, validSig[:len(validSig)-1], secret, false}, + {"truncated digest", body, validSig[:len(validSig)/2], secret, false}, } for _, test := range tests {