From 08e34ca89ed7cca38edc27c2fd0707680242a53b Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 3 Feb 2025 14:29:18 -0600 Subject: [PATCH] Handle late encryption error We should not see an encryption error after unless the data is corrupted on the wire, apparently this can happen fixes #1044 --- aioesphomeapi/_frame_helper/noise.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/aioesphomeapi/_frame_helper/noise.py b/aioesphomeapi/_frame_helper/noise.py index cedc8567..ffb14aaa 100644 --- a/aioesphomeapi/_frame_helper/noise.py +++ b/aioesphomeapi/_frame_helper/noise.py @@ -352,7 +352,18 @@ def _handle_frame(self, frame: bytes) -> None: """Handle an incoming frame.""" if TYPE_CHECKING: assert self._decrypt_cipher is not None, "Handshake should be complete" - msg = self._decrypt_cipher.decrypt(frame) + try: + msg = self._decrypt_cipher.decrypt(frame) + except InvalidTag: + # This shouldn't happen since we already checked the tag during handshake + # but it could happen if the server sends a bad frame see + # issue https://github.com/esphome/aioesphomeapi/issues/1044 + self._handle_error_and_close( + InvalidEncryptionKeyAPIError( + f"{self._log_name}: Encryption error", self._server_name + ) + ) + return # Message layout is # 2 bytes: message type # 2 bytes: message length