fix(micromate): the opcode gate is an allowlist -- unknown SUBs refused; tables read-only
READ_SUBS catalogues every read; a SUB in neither table is refused, and allowed_writes may only name catalogued writes. Tables are MappingProxyType, _send checks the exact bytes it writes, check_transmit documents precedence. Tests cover unknown opcodes, concatenation smuggling and table immutability. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
a3e4e85dfd
commit
9c1c7cec76
4 files changed
+108
-7
No files matched your search
+49
-4
@@ -1,6 +1,10 @@
|
||||
"""Micromate (Series IV) opcode table: which SUBs write, and which collide.
|
||||
|
||||
One place, as the parity spec requires. `MicromateProtocol._send` consults it
|
||||
One place, as the parity spec requires. The gate is an ALLOWLIST: a SUB is
|
||||
transmitted only if it is a catalogued read (READ_SUBS) or a catalogued write
|
||||
this connection was explicitly allowed. An unknown SUB is refused -- clock-set
|
||||
and delete-all have Series-IV opcodes nobody has catalogued yet, and "unknown
|
||||
means read" is the wrong default. `MicromateProtocol._send` consults it
|
||||
on every outgoing frame, so a write cannot reach a unit by a path nobody
|
||||
thought about -- a scratch tool calling `protocol._send`, a hand-built frame, a
|
||||
method added later.
|
||||
@@ -12,9 +16,10 @@ of these values are also ACK SUBs of other commands (0x71 acks 0x8E, 0x72 acks
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, FrozenSet
|
||||
from types import MappingProxyType
|
||||
from typing import Dict, FrozenSet, Mapping
|
||||
|
||||
WRITE_SUBS: Dict[int, str] = {
|
||||
_WRITE_SUBS: Dict[int, str] = {
|
||||
0x47: "scheduler enable/disable",
|
||||
0x68: "setup push: preferences block (0x08)",
|
||||
0x71: "setup push: setup block (0x1A)",
|
||||
@@ -38,17 +43,53 @@ WRITE_SUBS: Dict[int, str] = {
|
||||
# Series IV, allowed or not: if a Series-III unit is at the address (a moved
|
||||
# modem, a stale IP), it would execute the other meaning. Lifting an entry is
|
||||
# a spec change, not a parameter.
|
||||
CROSS_SERIES_COLLISIONS: Dict[int, str] = {
|
||||
_CROSS_SERIES_COLLISIONS: Dict[int, str] = {
|
||||
0xA2: "CONFIRM ERASE on Series III -- erases every stored event; "
|
||||
"'end call-home' on Series IV",
|
||||
}
|
||||
|
||||
|
||||
_READ_SUBS: Dict[int, str] = {
|
||||
0x01: "device info",
|
||||
0x06: "storage range",
|
||||
0x08: "event index / preferences block",
|
||||
0x0A: "monitor log",
|
||||
0x0C: "event record",
|
||||
0x15: "serial number",
|
||||
0x1A: "setup block",
|
||||
0x1C: "monitor status",
|
||||
0x1E: "event first",
|
||||
0x1F: "event next",
|
||||
0x2C: "call-home config",
|
||||
0x2E: "trigger config",
|
||||
0x3F: "setup list first",
|
||||
0x40: "setup list next",
|
||||
0x41: "active setup",
|
||||
0x48: "file read next page",
|
||||
0x49: "state",
|
||||
0x5A: "bulk download",
|
||||
0x5B: "poll",
|
||||
0x93: "arm event",
|
||||
0x94: "file open for read",
|
||||
}
|
||||
|
||||
# Read-only views: a stray .pop() anywhere in the process cannot disable a gate.
|
||||
WRITE_SUBS: Mapping[int, str] = MappingProxyType(_WRITE_SUBS)
|
||||
CROSS_SERIES_COLLISIONS: Mapping[int, str] = MappingProxyType(_CROSS_SERIES_COLLISIONS)
|
||||
READ_SUBS: Mapping[int, str] = MappingProxyType(_READ_SUBS)
|
||||
|
||||
|
||||
class OpcodeRefused(RuntimeError):
|
||||
"""A frame was stopped before it reached the wire."""
|
||||
|
||||
|
||||
def check_transmit(sub: int, allowed_writes: FrozenSet[int] = frozenset()) -> None:
|
||||
"""Raise OpcodeRefused unless `sub` may go on the wire.
|
||||
|
||||
Precedence: (1) a cross-series collision is refused always; (2) a
|
||||
catalogued write is refused unless in `allowed_writes`; (3) a SUB in
|
||||
neither READ_SUBS nor `allowed_writes` is unknown and refused.
|
||||
"""
|
||||
if sub in CROSS_SERIES_COLLISIONS:
|
||||
raise OpcodeRefused(
|
||||
f"refused to transmit SUB 0x{sub:02X}: {CROSS_SERIES_COLLISIONS[sub]}")
|
||||
@@ -56,3 +97,7 @@ def check_transmit(sub: int, allowed_writes: FrozenSet[int] = frozenset()) -> No
|
||||
raise OpcodeRefused(
|
||||
f"refused to transmit SUB 0x{sub:02X} ({WRITE_SUBS[sub]}): writes are "
|
||||
"not enabled on this connection")
|
||||
if sub not in READ_SUBS and sub not in allowed_writes:
|
||||
raise OpcodeRefused(
|
||||
f"refused to transmit SUB 0x{sub:02X}: unknown opcode -- not in "
|
||||
"micromate.opcodes; catalogue it first")
|
||||
+10
-2
@@ -8,7 +8,8 @@ Scope: **reads only on the wire, enforced.** Every outgoing frame passes
|
||||
`micromate.opcodes.check_transmit()` in `_send`: a write opcode is refused
|
||||
unless this connection was constructed with it in `allowed_writes` (nothing in
|
||||
the codebase does so yet), and `0xA2` -- CONFIRM ERASE on Series III -- is
|
||||
refused always. No command has ever been originated against a unit by this
|
||||
refused always. The gate is an allowlist: a SUB not catalogued in
|
||||
`opcodes` (read or write) is refused as unknown. No command has ever been originated against a unit by this
|
||||
project; every write in ``docs/micromate_protocol_reference.md`` was performed
|
||||
by THOR while we recorded. The first thing this codebase ever sends to a
|
||||
customer's instrument should be a decision someone made on purpose, not a side
|
||||
@@ -47,7 +48,7 @@ from typing import Optional
|
||||
from minimateplus.transport import BaseTransport
|
||||
|
||||
from .framing import MicromateFrame, MicromateFrameParser, build_request, request_sub
|
||||
from .opcodes import check_transmit
|
||||
from .opcodes import WRITE_SUBS, check_transmit
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -271,6 +272,12 @@ class MicromateProtocol:
|
||||
self._recv_timeout = recv_timeout
|
||||
self._strict = strict_checksums
|
||||
self._allowed_writes = frozenset(allowed_writes)
|
||||
unknown = self._allowed_writes - set(WRITE_SUBS)
|
||||
if unknown:
|
||||
raise ValueError(
|
||||
"allowed_writes may only name catalogued write SUBs; not in "
|
||||
"micromate.opcodes.WRITE_SUBS: "
|
||||
+ ", ".join(f"0x{x:02X}" for x in sorted(unknown)))
|
||||
self._parser = MicromateFrameParser()
|
||||
self._pending: list[MicromateFrame] = []
|
||||
|
||||
@@ -520,6 +527,7 @@ class MicromateProtocol:
|
||||
def _send(self, frame: bytes) -> None:
|
||||
# The gate sees the bytes that are about to go out, not the caller's
|
||||
# intent: every transmit in this package passes through here.
|
||||
frame = bytes(frame) # checked bytes == written bytes
|
||||
check_transmit(request_sub(frame), self._allowed_writes)
|
||||
log.debug("TX %d bytes: %s", len(frame), frame.hex())
|
||||
self._transport.write(frame)
|
||||
|
||||
@@ -476,6 +476,7 @@ def _noncanonical_frames():
|
||||
"lone DLE before ETX": good[:-1] + b"\x10" + good[-1:],
|
||||
"double 41 02 prefix": good[:2] + good,
|
||||
"first byte not 0x10": good[:2] + bytes([0x11]) + good[3:],
|
||||
"two frames concatenated": build_request(0x5B, 0x0030) + good,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
import micromate.protocol as mm_proto # noqa: E402
|
||||
from micromate.framing import build_request # noqa: E402
|
||||
from micromate.opcodes import ( # noqa: E402
|
||||
CROSS_SERIES_COLLISIONS, WRITE_SUBS, OpcodeRefused, check_transmit,
|
||||
CROSS_SERIES_COLLISIONS, READ_SUBS, WRITE_SUBS, OpcodeRefused, check_transmit,
|
||||
)
|
||||
from test_micromate_protocol import frame, proto # noqa: E402
|
||||
|
||||
@@ -73,3 +73,50 @@ def test_a_frame_that_is_not_a_request_is_refused_not_sent():
|
||||
with pytest.raises(ValueError):
|
||||
p._send(b"\x41\x03")
|
||||
assert t.written == []
|
||||
|
||||
|
||||
def test_every_protocol_read_sub_is_in_the_read_table():
|
||||
consts = {k: v for k, v in vars(mm_proto).items() if k.startswith("SUB_")}
|
||||
assert len(consts) == 19
|
||||
assert set(consts.values()) <= set(READ_SUBS)
|
||||
assert {0x94, 0x48} <= set(READ_SUBS)
|
||||
|
||||
|
||||
def test_read_and_write_tables_are_disjoint():
|
||||
assert not (set(READ_SUBS) & set(WRITE_SUBS))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sub", [0xA3, 0x69, 0x74, 0x98, 0xEE])
|
||||
def test_an_unknown_opcode_is_refused_and_nothing_is_written(sub):
|
||||
p, t = proto([])
|
||||
with pytest.raises(OpcodeRefused, match="unknown opcode"):
|
||||
p._send(build_request(sub, 0))
|
||||
assert t.written == []
|
||||
|
||||
|
||||
def test_allowed_writes_may_only_name_catalogued_writes():
|
||||
for bad in (frozenset({0xEE}), frozenset({0x5B})):
|
||||
with pytest.raises(ValueError):
|
||||
proto([], allowed_writes=bad)
|
||||
|
||||
|
||||
def test_the_tables_are_read_only():
|
||||
for table in (WRITE_SUBS, READ_SUBS, CROSS_SERIES_COLLISIONS):
|
||||
with pytest.raises((TypeError, AttributeError)):
|
||||
table.pop(next(iter(table)))
|
||||
with pytest.raises(TypeError):
|
||||
table[0x00] = "x"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tail", [build_request(0x96, 0xFFFF), A2_WIRE])
|
||||
def test_a_read_followed_by_a_write_in_one_send_is_refused(tail):
|
||||
p, t = proto([], allowed_writes=frozenset({0x96}))
|
||||
with pytest.raises(ValueError):
|
||||
p._send(build_request(0x5B, 0x0030) + tail)
|
||||
assert t.written == []
|
||||
|
||||
|
||||
def test_a_bytearray_frame_is_checked_and_written_as_the_same_bytes():
|
||||
p, t = proto([])
|
||||
p._send(bytearray(build_request(0x5B, 0x0030)))
|
||||
assert t.written == [build_request(0x5B, 0x0030)]
|
||||
Reference in new issue
Block a user