From 5a0e0838232d7aa7c82b5a33d89458c01ccd4ffc Mon Sep 17 00:00:00 2001 From: Roland Shoemaker Date: Fri, 27 Mar 2026 08:40:08 -0700 Subject: crypto: disallow RegisterHash with hash value 0 We already prevent registering hash values larger than the number of hashes we actually have, but for some reason we don't prevent registering hash value 0, which is the sentinel value we typically use for "no hash". This change adds a check to prevent registering hash value 0. Fixes #60548 Change-Id: Ifd6edffb22b268ef282eae1b2ae4cc0ce748776c Reviewed-on: https://go-review.googlesource.com/c/go/+/760280 Reviewed-by: Filippo Valsorda LUCI-TryBot-Result: Go LUCI Auto-Submit: Roland Shoemaker Reviewed-by: Dmitri Shuralyov --- src/crypto/crypto.go | 2 +- src/crypto/crypto_test.go | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/crypto/crypto.go b/src/crypto/crypto.go index 0bf9ec834b..51275942a6 100644 --- a/src/crypto/crypto.go +++ b/src/crypto/crypto.go @@ -143,7 +143,7 @@ func (h Hash) Available() bool { // hash function. This is intended to be called from the init function in // packages that implement hash functions. func RegisterHash(h Hash, f func() hash.Hash) { - if h >= maxHash { + if h == 0 || h >= maxHash { panic("crypto: RegisterHash of unknown hash function") } hashes[h] = f diff --git a/src/crypto/crypto_test.go b/src/crypto/crypto_test.go index 66babcc2fb..9cd62dce19 100644 --- a/src/crypto/crypto_test.go +++ b/src/crypto/crypto_test.go @@ -9,9 +9,11 @@ import ( "crypto" "crypto/rand" "crypto/rsa" + "crypto/sha256" "crypto/x509" "encoding/pem" "errors" + "fmt" "internal/testenv" "io" "io/fs" @@ -141,3 +143,18 @@ func TestDisallowedAssemblyInstructions(t *testing.T) { t.Fatal(err) } } + +func TestRegisterHashLimits(t *testing.T) { + // maxHash is not exported, so we just use its value. If maxHash ever changes + // this will need to be updated. + for _, h := range []crypto.Hash{0, 20} { + t.Run(fmt.Sprintf("h=%d", h), func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("RegisterHash did not panic for %v", h) + } + }() + crypto.RegisterHash(h, sha256.New) + }) + } +} -- cgit v1.3-6-g1900