One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.4.1
Toby Kalkmandf10204f446e
diff --git a/SECURITY.md b/SECURITY.mdindex 640aaed..7ec0335 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -5,12 +5,19 @@ them matters. This is what it protects, what it does not, and how to report a pr## What the link protects-- **Every frame is encrypted and authenticated.** Both apps derive a key from the shared token with- HKDF-SHA256 and seal every frame with ChaCha20-Poly1305. A peer that cannot decrypt the first- frame does not hold the token, and the connection goes no further.+- **Every frame is encrypted and authenticated.** Each connection opens with both machines sending+ a fresh random prefix. Each direction of that connection then gets its own key, derived with+ HKDF-SHA256 from the shared token and both prefixes, and every frame is sealed with+ ChaCha20-Poly1305. A peer that cannot decrypt the first frame does not hold the token, and the+ connection goes no further.- **The token is never sent.** Not when connecting, and not when pairing.-- **Captured frames cannot be replayed.** Each frame carries a counter the receiver requires to- advance by one, and every connection starts from a fresh random nonce prefix.+- **Recorded traffic cannot be played back.** Within a connection, each frame carries a counter the+ receiver requires to advance by one, so a frame sent twice, dropped or reordered ends the+ connection. A whole recorded connection sent again as a new one fails too: the receiver's fresh+ prefix is part of the key, so frames recorded under an earlier one do not decrypt. Before 1.4.1+ the key was the same for every connection, and that whole-connection replay worked: someone on+ your network who recorded a session could send it again, and the keystrokes, clicks and clipboard+ in it would be repeated. Update both machines to 1.4.1 or later.- **Pairing is a six-digit code that lasts a minute and works once.** The two machines agree atoken over X25519, and each proves it knows the code with an HMAC keyed from it (scrypt, saltedper code). The code itself never crosses the network. The PC uses up its code on the first@@ -43,6 +50,9 @@ them matters. This is what it protects, what it does not, and how to report a prPairing again replaces it.- **Malware on either machine.** Anything that can read your keyboard or the settings file on onemachine already has what Beamer would protect.+- **A token that leaks later.** The keys come from the token and the prefixes, and the prefixes+ are sent in the clear, so anyone who records your traffic and later learns the token can decrypt+ the recording. Pairing again gives a new token.- **Traffic analysis.** Encryption hides what you type, not when. Someone watching the network cansee that the two machines are talking and the size and timing of frames. The protocol versionbyte at the start of each connection is sent in the clear.diff --git a/VERSION b/VERSIONindex 88c5fb8..347f583 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.4.0+1.4.1diff --git a/mac_app/protocol.py b/mac_app/protocol.pyindex dc86bad..3168324 100644--- a/mac_app/protocol.py+++ b/mac_app/protocol.py@@ -1,18 +1,26 @@"""Wire protocol shared by mac_app/bridge.py and win_app/receiver.py.-The link is encrypted and authenticated with ChaCha20-Poly1305 under a key both-sides derive from the shared token (HKDF-SHA256); the token itself never crosses-the wire, and a peer that cannot produce a valid tag does not hold it.+The link is encrypted and authenticated with ChaCha20-Poly1305; the shared+token never crosses the wire, and a peer that cannot produce a valid tag does+not hold it.A connection opens with one cleartext preamble each way -- WIRE_MAGIC, one-version byte, and that side's 8-byte nonce prefix -- so a version mismatch-produces a readable status instead of undecryptable garbage. Every frame after-that is a 4-byte big-endian length, then a 4-byte big-endian counter, then the-ciphertext with its tag; the length covers the counter and ciphertext. The nonce-is prefix + counter, each side counting its own frames from 1, and the receiver-rejects any counter that is not the next one, so a captured frame cannot be-replayed. A reconnect draws a new prefix, so a counter never repeats under one-key and prefix.+version byte, and that side's 8-byte nonce prefix, drawn fresh per connection+-- so a version mismatch produces a readable status instead of undecryptable+garbage. Each direction then has its own key, HKDF-SHA256 over the token with+the sender's prefix and the receiver's prefix in `info`, so nothing is sealed+until the peer's preamble is in. Every frame after that is a 4-byte big-endian+length, then a 4-byte big-endian counter, then the ciphertext with its tag; the+length covers the counter and ciphertext. The nonce is prefix + counter, each+side counting its own frames from 1, and the receiver rejects any counter that+is not the next one.++What that stops: a frame played again, dropped or reordered inside a+connection fails the counter; a whole recorded connection played into a new+one fails the tag, because the receiver's fresh prefix is part of the key its+peer had to seal under; a side's own frames reflected back fail the tag,+because the two directions' keys differ. What it does not give is forward+secrecy: anyone who later learns the token can read a recording made before."""import base64@@ -37,7 +45,9 @@ MAX_COUNTER = 0xFFFFFFFF# pairing and a mixed-version pair for no gain.WIRE_MAGIC = b"BEAMY"PREAMBLE_SIZE = len(WIRE_MAGIC) + 1 + NONCE_PREFIX_SIZE-PROTOCOL_VERSION = 4+# 5: per-connection keys bound to both prefixes (1.4.1). 4 keyed every connection alike from the+# token, so a recorded connection could be played into a new one whole.+PROTOCOL_VERSION = 5# Both ports sit below 49152 on purpose. Windows and macOS both hand out 49152-65535 as# ephemeral ports, and Windows lets WinNAT reserve whole 100-port blocks from that range that@@ -49,12 +59,8 @@ PAIRING_PORT = 24821# What DEFAULT_PORT used to be. A config still carrying it was never chosen by# anyone, so it is migrated rather than honoured; a port a user picked is left alone.LEGACY_DEFAULT_PORT = 51820-# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing-# pairing and a mixed-version pair for no gain.-KEY_SALT = b"beamy-key-v1"-# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing-# pairing and a mixed-version pair for no gain.-KEY_INFO = b"beamy-input-channel"+KEY_SALT = b"beamer-link-v5"+KEY_INFO = b"beamer-frames"CLIPBOARD_MAX_BYTES = 256 * 1024# The clipboard goes out ahead of the focus message on every switch, sealed as one frame and# buffered whole on both sides, so the image cap is a bound on how late the switch lands, not on@@ -135,27 +141,34 @@ class VersionMismatch(ProtocolError):self.peer_version = peer_version-def derive_key(token: str) -> bytes:- return HKDF(algorithm=hashes.SHA256(), length=32, salt=KEY_SALT, info=KEY_INFO).derive(- token.encode("utf-8")- )+def derive_key(token: str, sender_prefix: bytes, receiver_prefix: bytes) -> bytes:+ """The key for the frames one side seals and the other opens, on one+ connection only: both prefixes are drawn fresh per connection, and their+ order is the direction."""+ return HKDF(+ algorithm=hashes.SHA256(), length=32, salt=KEY_SALT, info=KEY_INFO + sender_prefix + receiver_prefix+ ).derive(token.encode("utf-8"))class SecureSession:"""One connection's cipher state for both directions. Build a new one perconnection: it draws a fresh nonce prefix and starts both counters at zero.+ Neither key exists until accept_preamble, so nothing can be sealed or+ opened before the peer's prefix is known.`send_lock` serialises sealing, and send_msg holds it across the write too,so counters are never reused and frames reach the wire in counter order;`open` is expected to run on a single reader thread per connection."""def __init__(self, token: str, prefix: bytes = None):- self._cipher = ChaCha20Poly1305(derive_key(token))+ self._token = tokenself.prefix = os.urandom(NONCE_PREFIX_SIZE) if prefix is None else bytes(prefix)if len(self.prefix) != NONCE_PREFIX_SIZE:raise ValueError("nonce prefix must be 8 bytes")self.send_lock = threading.RLock()self._send_counter = 0+ self._send_cipher = Noneself.peer_prefix = None+ self._recv_cipher = Noneself._recv_counter = 0def preamble(self) -> bytes:@@ -168,23 +181,30 @@ class SecureSession:if version != PROTOCOL_VERSION:raise VersionMismatch(version)peer_prefix = data[len(WIRE_MAGIC) + 1:]- # A reflected preamble would let our own frames be played back to us.+ if self.peer_prefix is not None:+ raise ProtocolError("second preamble on one connection")+ # Equal prefixes would make both directions one key.if peer_prefix == self.prefix:raise ProtocolError("peer echoed this side's nonce prefix")+ with self.send_lock:+ self._send_cipher = ChaCha20Poly1305(derive_key(self._token, self.prefix, peer_prefix))+ self._recv_cipher = ChaCha20Poly1305(derive_key(self._token, peer_prefix, self.prefix))self.peer_prefix = peer_prefixdef seal(self, msg: dict) -> bytes:body = json.dumps(msg).encode("utf-8")with self.send_lock:+ if self._send_cipher is None:+ raise ProtocolError("nothing is sealed before the peer's preamble")if self._send_counter >= MAX_COUNTER:raise ProtocolError("frame counter exhausted; reconnect")self._send_counter += 1counter = struct.pack(">I", self._send_counter)- ciphertext = self._cipher.encrypt(self.prefix + counter, body, None)+ ciphertext = self._send_cipher.encrypt(self.prefix + counter, body, None)return struct.pack(">I", COUNTER_SIZE + len(ciphertext)) + counter + ciphertextdef open(self, body: bytes) -> dict:- if self.peer_prefix is None:+ if self._recv_cipher is None:raise ProtocolError("frame received before the peer's preamble")if len(body) <= COUNTER_SIZE:raise ProtocolError("frame too short")@@ -192,7 +212,7 @@ class SecureSession:if counter != self._recv_counter + 1:raise ProtocolError("frame counter did not advance; replay rejected")try:- plain = self._cipher.decrypt(self.peer_prefix + body[:COUNTER_SIZE], body[COUNTER_SIZE:], None)+ plain = self._recv_cipher.decrypt(self.peer_prefix + body[:COUNTER_SIZE], body[COUNTER_SIZE:], None)except InvalidTag:raise AuthenticationError() from Noneself._recv_counter = counterdiff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.pyindex 650debf..3fa2084 100644--- a/mac_app/tests/test_bridge.py+++ b/mac_app/tests/test_bridge.py@@ -31,28 +31,36 @@ from gestures import DOCK_CONTROL_TYPE, MAGNIFY_TYPE, SWIPE_TYPEfrom input_injector_mac import INJECTED_MARK-def receiver_for(controller, token="synthetic-token"):- """A receiver-side session that can open what `controller` seals."""- peer = protocol.SecureSession(token)- peer.accept_preamble(controller.session.preamble())- return peer+def link(controller, sock=None, token="synthetic-token"):+ """Hand `controller` a FakeSocket as _connect_once would: a new session+ with the preambles exchanged, so both ends hold this connection's keys."""+ sock = sock or FakeSocket()+ sock.peer = protocol.SecureSession(token)+ controller.session = protocol.SecureSession(controller.cfg.auth_token)+ controller.session.accept_preamble(sock.peer.preamble())+ sock.peer.accept_preamble(controller.session.preamble())+ sock.mac_preamble = controller.session.preamble()+ controller.sock = sock+ return sockdef sent_messages(controller, sock):"""Open every frame `controller` sent over a FakeSocket, in order --- counters must advance, so a frame can only be read in sequence."""- peer = receiver_for(controller)- return [peer.open(payload[protocol.HEADER_SIZE:]) for payload in sock.sent]+ counters must advance, so a frame can only be read in sequence. A fresh+ opener with the receiver's prefix each call, so this can be asked twice."""+ opener = protocol.SecureSession(sock.peer._token, prefix=sock.peer.prefix)+ opener.accept_preamble(sock.mac_preamble)+ return [opener.open(payload[protocol.HEADER_SIZE:]) for payload in sock.sent if payload != sock.mac_preamble]def seed_receiver_reply(sock, *messages, token="synthetic-token"):- """Queue a receiver's preamble and sealed replies on a FakeSocket, as a- Windows receiver holding `token` would send them."""- peer = protocol.SecureSession(token)- sock.inbound.extend(peer.preamble())- for message in messages:- sock.inbound.extend(peer.seal(message))- return peer+ """Queue a receiver's preamble on a FakeSocket, and replies it seals once+ the Mac's preamble has gone out, as a Windows receiver holding `token`+ would send them: a reply's key needs both prefixes."""+ sock.peer = protocol.SecureSession(token)+ sock.inbound.extend(sock.peer.preamble())+ sock.pending.extend(messages)+ return sock.peerclass FakeQuartz:@@ -172,6 +180,9 @@ class FakeSocket:self.closed = Falseself.shutdown_called = Falseself.inbound = bytearray()+ self.peer = None+ self.mac_preamble = None+ self.pending = []def settimeout(self, value):self.timeout = value@@ -183,6 +194,13 @@ class FakeSocket:self.sent.append(payload)def recv(self, size):+ if self.peer is not None and self.peer.peer_prefix is None and self.sent:+ self.mac_preamble = self.sent[0]+ self.peer.accept_preamble(self.mac_preamble)+ if self.pending and self.mac_preamble is not None:+ for message in self.pending:+ self.inbound.extend(self.peer.seal(message))+ self.pending = []if not self.inbound:raise TimeoutError("no synthetic reply")chunk = bytes(self.inbound[:size])@@ -253,6 +271,7 @@ class FrameDecoderTests(unittest.TestCase):self.windows = protocol.SecureSession("synthetic-token")self.mac = protocol.SecureSession("synthetic-token")self.mac.accept_preamble(self.windows.preamble())+ self.windows.accept_preamble(self.mac.preamble())self.decoder = FrameDecoder(self.mac)def test_decodes_fragmented_frames(self):@@ -276,6 +295,7 @@ class FrameDecoderTests(unittest.TestCase):def test_wrong_token_fails_authentication(self):stranger = protocol.SecureSession("another-token", prefix=self.windows.prefix)+ stranger.accept_preamble(self.mac.preamble())with self.assertRaises(protocol.AuthenticationError):self.decoder.feed(stranger.seal(protocol.ack_msg(1)))@@ -589,7 +609,7 @@ class ControllerTests(unittest.TestCase):def test_double_tap_right_option_only_flips_redirect_flag(self):sock = FakeSocket()- self.controller.sock = sock+ link(self.controller, sock)down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D,"flags": FakeQuartz.kCGEventFlagMaskAlternate,@@ -629,7 +649,7 @@ class ControllerTests(unittest.TestCase):alerts = []self.controller.on_user_alert = lambda title, message: alerts.append((title, message))sock = FakeSocket()- self.controller.sock = sock+ link(self.controller, sock)self.controller.redirecting = Trueself.controller.connected_at = 10.0self.controller.last_ack_at = 10.0@@ -648,7 +668,7 @@ class ControllerTests(unittest.TestCase):# double-tap would "succeed" into a void. It must now be detected and# torn down the same way regardless of redirect state.sock = FakeSocket()- self.controller.sock = sock+ link(self.controller, sock)self.controller.redirecting = Falseself.controller.connected_at = 10.0self.controller.last_ack_at = 10.0@@ -661,7 +681,7 @@ class ControllerTests(unittest.TestCase):def test_watchdog_sends_idle_ping_after_a_second_of_silence(self):sock = FakeSocket()- self.controller.sock = sock+ link(self.controller, sock)self.controller.connected_at = 10.0self.controller.last_ack_at = 10.0self.controller.last_send_at = 10.0@@ -673,7 +693,7 @@ class ControllerTests(unittest.TestCase):def test_watchdog_suppresses_idle_ping_while_traffic_flows(self):sock = FakeSocket()- self.controller.sock = sock+ link(self.controller, sock)self.controller.connected_at = 10.0self.controller.last_ack_at = 10.0self.controller.last_send_at = 11.5@@ -689,7 +709,7 @@ class ControllerTests(unittest.TestCase):# while Windows is already driving this Mac corrupts the pair. This# asserts the invariant, which the current code violates.sock = FakeSocket()- self.controller.sock = sock+ link(self.controller, sock)self.controller.receiving = Trueself.controller.set_redirecting(True)self.assertFalse(@@ -702,7 +722,7 @@ class ControllerTests(unittest.TestCase):# the edge never fired, and the menu's switch only said Windows was# already driving. Switching now sends the PC's input home instead.sent_home = []- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.receiving = Trueself.controller.send_peer_home = lambda: sent_home.append(True) or Trueself.assertTrue(self.controller.set_redirecting(True))@@ -710,7 +730,7 @@ class ControllerTests(unittest.TestCase):self.assertFalse(self.controller.redirecting)def test_switching_while_receiving_with_the_pc_unreachable_is_refused(self):- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.receiving = Trueself.controller.send_peer_home = lambda: Falseself.assertFalse(self.controller.set_redirecting(True))@@ -718,7 +738,7 @@ class ControllerTests(unittest.TestCase):def test_this_macs_trigger_sends_the_pcs_input_home_while_receiving(self):sent_home = []- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.receiving = Trueself.controller.send_peer_home = lambda: sent_home.append(True) or Truedown = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}@@ -734,7 +754,7 @@ class ControllerTests(unittest.TestCase):def test_the_pcs_injected_trigger_is_not_this_macs_while_receiving(self):sent_home = []- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.receiving = Trueself.controller.send_peer_home = lambda: sent_home.append(True) or Truedown = {@@ -748,7 +768,7 @@ class ControllerTests(unittest.TestCase):self.assertEqual(sent_home, [])def test_sending_to_windows_switched_off_refuses_the_switch(self):- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.cfg.send_to_windows = Falseself.assertFalse(self.controller.set_redirecting(True))self.assertFalse(self.controller.redirecting)@@ -756,7 +776,7 @@ class ControllerTests(unittest.TestCase):def test_sending_to_windows_switched_off_still_sends_the_pcs_input_home(self):# Each switch covers one direction: the PC's input on this Mac still goes home.sent_home = []- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.cfg.send_to_windows = Falseself.controller.receiving = Trueself.controller.send_peer_home = lambda: sent_home.append(True) or True@@ -787,7 +807,7 @@ class ControllerTests(unittest.TestCase):# key-up went missing (e.g. a tap restart never delivered it), which# silently killed the double-tap trigger on the very next press.sock = FakeSocket()- self.controller.sock = sock+ link(self.controller, sock)down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D,"flags": FakeQuartz.kCGEventFlagMaskAlternate | 0x0040,@@ -849,7 +869,7 @@ class ControllerTests(unittest.TestCase):def test_an_ack_without_an_object_body_drops_the_connection_not_the_reader(self):sock = FakeSocket()- self.controller.sock = sock+ link(self.controller, sock)with self.assertRaises(protocol.ProtocolError):self.controller._handle_inbound({"type": protocol.MSG_ACK, "data": None})@@ -861,7 +881,7 @@ class ControllerTests(unittest.TestCase):lambda: self.controller._event_tap_callback(None, FakeQuartz.kCGEventTapDisabledByTimeout, {}, None),):with self.subTest(way_home=way_home):- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.event_tap = object()self.controller.set_redirecting(True)self.controller._drain_outbound()@@ -881,7 +901,7 @@ class ControllerTests(unittest.TestCase):lambda: self.controller._thread_entry("synthetic", lambda: (_ for _ in ()).throw(RuntimeError())),):with self.subTest(way_home=way_home):- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.set_redirecting(True)FakeQuartz.reset_cursor_spies()way_home()@@ -911,7 +931,7 @@ class ControllerTests(unittest.TestCase):# The hello carries the way home, which is how Windows knows which of# its own edges leads back here before this Mac has ever crossed.self.assertEqual(- sent_messages(controller, types.SimpleNamespace(sent=sock.sent[1:])),+ sent_messages(controller, sock),[protocol.hello_msg(return_edge="left", resistance_px=120)],)self.assertNotIn(b"synthetic-token", b"".join(sock.sent))@@ -1074,7 +1094,7 @@ class ControllerTests(unittest.TestCase):def test_set_redirecting_off_resets_mouse_accumulators(self):sock = FakeSocket()- self.controller.sock = sock+ link(self.controller, sock)self.controller.redirecting = Trueself.controller.translator._move_accum_x = 0.4self.controller.translator._move_accum_y = -0.4@@ -1100,7 +1120,7 @@ class ClipboardSyncTests(unittest.TestCase):clock=self.clock,)self.sock = FakeSocket()- self.controller.sock = self.sock+ link(self.controller, self.sock)def _drain_outbound(self):while not self.controller.outbound.empty():@@ -1238,7 +1258,7 @@ class CursorPinningTests(unittest.TestCase):clock=self.clock,)self.sock = FakeSocket()- self.controller.sock = self.sock+ link(self.controller, self.sock)def test_pin_captured_and_association_disabled_at_redirect_start(self):self.assertTrue(self.controller.set_redirecting(True))@@ -1296,7 +1316,7 @@ class CursorPinningTests(unittest.TestCase):controller = KVMController(make_config(), logger=logger, quartz=FakeQuartz, clock=self.clock,)- controller.sock = FakeSocket()+ link(controller)with self.assertLogs(logger, level="INFO") as captured:controller.set_redirecting(True)controller.set_redirecting(False)@@ -1334,7 +1354,7 @@ class CursorPinningTests(unittest.TestCase):controller = KVMController(make_config(), logger=logger, quartz=ErroringQuartz, clock=self.clock,)- controller.sock = FakeSocket()+ link(controller)controller.set_redirecting(True)move_event = {ErroringQuartz.kCGMouseEventDeltaX: 4,@@ -1365,7 +1385,7 @@ class OverlayGestureTests(unittest.TestCase):clock=self.clock,)self.sock = FakeSocket()- self.controller.sock = self.sock+ link(self.controller, self.sock)def test_overlay_gesture_translated_and_enqueued_while_redirecting(self):self.controller.redirecting = True@@ -1536,7 +1556,7 @@ class GestureWiringTests(unittest.TestCase):controller = self._controller(lambda event: FakeGestureEvent(deltaX=1.0))controller.redirecting = Truesock = FakeSocket()- controller.sock = sock+ link(controller, sock)returned = controller._event_tap_callback(None, SWIPE_TYPE, object(), None)self.assertIsNone(returned)drained = []@@ -1757,7 +1777,7 @@ class CrossingWiringTests(unittest.TestCase):clock=self.clock,desktop_bounds=lambda: self.BOUNDS,)- controller.sock = FakeSocket()+ link(controller)controller.on_crossing = lambda kind, step: self.feedback.append((kind, step))return controller@@ -2088,7 +2108,7 @@ class RoundTripTests(unittest.TestCase):self.controller = KVMController(crossing_config(), logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock)- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.redirecting = Truedef _send(self):@@ -2142,7 +2162,7 @@ class RoundTripTests(unittest.TestCase):def test_nothing_is_shown_when_the_link_is_down(self):self._ack(self._send(), 0.02)self.controller._connection_failed("Windows stopped responding")- self.controller.sock = FakeSocket()+ link(self.controller)self.controller.redirecting = Trueself.assertIsNone(self.controller.round_trip_ms)diff --git a/mac_app/tests/test_hello_limit.py b/mac_app/tests/test_hello_limit.pyindex ec0bb6e..b330a57 100644--- a/mac_app/tests/test_hello_limit.py+++ b/mac_app/tests/test_hello_limit.py@@ -30,6 +30,7 @@ class HelloFrameLimitTests(unittest.TestCase):theirs = protocol.SecureSession("t")mine = protocol.SecureSession("t")mine.accept_preamble(theirs.preamble())+ theirs.accept_preamble(mine.preamble())frame = theirs.seal(protocol.hello_msg(return_edge="left", resistance_px=120))self.assertLess(len(frame) - protocol.HEADER_SIZE, protocol.HELLO_MAX_BYTES)sender.sendall(frame)diff --git a/mac_app/tests/test_replay.py b/mac_app/tests/test_replay.pynew file mode 100644index 0000000..a0c1a97--- /dev/null+++ b/mac_app/tests/test_replay.py@@ -0,0 +1,149 @@+"""Whole-connection replay, over both links with the real link code at each end.++An attacker on the LAN who recorded one connection opens a new one and sends the recorded+initiator bytes in order: the preamble, the hello and every input frame after it. Per-frame+replay inside a connection was always refused; this is the whole stream again, into a fresh+responder, and it must fail the tag rather than inject what was recorded."""++import socket+import time+import unittest++import protocol+from two_machines import Duo, wait_for+++class Recording:+ """A connected socket that keeps a copy of every byte each way."""++ def __init__(self, sock):+ self._sock = sock+ self.sent = bytearray()+ self.received = bytearray()++ def sendall(self, data, *args):+ self.sent += data+ return self._sock.sendall(data, *args)++ def send(self, data, *args):+ count = self._sock.send(data, *args)+ self.sent += data[:count]+ return count++ def recv(self, size, *args):+ data = self._sock.recv(size, *args)+ self.received += data+ return data++ def __getattr__(self, name):+ return getattr(self._sock, name)+++def recording_factory(recordings):+ def connect(address, timeout=None, *args, **kwargs):+ recording = Recording(socket.create_connection(address, timeout))+ recordings.append(recording)+ return recording++ return connect+++def replay(port, data):+ """Send `data` as a fresh connection and return every byte the responder sent back before it+ closed."""+ with socket.create_connection(("127.0.0.1", port), timeout=3.0) as attacker:+ attacker.sendall(bytes(data))+ attacker.shutdown(socket.SHUT_WR)+ reply = bytearray()+ while True:+ try:+ chunk = attacker.recv(65536)+ except (ConnectionResetError, socket.timeout):+ break+ if not chunk:+ break+ reply += chunk+ return bytes(reply)+++def settle():+ # Anything a replayed frame would inject lands on the receiver's session thread; the reply+ # above has already been read to the close, so this only covers the last callback.+ time.sleep(0.2)+++class WholeConnectionReplayTests(unittest.TestCase):+ def test_the_macs_recorded_link_replayed_into_the_pc_is_refused(self):+ duo = Duo(crossing={"resistance_px": 40}).listen()+ self.addCleanup(duo.close)+ recordings = []+ duo.mac.socket_factory = recording_factory(recordings)+ duo.link_mac_to_pc()+ self.assertTrue(duo.mac_push(1727, 500, 30), "the push never crossed")+ self.assertTrue(wait_for(lambda: duo.pc_desktop.cursor[0] == 0), "the switch never placed the PC's pointer")+ self.assertTrue(duo.mac.send_arrangement("left", 500))+ self.assertTrue(wait_for(lambda: duo.pc_arrangements), "the arrangement never arrived")+ duo.mac.stop()+ duo.pc_desktop.cursor = (900, 500)+ arrangements = len(duo.pc_arrangements)+ self.assertEqual(len(recordings), 1)++ reply = replay(duo.pc_port, recordings[0].sent)+ settle()++ self.assertEqual(duo.pc_desktop.cursor, (900, 500), "a replayed switch moved the PC's pointer")+ self.assertEqual(len(duo.pc_arrangements), arrangements, "a replayed arrangement was applied")+ self.assertEqual(len(reply), protocol.PREAMBLE_SIZE, "the PC answered past its preamble")++ def test_the_pcs_recorded_link_replayed_into_the_mac_is_refused(self):+ duo = Duo().listen()+ self.addCleanup(duo.close)+ recordings = []+ duo.pc._socket_factory = recording_factory(recordings)+ duo.link_pc_to_mac()+ self.assertTrue(duo.pc.send_arrangement("top", 600))+ self.assertTrue(wait_for(lambda: duo.mac_arrangements), "the arrangement never arrived")+ duo.pc.stop()+ arrangements = len(duo.mac_arrangements)+ self.assertEqual(len(recordings), 1)++ reply = replay(duo.mac_port, recordings[0].sent)+ settle()++ self.assertEqual(len(duo.mac_arrangements), arrangements, "a replayed arrangement was applied")+ self.assertEqual(len(reply), protocol.PREAMBLE_SIZE, "the Mac answered past its preamble")+++class SessionKeyTests(unittest.TestCase):+ def pair(self):+ a, b = protocol.SecureSession("t"), protocol.SecureSession("t")+ a.accept_preamble(b.preamble())+ b.accept_preamble(a.preamble())+ return a, b++ def test_nothing_is_sealed_before_the_peers_preamble(self):+ with self.assertRaises(protocol.ProtocolError):+ protocol.SecureSession("t").seal(protocol.ping_msg())++ def test_a_sides_own_frames_reflected_back_fail_the_tag(self):+ a, b = self.pair()+ with self.assertRaises(protocol.AuthenticationError):+ a.open(a.seal(protocol.ping_msg())[protocol.HEADER_SIZE:])++ def test_a_frame_from_another_connection_fails_the_tag(self):+ a, b = self.pair()+ frame = a.seal(protocol.ping_msg())+ fresh = protocol.SecureSession("t")+ fresh.accept_preamble(a.preamble())+ with self.assertRaises(protocol.AuthenticationError):+ fresh.open(frame[protocol.HEADER_SIZE:])+ self.assertEqual(b.open(frame[protocol.HEADER_SIZE:]), protocol.ping_msg())++ def test_a_second_preamble_is_refused(self):+ a, b = self.pair()+ with self.assertRaises(protocol.ProtocolError):+ a.accept_preamble(protocol.SecureSession("t").preamble())+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_update_config_redirecting.py b/mac_app/tests/test_update_config_redirecting.pyindex 7c66d19..4be45cd 100644--- a/mac_app/tests/test_update_config_redirecting.py+++ b/mac_app/tests/test_update_config_redirecting.py@@ -1,7 +1,7 @@import unittestfrom bridge import KVMController-from test_bridge import FakeClock, FakeQuartz, FakeSocket, crossing_config, quiet_logger+from test_bridge import FakeClock, FakeQuartz, FakeSocket, crossing_config, link, quiet_loggerclass UpdateConfigWhileRedirectingTests(unittest.TestCase):@@ -18,7 +18,7 @@ class UpdateConfigWhileRedirectingTests(unittest.TestCase):clock=FakeClock(),desktop_bounds=lambda: (0.0, 0.0, 1728.0, 1117.0),)- self.controller.sock = FakeSocket()+ link(self.controller)def test_update_config_while_redirecting_restores_cursor_association(self):self.controller.set_redirecting(True)diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pyindex 450fcc9..28c7e4d 100644--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@ -1766,6 +1766,12 @@ class WindowsApplication(QWidget):self._run_firewall(firewall_win.status, "Checking…")def _firewall_action(self) -> None:+ # Only the built exe changes the firewall, by the button or on its own. From source the+ # executable is python.exe, and repair() replaces Beamer's rules by name, so a test run on+ # the PC took the installed Beamer's rules with it and cut the Mac's link (29-09-2026).+ if not getattr(sys, "frozen", False):+ LOGGER.info("Running from source; the firewall is left as it is")+ returnadvice = self._firewall_adviceif advice is None or advice.action is None:return@@ -2005,10 +2011,10 @@ class WindowsApplication(QWidget):def start(self) -> None:self.update_checker.start()- if firewall_win.is_elevated():+ if getattr(sys, "frozen", False) and firewall_win.is_elevated():# Beamer's own rules before any socket opens: a listener Windows has no rule for makes# it ask, and a click on Allow there writes rules for every network, public ones too,- # where Beamer's are for private networks only.+ # where Beamer's are for private networks only. Not from source: see _firewall_action.threading.Thread(target=self._rules_then_listen, name="Beamer-firewall-first", daemon=True).start()else:self._listen()diff --git a/win_app/protocol.py b/win_app/protocol.pyindex dc86bad..3168324 100644--- a/win_app/protocol.py+++ b/win_app/protocol.py@@ -1,18 +1,26 @@"""Wire protocol shared by mac_app/bridge.py and win_app/receiver.py.-The link is encrypted and authenticated with ChaCha20-Poly1305 under a key both-sides derive from the shared token (HKDF-SHA256); the token itself never crosses-the wire, and a peer that cannot produce a valid tag does not hold it.+The link is encrypted and authenticated with ChaCha20-Poly1305; the shared+token never crosses the wire, and a peer that cannot produce a valid tag does+not hold it.A connection opens with one cleartext preamble each way -- WIRE_MAGIC, one-version byte, and that side's 8-byte nonce prefix -- so a version mismatch-produces a readable status instead of undecryptable garbage. Every frame after-that is a 4-byte big-endian length, then a 4-byte big-endian counter, then the-ciphertext with its tag; the length covers the counter and ciphertext. The nonce-is prefix + counter, each side counting its own frames from 1, and the receiver-rejects any counter that is not the next one, so a captured frame cannot be-replayed. A reconnect draws a new prefix, so a counter never repeats under one-key and prefix.+version byte, and that side's 8-byte nonce prefix, drawn fresh per connection+-- so a version mismatch produces a readable status instead of undecryptable+garbage. Each direction then has its own key, HKDF-SHA256 over the token with+the sender's prefix and the receiver's prefix in `info`, so nothing is sealed+until the peer's preamble is in. Every frame after that is a 4-byte big-endian+length, then a 4-byte big-endian counter, then the ciphertext with its tag; the+length covers the counter and ciphertext. The nonce is prefix + counter, each+side counting its own frames from 1, and the receiver rejects any counter that+is not the next one.++What that stops: a frame played again, dropped or reordered inside a+connection fails the counter; a whole recorded connection played into a new+one fails the tag, because the receiver's fresh prefix is part of the key its+peer had to seal under; a side's own frames reflected back fail the tag,+because the two directions' keys differ. What it does not give is forward+secrecy: anyone who later learns the token can read a recording made before."""import base64@@ -37,7 +45,9 @@ MAX_COUNTER = 0xFFFFFFFF# pairing and a mixed-version pair for no gain.WIRE_MAGIC = b"BEAMY"PREAMBLE_SIZE = len(WIRE_MAGIC) + 1 + NONCE_PREFIX_SIZE-PROTOCOL_VERSION = 4+# 5: per-connection keys bound to both prefixes (1.4.1). 4 keyed every connection alike from the+# token, so a recorded connection could be played into a new one whole.+PROTOCOL_VERSION = 5# Both ports sit below 49152 on purpose. Windows and macOS both hand out 49152-65535 as# ephemeral ports, and Windows lets WinNAT reserve whole 100-port blocks from that range that@@ -49,12 +59,8 @@ PAIRING_PORT = 24821# What DEFAULT_PORT used to be. A config still carrying it was never chosen by# anyone, so it is migrated rather than honoured; a port a user picked is left alone.LEGACY_DEFAULT_PORT = 51820-# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing-# pairing and a mixed-version pair for no gain.-KEY_SALT = b"beamy-key-v1"-# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing-# pairing and a mixed-version pair for no gain.-KEY_INFO = b"beamy-input-channel"+KEY_SALT = b"beamer-link-v5"+KEY_INFO = b"beamer-frames"CLIPBOARD_MAX_BYTES = 256 * 1024# The clipboard goes out ahead of the focus message on every switch, sealed as one frame and# buffered whole on both sides, so the image cap is a bound on how late the switch lands, not on@@ -135,27 +141,34 @@ class VersionMismatch(ProtocolError):self.peer_version = peer_version-def derive_key(token: str) -> bytes:- return HKDF(algorithm=hashes.SHA256(), length=32, salt=KEY_SALT, info=KEY_INFO).derive(- token.encode("utf-8")- )+def derive_key(token: str, sender_prefix: bytes, receiver_prefix: bytes) -> bytes:+ """The key for the frames one side seals and the other opens, on one+ connection only: both prefixes are drawn fresh per connection, and their+ order is the direction."""+ return HKDF(+ algorithm=hashes.SHA256(), length=32, salt=KEY_SALT, info=KEY_INFO + sender_prefix + receiver_prefix+ ).derive(token.encode("utf-8"))class SecureSession:"""One connection's cipher state for both directions. Build a new one perconnection: it draws a fresh nonce prefix and starts both counters at zero.+ Neither key exists until accept_preamble, so nothing can be sealed or+ opened before the peer's prefix is known.`send_lock` serialises sealing, and send_msg holds it across the write too,so counters are never reused and frames reach the wire in counter order;`open` is expected to run on a single reader thread per connection."""def __init__(self, token: str, prefix: bytes = None):- self._cipher = ChaCha20Poly1305(derive_key(token))+ self._token = tokenself.prefix = os.urandom(NONCE_PREFIX_SIZE) if prefix is None else bytes(prefix)if len(self.prefix) != NONCE_PREFIX_SIZE:raise ValueError("nonce prefix must be 8 bytes")self.send_lock = threading.RLock()self._send_counter = 0+ self._send_cipher = Noneself.peer_prefix = None+ self._recv_cipher = Noneself._recv_counter = 0def preamble(self) -> bytes:@@ -168,23 +181,30 @@ class SecureSession:if version != PROTOCOL_VERSION:raise VersionMismatch(version)peer_prefix = data[len(WIRE_MAGIC) + 1:]- # A reflected preamble would let our own frames be played back to us.+ if self.peer_prefix is not None:+ raise ProtocolError("second preamble on one connection")+ # Equal prefixes would make both directions one key.if peer_prefix == self.prefix:raise ProtocolError("peer echoed this side's nonce prefix")+ with self.send_lock:+ self._send_cipher = ChaCha20Poly1305(derive_key(self._token, self.prefix, peer_prefix))+ self._recv_cipher = ChaCha20Poly1305(derive_key(self._token, peer_prefix, self.prefix))self.peer_prefix = peer_prefixdef seal(self, msg: dict) -> bytes:body = json.dumps(msg).encode("utf-8")with self.send_lock:+ if self._send_cipher is None:+ raise ProtocolError("nothing is sealed before the peer's preamble")if self._send_counter >= MAX_COUNTER:raise ProtocolError("frame counter exhausted; reconnect")self._send_counter += 1counter = struct.pack(">I", self._send_counter)- ciphertext = self._cipher.encrypt(self.prefix + counter, body, None)+ ciphertext = self._send_cipher.encrypt(self.prefix + counter, body, None)return struct.pack(">I", COUNTER_SIZE + len(ciphertext)) + counter + ciphertextdef open(self, body: bytes) -> dict:- if self.peer_prefix is None:+ if self._recv_cipher is None:raise ProtocolError("frame received before the peer's preamble")if len(body) <= COUNTER_SIZE:raise ProtocolError("frame too short")@@ -192,7 +212,7 @@ class SecureSession:if counter != self._recv_counter + 1:raise ProtocolError("frame counter did not advance; replay rejected")try:- plain = self._cipher.decrypt(self.peer_prefix + body[:COUNTER_SIZE], body[COUNTER_SIZE:], None)+ plain = self._recv_cipher.decrypt(self.peer_prefix + body[:COUNTER_SIZE], body[COUNTER_SIZE:], None)except InvalidTag:raise AuthenticationError() from Noneself._recv_counter = counterdiff --git a/win_app/tests/fakes.py b/win_app/tests/fakes.pyindex 1cc0e2c..6b477f9 100644--- a/win_app/tests/fakes.py+++ b/win_app/tests/fakes.py@@ -85,7 +85,7 @@ class FakeDesktop:class SecureClient:- """The Mac's half of a v4 connection, driven from a test over a real+ """The Mac's half of a connection, driven from a test over a realsocket: sends its preamble at once and reads the receiver's on first use,so it can be built before the session thread that answers it has started.Frames are sealed and opened with the real cipher, never mocked away."""@@ -95,12 +95,17 @@ class SecureClient:self.session = protocol.SecureSession(token)sock.sendall(self.session.preamble())+ def _preamble(self):+ # Both keys need the receiver's prefix, so neither side of a test can seal or open without it.+ if self.session.peer_prefix is None:+ protocol.recv_preamble(self.sock, self.session)+def send(self, message):+ self._preamble()protocol.send_msg(self.sock, self.session, message)def recv(self):- if self.session.peer_prefix is None:- protocol.recv_preamble(self.sock, self.session)+ self._preamble()return protocol.recv_msg(self.sock, self.session)def settimeout(self, value):diff --git a/win_app/tests/test_clipboard_win.py b/win_app/tests/test_clipboard_win.pyindex 91ea2a4..9f2643d 100644--- a/win_app/tests/test_clipboard_win.py+++ b/win_app/tests/test_clipboard_win.py@@ -113,6 +113,7 @@ class ClipboardMessageTests(unittest.TestCase):sender = protocol.SecureSession("shared-token")receiver = protocol.SecureSession("shared-token")receiver.accept_preamble(sender.preamble())+ sender.accept_preamble(receiver.preamble())frame = sender.seal(protocol.clipboard_msg("shot.png", PNG))message = receiver.open(frame[protocol.HEADER_SIZE:])self.assertEqual(message["data"]["text"], "shot.png")diff --git a/win_app/tests/test_firewall_first.py b/win_app/tests/test_firewall_first.pyindex ade0fe0..eea90cf 100644--- a/win_app/tests/test_firewall_first.py+++ b/win_app/tests/test_firewall_first.py@@ -56,5 +56,48 @@ class RulesBeforeListeningTests(unittest.TestCase):self.assertEqual(events, ["listen"])[email protected](sys.platform == "win32", "the app module needs Windows")+class FromSourceTests(unittest.TestCase):+ """29-09-2026: the test suite on the rig replaced the installed Beamer's rules with+ python.exe's, and the Mac's link timed out until Beamer restarted."""++ def run_both(self, frozen):+ import kvm_bridge_win as module++ events = []+ owner = SimpleNamespace(+ update_checker=SimpleNamespace(start=lambda: None),+ _firewall_target=lambda: ("C:\\Beamer\\Beamer.exe", 24820),+ bridge=SimpleNamespace(rules_ready=SimpleNamespace(emit=lambda: None)),+ _listen=lambda: None,+ _firewall_advice=SimpleNamespace(action="repair", rule_profiles=("Private",)),+ _run_firewall=lambda job, working: job("C:\\Beamer\\Beamer.exe", 24820),+ )+ owner._rules_then_listen = lambda: module.WindowsApplication._rules_then_listen(owner)++ class Inline:+ def __init__(self, target, **kwargs):+ self.target = target++ def start(self):+ self.target()++ missing = SimpleNamespace(allowed=False, blocked=False, error="")+ with mock.patch.object(module.sys, "frozen", frozen, create=True), \+ mock.patch.object(module.threading, "Thread", Inline), \+ mock.patch.object(module.firewall_win, "is_elevated", return_value=True), \+ mock.patch.object(module.firewall_win, "status", return_value=missing), \+ mock.patch.object(module.firewall_win, "repair", side_effect=lambda *a: events.append("repair")):+ module.WindowsApplication.start(owner)+ module.WindowsApplication._firewall_action(owner)+ return events++ def test_the_built_exe_writes_its_rules_at_start_and_on_fix(self):+ self.assertEqual(self.run_both(frozen=True), ["repair", "repair"])++ def test_from_source_neither_path_touches_the_firewall(self):+ self.assertEqual(self.run_both(frozen=False), [])++if __name__ == "__main__":unittest.main()diff --git a/win_app/tests/test_replay.py b/win_app/tests/test_replay.pynew file mode 100644index 0000000..c2ec3a0--- /dev/null+++ b/win_app/tests/test_replay.py@@ -0,0 +1,116 @@+"""Whole-connection replay: the PC's real link recorded, then its bytes sent again as a new+connection to the same receiver.++An attacker on the LAN who recorded one connection opens a new one and sends the recorded+initiator bytes in order: the preamble, the hello and every input frame after it. Per-frame+replay inside a connection was always refused; this is the whole stream again, into a fresh+responder, and it must fail the tag rather than type what was recorded."""++import socket+import time+import unittest++import protocol+import receiver+import sender+from app_config import Config+from fakes import FakeClipboard, FakeDesktop, FakeInjector, wait_for_calls+from return_edge import Rect+from test_sender import NoUnlock, free_port, make_config, wait_for++MONITORS = [Rect(0, 0, 1920, 1080)]+++class Recording:+ """A connected socket that keeps a copy of every byte each way."""++ def __init__(self, sock):+ self._sock = sock+ self.sent = bytearray()+ self.received = bytearray()++ def sendall(self, data, *args):+ self.sent += data+ return self._sock.sendall(data, *args)++ def send(self, data, *args):+ count = self._sock.send(data, *args)+ self.sent += data[:count]+ return count++ def recv(self, size, *args):+ data = self._sock.recv(size, *args)+ self.received += data+ return data++ def __getattr__(self, name):+ return getattr(self._sock, name)+++def replay(port, data):+ """Send `data` as a fresh connection and return every byte the responder sent back before it+ closed."""+ with socket.create_connection(("127.0.0.1", port), timeout=3.0) as attacker:+ attacker.sendall(bytes(data))+ attacker.shutdown(socket.SHUT_WR)+ reply = bytearray()+ while True:+ try:+ chunk = attacker.recv(65536)+ except (ConnectionResetError, ConnectionAbortedError, socket.timeout):+ break+ if not chunk:+ break+ reply += chunk+ return bytes(reply)+++class WholeConnectionReplayTests(unittest.TestCase):+ def test_the_pcs_recorded_keystrokes_replayed_into_the_mac_are_refused(self):+ injector = FakeInjector()+ server = receiver.ReceiverServer(+ status_callback=lambda state, detail: None,+ clipboard=FakeClipboard(),+ unlock=NoUnlock(),+ desktop=FakeDesktop(MONITORS, cursor=(900, 500)),+ injector=injector,+ self_name="Mac",+ peer_name="PC",+ self_target="mac",+ peer_target="windows",+ )+ port = free_port()+ server.start(Config(host="127.0.0.1", port=port, auth_token="shared-token"))+ self.addCleanup(server.stop)+ recordings = []++ def connect(address, timeout):+ recordings.append(Recording(socket.create_connection(address, timeout)))+ return recordings[-1]++ link = sender.MacSender(+ desktop=FakeDesktop(MONITORS, cursor=(0, 500)),+ clipboard=FakeClipboard(),+ is_local=lambda host: False,+ socket_factory=connect,+ )+ link.start(make_config(port=port))+ self.assertTrue(wait_for(lambda: link.connected), f"never connected: {link.status}")+ link.set_redirecting(True, arrival_edge="right", offset=0.5)+ link.on_key("a", True)+ link.on_key("a", False)+ wait_for_calls(injector.calls, 2)+ link.stop()+ typed = [call for call in injector.calls if call[0] == "key"]+ self.assertEqual(typed, [("key", ("a", True)), ("key", ("a", False))])+ self.assertEqual(len(recordings), 1)++ reply = replay(port, recordings[0].sent)+ time.sleep(0.2)++ self.assertEqual([call for call in injector.calls if call[0] == "key"], typed, "replayed keys reached the Mac")+ self.assertEqual(len(reply), protocol.PREAMBLE_SIZE, "the Mac answered past its preamble")+++if __name__ == "__main__":+ unittest.main()