From f1127b228edb6328fd2b2d217e15eae73f824081 Mon Sep 17 00:00:00 2001 From: Julio Lopez <1953782+julio-lopez@users.noreply.github.com> Date: Sun, 16 Nov 2025 21:36:18 -0800 Subject: [PATCH] chore(general): check bounds for memory allocation (#4995) --- internal/crypto/aesgcm.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/internal/crypto/aesgcm.go b/internal/crypto/aesgcm.go index 50e08c107..60e35144f 100644 --- a/internal/crypto/aesgcm.go +++ b/internal/crypto/aesgcm.go @@ -40,6 +40,8 @@ func initCrypto(masterKey, salt []byte) (cipher.AEAD, []byte, error) { return aead, authData, nil } +var errPlaintextTooLarge = errors.New("plaintext data is too large to be encrypted") + // EncryptAes256Gcm encrypts data with AES 256 GCM. func EncryptAes256Gcm(data, masterKey, salt []byte) ([]byte, error) { aead, authData, err := initCrypto(masterKey, salt) @@ -48,8 +50,14 @@ func EncryptAes256Gcm(data, masterKey, salt []byte) ([]byte, error) { } nonceLength := aead.NonceSize() - noncePlusContentLength := nonceLength + len(data) - cipherText := make([]byte, noncePlusContentLength+aead.Overhead()) + noncePlusOverhead := nonceLength + aead.Overhead() + + const maxInt = int(^uint(0) >> 1) + if len(data) > maxInt-noncePlusOverhead { + return nil, errPlaintextTooLarge + } + + cipherText := make([]byte, len(data)+noncePlusOverhead) // Store nonce at the beginning of ciphertext. nonce := cipherText[0:nonceLength] @@ -70,11 +78,12 @@ func DecryptAes256Gcm(data, masterKey, salt []byte) ([]byte, error) { return nil, errors.Wrap(err, "cannot initialize cipher") } - data = append([]byte(nil), data...) if len(data) < aead.NonceSize() { return nil, errors.New("invalid encrypted payload, too short") } + data = append([]byte(nil), data...) + nonce := data[0:aead.NonceSize()] payload := data[aead.NonceSize():]