diff --git a/towercore/guard.py b/towercore/guard.py index 2438a3b..269dbe0 100755 --- a/towercore/guard.py +++ b/towercore/guard.py @@ -5,6 +5,7 @@ import contextlib import os HEADER_SIZE = 16 +READ_OPCODE = 0x21 BULK_READ_OPCODE = 0x23 SUBSCRIBER_TAG = 0x0B BACKEND_HOST = os.environ.get("BACKEND_HOST", "towercore") @@ -12,8 +13,8 @@ BACKEND_PORT = int(os.environ.get("BACKEND_PORT", "7250")) LISTEN_PORT = int(os.environ.get("LISTEN_PORT", "7250")) -def tlv_tags(payload: bytes) -> set[int]: - tags: set[int] = set() +def tlv_tags(payload: bytes) -> list[int]: + tags: list[int] = [] offset = 0 while offset < len(payload): if len(payload) - offset < 4: @@ -23,7 +24,7 @@ def tlv_tags(payload: bytes) -> set[int]: offset += 4 if size > len(payload) - offset: raise ValueError("truncated TLV value") - tags.add(tag) + tags.append(tag) offset += size return tags @@ -34,7 +35,12 @@ def should_block(frame: bytes) -> bool: payload_size = int.from_bytes(frame[14:16], "little") if len(frame) != HEADER_SIZE + payload_size: raise ValueError("invalid frame length") - return frame[3] == BULK_READ_OPCODE and SUBSCRIBER_TAG in tlv_tags(frame[HEADER_SIZE:]) + tags = tlv_tags(frame[HEADER_SIZE:]) + opcode = frame[3] + return ( + opcode == BULK_READ_OPCODE and SUBSCRIBER_TAG in tags + or opcode == READ_OPCODE and tags.count(SUBSCRIBER_TAG) > 1 + ) async def client_frames(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: diff --git a/towercore/test_guard.py b/towercore/test_guard.py index ee9a291..b5298e9 100644 --- a/towercore/test_guard.py +++ b/towercore/test_guard.py @@ -19,6 +19,19 @@ class GuardTests(unittest.TestCase): request = frame(0x23, [(0x0B, b"victim01"), (0x0B, b"victim02")]) self.assertTrue(module.should_block(request)) + def test_blocks_duplicate_subscriber_override_on_read(self) -> None: + module = importlib.import_module("guard") + request = frame( + 0x21, + [ + (0x0B, b"owned-ue"), + (0x0B, b"victimue"), + (0x0D, b"\x01\0\0\0"), + (0x0E, b"\xff\xff\xff\xff"), + ], + ) + self.assertTrue(module.should_block(request)) + def test_allows_checker_bulk_read_by_message_ids(self) -> None: guard = importlib.util.find_spec("guard") self.assertIsNotNone(guard, "Towercore guard is not implemented")