From 0826d043d5511c23878725742765da5687546723 Mon Sep 17 00:00:00 2001 From: "Alexander \"PapaTutuWawa" Date: Sun, 2 Oct 2022 17:03:39 +0200 Subject: [PATCH] feat: Attempt to detect already decrypted messages --- lib/src/errors.dart | 6 ++++++ lib/src/omemo/sessionmanager.dart | 6 ++++++ test/omemo_test.dart | 4 +++- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/src/errors.dart b/lib/src/errors.dart index 3a2cf70..a2672f4 100644 --- a/lib/src/errors.dart +++ b/lib/src/errors.dart @@ -40,3 +40,9 @@ class InvalidKeyExchangeException implements Exception { final int actualPn; String errMsg() => 'The pn attribute of the key exchange is invalid. Expected $expectedPn, got $actualPn'; } + +/// Triggered by the Session Manager when a message's sequence number is smaller than we +/// expect it to be. +class MessageAlreadyDecryptedException implements Exception { + String errMsg() => 'The message has already been decrypted'; +} diff --git a/lib/src/omemo/sessionmanager.dart b/lib/src/omemo/sessionmanager.dart index 3fbd160..cf06607 100644 --- a/lib/src/omemo/sessionmanager.dart +++ b/lib/src/omemo/sessionmanager.dart @@ -401,6 +401,12 @@ class OmemoSessionManager { final ratchet = (await _getRatchet(ratchetKey))!; oldRatchet ??= ratchet.clone(); + if (!rawKey.kex) { + if (message.n! < ratchet.nr - 1) { + throw MessageAlreadyDecryptedException(); + } + } + try { if (rawKey.kex) { keyAndHmac = await ratchet.ratchetDecrypt(message, authMessage.writeToBuffer()); diff --git a/test/omemo_test.dart b/test/omemo_test.dart index cdaf4fc..3858960 100644 --- a/test/omemo_test.dart +++ b/test/omemo_test.dart @@ -730,7 +730,9 @@ void main() { msg.encryptedKeys, ); expect(true, false); - } catch (_) { + } on MessageAlreadyDecryptedException catch (_) { + errorCounter++; + } on InvalidKeyExchangeException catch (_) { errorCounter++; } }