chore(general): check bounds for memory allocation (#4995)

This commit is contained in:
Julio Lopez
2025-11-16 21:36:18 -08:00
committed by GitHub
parent db4b89bc3d
commit f1127b228e

View File

@@ -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():]