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 <alex.scheel@hashicorp.com>
This commit is contained in:
Alexander Scheel 2021-11-22 12:25:50 -05:00 committed by GitHub
parent 5236fe93aa
commit 3bad83f76f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 5 additions and 0 deletions

View File

@ -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)