From 29457de88641d25e8f125b8b56c9eb08260f549e Mon Sep 17 00:00:00 2001 From: Alexander Scheel Date: Mon, 22 Nov 2021 12:25:50 -0500 Subject: [PATCH] Prevent CWE-190/AllocationSizeOverflow in KDF (#13237) In the Counter-mode KBKDF implementation, due to the nature of the PRF (being implemented as a function rather than a hash.Hash instance), we need to allocate a buffer capable of storing the entire input to the PRF. This consists of the user-supplied context with 8 additional bytes (4 before and 4 after) of encoded integers. If the user supplies a maximally-sized context, the internally allocated buffer's size computation will overflow, resulting in a runtime panic. Guard against this condition. Signed-off-by: Alexander Scheel --- sdk/helper/kdf/kdf.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sdk/helper/kdf/kdf.go b/sdk/helper/kdf/kdf.go index 22e9f67bc4..d1c73b9f46 100644 --- a/sdk/helper/kdf/kdf.go +++ b/sdk/helper/kdf/kdf.go @@ -9,6 +9,7 @@ import ( "crypto/sha256" "encoding/binary" "fmt" + "math" ) // PRF is a pseudo-random function that takes a key or seed, @@ -37,6 +38,10 @@ func CounterMode(prf PRF, prfLen uint32, key []byte, context []byte, bits uint32 rounds++ } + if len(context) > math.MaxInt - 8 { + return nil, fmt.Errorf("too much context specified; would overflow: %d bytes", len(context)) + } + // Allocate and setup the input input := make([]byte, 4+len(context)+4) copy(input[4:], context)