mirror of
https://github.com/kopia/kopia.git
synced 2026-05-15 10:17:16 -04:00
chore(general): check bounds for memory allocation (#4995)
This commit is contained in:
@@ -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():]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user