From 889350dd8bb4d32a9ec2ac0a4cbe440e5308ebb4 Mon Sep 17 00:00:00 2001
From: Nicolas Werner <nicolas.werner@hotmail.de>
Date: Mon, 2 Dec 2019 17:56:05 +0100
Subject: [PATCH] Fix potential buffer overrun in AES_CTR functions

---
 lib/crypto/utils.cpp | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/lib/crypto/utils.cpp b/lib/crypto/utils.cpp
index 283383539..6dcb8fead 100644
--- a/lib/crypto/utils.cpp
+++ b/lib/crypto/utils.cpp
@@ -32,7 +32,8 @@ AES_CTR_256_Encrypt(const std::string plaintext, const BinaryBuf aes256Key, Bina
 
         int ciphertext_len;
 
-        BinaryBuf encrypted = create_buffer(plaintext.size());
+        // The ciphertext expand up to block size, which is 128 for AES256
+        BinaryBuf encrypted = create_buffer(plaintext.size() + 128);
 
         uint8_t *iv_data = iv.data();
         // need to set bit 63 to 0
@@ -67,6 +68,7 @@ AES_CTR_256_Encrypt(const std::string plaintext, const BinaryBuf aes256Key, Bina
         }
 
         ciphertext_len += len;
+        encrypted.resize(ciphertext_len);
 
         /* Clean up */
         EVP_CIPHER_CTX_free(ctx);
@@ -118,6 +120,7 @@ AES_CTR_256_Decrypt(const std::string ciphertext, const BinaryBuf aes256Key, Bin
                 //  handleErrors();
         }
         plaintext_len += len;
+        decrypted.resize(plaintext_len);
 
         /* Clean up */
         EVP_CIPHER_CTX_free(ctx);
-- 
GitLab