From 4a598632f432953f4dbfacf6cfed4f85a1c59c5a Mon Sep 17 00:00:00 2001
From: Nicolas Werner <nicolas.werner@hotmail.de>
Date: Mon, 4 Oct 2021 21:18:24 +0200
Subject: [PATCH] Fix crash when invlaid data is passed to the decryption
 functions

---
 include/mtxclient/crypto/client.hpp | 8 ++++++--
 lib/crypto/client.cpp               | 6 +++++-
 tests/e2ee.cpp                      | 4 ++++
 3 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/include/mtxclient/crypto/client.hpp b/include/mtxclient/crypto/client.hpp
index 8b4f24ae3..928a57a37 100644
--- a/include/mtxclient/crypto/client.hpp
+++ b/include/mtxclient/crypto/client.hpp
@@ -82,11 +82,15 @@ public:
     {}
 
     olm_exception(std::string func, OlmOutboundGroupSession *s)
-      : olm_exception(std::move(func), std::string(olm_outbound_group_session_last_error(s)))
+      : olm_exception(
+          std::move(func),
+          std::string(s ? olm_outbound_group_session_last_error(s) : "session == nullptr"))
     {}
 
     olm_exception(std::string func, OlmInboundGroupSession *s)
-      : olm_exception(std::move(func), std::string(olm_inbound_group_session_last_error(s)))
+      : olm_exception(
+          std::move(func),
+          std::string(s ? olm_inbound_group_session_last_error(s) : "session == nullptr"))
     {}
 
     olm_exception(std::string func, OlmSAS *s)
diff --git a/lib/crypto/client.cpp b/lib/crypto/client.cpp
index 62233def2..336d1b02e 100644
--- a/lib/crypto/client.cpp
+++ b/lib/crypto/client.cpp
@@ -252,12 +252,16 @@ OlmClient::decrypt_group_message(OlmInboundGroupSession *session,
                                  const std::string &message,
                                  uint32_t message_index)
 {
-    // TODO handle errors
+    if (!session)
+        throw olm_exception("decrypt_group_message", session);
+
     auto tmp_msg = create_buffer(message.size());
     std::copy(message.begin(), message.end(), tmp_msg.begin());
 
     auto plaintext_len =
       olm_group_decrypt_max_plaintext_length(session, tmp_msg.data(), tmp_msg.size());
+    if (plaintext_len == olm_error())
+        throw olm_exception("olm_group_decrypt_max_plaintext_length: invalid ciphertext", session);
     auto plaintext = create_buffer(plaintext_len);
 
     tmp_msg = create_buffer(message.size());
diff --git a/tests/e2ee.cpp b/tests/e2ee.cpp
index c314d399c..f8a4641f4 100644
--- a/tests/e2ee.cpp
+++ b/tests/e2ee.cpp
@@ -1185,6 +1185,10 @@ TEST(Encryption, PickleMegolmSessions)
               std::string((char *)restored_plaintext.data.data(), restored_plaintext.data.size()));
 
     EXPECT_EQ(std::string((char *)plaintext.data.data(), plaintext.data.size()), SECRET);
+
+    EXPECT_THROW(alice->decrypt_group_message(inbound_session.get(), ""), olm_exception);
+    EXPECT_THROW(alice->decrypt_group_message(nullptr, ""), olm_exception);
+    EXPECT_THROW(alice->decrypt_group_message(nullptr, ciphertext), olm_exception);
 }
 
 TEST(ExportSessions, InboundMegolmSessions)
-- 
GitLab