One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.4.3
Toby Kalkman8ff1d989e618
diff --git a/PAIRING.md b/PAIRING.mdnew file mode 100644index 0000000..f620105--- /dev/null+++ b/PAIRING.md@@ -0,0 +1,220 @@+# Pairing++How two machines running Beamer agree a token from the six-digit code, exactly enough to write+a second implementation. The code is `mac_app/pairing.py` (and its byte-identical copy in+`win_app`); `mac_app/tests/pairing_vectors.json` holds test vectors for every step. What+pairing protects and what it does not is in [SECURITY.md](SECURITY.md).++Pairing is CPace, a password-authenticated key exchange, with the code as the password:+[draft-irtf-cfrg-cpace-21](https://datatracker.ietf.org/doc/draft-irtf-cfrg-cpace/21/), "the+draft" below. Nothing either machine sends can be tested against a list of codes, so whoever takes part+without the code gets at most one guess against each machine, and the guesses are limited by a+person pressing a button.++## The protocol++Suite: CPACE-X25519-SHA512, initiator and responder roles, with the explicit key confirmation+of the draft's section 10.4. The requester is the initiator (A); the host, which shows the+code, is the responder (B).++### Encodings++- **Datagrams.** One JSON object each, UTF-8, on UDP 24821, with `"beamy": 1` added to the+ fields shown below. At most 1024 bytes as encoded; a longer one is dropped unread. The+ messages in the vectors file are shown before `beamy` is added.+- **`b64`.** URL-safe base64 without padding, and only that spelling: a receiver decodes a+ field, encodes it again, and refuses the message if the text differs. Empty bytes are `""`.+- **`lv_cat(a, b, ...)`.** The draft's length-value concatenation: each string with its length+ in LEB128 before it (one byte for lengths under 128). `lv_cat` of one string still carries+ that string's length.+- **Hex in the vectors** is bytes in wire order. The two `elligator2` fields are the exception:+ integers printed big-endian, as RFC 9380 prints them.+- **`pair_id`** is 32 lowercase hex characters (16 random bytes) the host makes with each code+ and sends in its beacon. Everywhere it is used as those 32 ASCII characters, never decoded.+ A receiver ignores one that is empty, longer than 64 characters or not ASCII.+- **Names** in `pair_start` and `pair_answer` are at most 48 Unicode code points. A beacon's+ name is not held to that: it is only shown, cut to 64 for the list, and proves nothing. That is not UTF-16 units (Kotlin's and Java's+ `length`), not grapheme clusters (Swift's `count`) and not bytes. The sender cuts a longer+ name on a code point boundary before sending; a receiver refuses a longer one, and one that+ is not valid Unicode (a lone surrogate). Both sides hash the UTF-8 of the name exactly as the+ JSON carried it, with no normalisation. The `name_cut` vector pins the count.+- **Identities** are 0 to 32 bytes, and empty today. A later version feeds each machine's+ 16-byte id and changes nothing else; the second exchange in the vectors is that shape. The+ exchange proves an identity was sent unaltered, not that it is the one wanted: a side that+ receives one must check it against what it expects, as the draft's section 10.1.1 requires.+ With empty identities there is nothing to check.++### Inputs++| CPace input | Value |+|---|---|+| PRS | the code, six ASCII digits |+| sid | `lv_cat(pair_id as its 32 ASCII characters, nonce)`, 50 bytes |+| CI | `b"beamer-pair-v2"` |+| ADa | `lv_cat(b"requester", requester_id, requester_name as UTF-8)` |+| ADb | `lv_cat(b"host", host_id, host_name as UTF-8)` |++- `nonce` is 16 random bytes from the requester, new for every attempt. With the host's+ `pair_id` the sid has fresh randomness from both ends, which is what the draft recommends.+- The host builds ADa from the `id` and `name` in `pair_start`; the requester builds ADb from+ the `id` and `name` in `pair_answer`. Each side builds its own from what it sent.+- The roles are the two fixed strings. They come first in ADa and ADb, so the two can never be+ equal, and a tag cannot be reflected at the side that made it.++### Computation++```+generator_string = lv_cat(b"CPace255", PRS, zero_bytes(z), CI, sid)+ z = 128 - 1 - len(prepend_len(PRS)) - len(prepend_len(b"CPace255")) = 111 for a six-digit code+h = first 32 bytes of SHA-512(generator_string)+r = h as a little-endian integer, with bit 255 cleared+g = elligator2(r) as 32 little-endian bytes+ya, yb = 32 random bytes each, new for every exchange+Ya = X25519(ya, g) Yb = X25519(yb, g)+K = X25519(ya, Yb) = X25519(yb, Ya); refuse if K is 32 zero bytes (the host checks this before it computes g)+ISK = SHA-512(lv_cat(b"CPace255_ISK", sid, K) || lv_cat(Ya, ADa) || lv_cat(Yb, ADb))+mac_key = SHA-512(b"CPaceMac" || sid || ISK)+Ta = HMAC-SHA-512(mac_key, lv_cat(Ya, ADa))+Tb = HMAC-SHA-512(mac_key, lv_cat(Yb, ADb))+Td = HMAC-SHA-512(mac_key, lv_cat(b"beamer-pair-done"))+token = b64(HKDF-SHA-256(ikm = ISK, salt = sid, info = b"beamer-pair-token-v2", 32 bytes))+```++- **`elligator2(r)`**, with p = 2^255 - 19 and A = 486662, all arithmetic mod p (r may be p or+ more, and is reduced): `v = -A / (1 + 2 r^2)`; `e = (v^3 + A v^2 + v)^((p - 1) / 2)`; the+ result is `v` if `e` is 1, else `-v - A`. This is RFC 9380 section 6.7.1 with Z = 2, and the+ draft's appendix A.5. Only the u coordinate is used.+- **`X25519`** is RFC 7748's: the scalar is clamped and bit 255 of the incoming u is ignored.+ A platform's own X25519 does both. The draft's low-order vectors depend on the mask.+- **K all zero** is how a low-order share shows. Test the output. A library that throws on+ such a share instead of returning zeros (Node does, CryptoKit does for some) has made the+ same finding: treat the throw as a refusal.+- **The transcript** is the draft's `transcript_ir`: the initiator's part first, always.+- **`mac_key`** is used as the 64-byte HMAC key as it stands. The tags are the full 64 bytes.+- **HKDF** is RFC 5869 with the sid as the extract step's salt and the ASCII label as info.+ The token is the 43 characters of `b64` over its 32 bytes.++Everything down to `Tb` is the draft. `Td` and `token` are Beamer's. `Td` is the host's receipt+that it accepted the confirmation and holds the same token; it is sent before the host writes+its settings, so it does not prove that write succeeded. `token` is what both apps save and+what `protocol.py` derives each connection's keys from, unchanged.++### Messages++```+beacon host, every 2 s {type:"beacon", name, port, pairing:2, pair: pair_id while a code is up}+pair_start requester {type, pair, v:2, nonce: b64, share: b64(Ya), name, id: b64}+pair_answer host {type, pair, ok:true, share: b64(Yb), tag: b64(Tb), name, id: b64}+pair_confirm requester {type, pair, tag: b64(Ta)}+pair_done host {type, pair, ok:true, tag: b64(Td)}+```++A failure is `{type, pair, ok:false, error}` in place of `pair_answer` or `pair_done`:++| `error` | When |+|---|---|+| `not_pairing` | no code is up, the code has expired, or `pair` is not the current pairing id |+| `version` | `v` in `pair_start` is not 2; the code is dropped |+| `refused` | everything else: a malformed field (a nonce that is not 16 bytes, a share that is not 32, a name or identity over its limit), a share that gives a zero K, a second different `pair_start`, a tag that does not check out |++Errors are not authenticated: anyone on the LAN can already stop a pairing.++### Rules++These are what hold an attacker to one guess against each side, so a second implementation+keeps every one.++1. **A host answers one `pair_start` per code.** The first one binds the code. The same+ datagram again gets the same answer (UDP retransmits). A different one gets `refused`, and+ the exchange under way is left alone. Every answer would be another guess for its sender.+2. **A requester judges one `pair_answer` per share.** It takes the first `pair_answer` from+ the host's address that carries its `pair` and decides on it. It never waits for a better+ one: each answer it judged would be a guess for whoever is answering. A new attempt means a+ new nonce and a new scalar. The source address only sorts the replies; it proves nothing,+ and nothing may rest on it.+3. **A requester does not send a code again once an `ok:true` answer to it has failed.** Whoever+ sent that answer has had a guess at the code. The real host has by then bound the code to+ that attempt or dropped it, so sending it again cannot pair; it would only buy a second+ guess. For two minutes, longer than any code lives, the requester reports `refused` for+ that code without sending anything. It is the code that is remembered and not the pairing+ id, because a beacon with a new pairing id costs an attacker nothing. An `ok:false` answer+ tests no guess and is not remembered: an honest host sends one for a stale pairing id.+4. **The requester checks `Tb` before it sends `Ta`.** It refuses an `ok:true` answer when+ `ok` is anything but JSON `true`, a field is not the one spelling of `b64`, the share is+ not 32 bytes, the identity is over 32 bytes, the name is over 48 code points or not valid+ Unicode, K is zero, or `Tb` does not check out. It then sends `pair_confirm` with `tag: ""`,+ once, and reports `refused`. The host answers that with `pair_done`, `ok:false`, `refused`,+ drops the code, and its window says a wrong code was entered.+5. **The host stores the token only after `Ta` checks out.** A wrong tag ends the code.+6. **The requester stores the token only after `Td` checks out**, and records the host's name+ from `pair_answer`, which the exchange proved, not the one in the beacon.+7. **A share that gives an all-zero `K` is refused.** These are the low-order points; the+ draft's appendix B.1.10 lists them and the vectors file repeats them.+8. **No fallback.** A beacon without `pairing: 2` is never paired with; the requester says the+ two versions differ before it sends anything. A host answers a 1.4.2 `pair_request` with a+ refusal and drops its code, unless an exchange is already under way, which it leaves alone.+9. **Tags are compared in constant time**, and scalars are never reused.+10. **A code lasts 60 seconds**, bound or not.++### On the socket++- The host sends at most one refusal to an address every half second, as it already did for+ `find`. A requester that misses one asks again after its own 1.5 second timeout. A datagram+ whose `pair` is not shaped like a pairing id gets no reply at all, so a reply is never much+ larger than what drew it.+- The host sends a newly made `pair_answer` 50 milliseconds after the `pair_start` arrived,+ so the time the generator took cannot be read off the reply; making the answer takes about a+ thirtieth of that. Everything that can refuse a `pair_start` is checked before the code is+ used, so a refusal, which goes back at once, carries none of that time either. A retransmit+ is answered from memory, at once.+- The requester's list of hosts holds 64. When it is full, the one heard from longest ago makes+ way for a new one, except a host the user asked for by address, which always stays.+- The requester sends each datagram up to three times, 1.5 seconds apart, until the reply+ comes. It keeps only replies from the host's address that carry its pairing id, at most 64+ of them, and only while an attempt is under way.+- A datagram that does not parse, a nest of brackets included, is dropped, and nothing one+ datagram does ends the loop that read it.++### What it does not do++- It does not stop a denial. A junk `pair_start` uses up the code.+- It does not make the two machines' guesses one. Someone on the path can spend a guess against+ the host, as a requester, and another against the requester, as a host: two chances in a+ million for a code, not one. No exchange between two parties can do better than a guess a+ side.+- If every `pair_done` is lost, the host has stored the token and the requester has not. The+ requester reports no answer and the user pairs again, as with a lost reply in 1.4.2.+- The host's address, port and wake address are still taken from the beacon, which nothing+ authenticates. Something on the path can point the Mac at the wrong address; it cannot read+ or forge the link, whose keys come from the token.+- The map to the curve runs in Python integers, which are not constant time, where the draft+ asks for a constant-time map. PyNaCl exposes no Montgomery Elligator map; libsodium's+ `crypto_core_ed25519_from_uniform` clears the cofactor, which would give a different+ generator from the draft's and lose its vectors. The input is a hash of a code that is used+ once and lives a minute, and the host's answer leaves at a fixed time whatever the map took.+ The host computes it once per code and the requester once per attempt; on an Apple M1 it takes about 290 µs with 5.5 µs of spread, noise included, so there+ is one sample of a few microseconds' signal to time across a network.++## Versions++- This exchange is pairing version 2, in Beamer 1.4.3 and later. Version 1, in 1.4.2 and+ earlier, proved the code with an HMAC keyed from it and could be attacked offline; it is not+ spoken any more, in either direction.+- The link's wire protocol is not changed by it. Machines paired by an earlier Beamer stay+ paired, and the two can be updated one at a time; both need 1.4.3 to pair afresh.++## The vectors++`mac_app/tests/pairing_vectors.json`, with an identical copy in `win_app/tests`:++- `cpace_draft`: the draft's own X25519 vector, so the core is proved against the IETF's+ numbers before anything of Beamer's is added;+- `elligator2`: field elements and the u coordinates they map to, from RFC 9380 J.4.2;+- `low_order_shares`: the shares that must be refused, and five that must not be;+- `exchanges`: two complete exchanges with every intermediate value and all four messages, one+ with empty identities and one with 16-byte identities and a name outside ASCII and the BMP;+- `wrong_code`: an answer made under another code, which the requester must refuse and abort;+- `name_cut`: a 60 code point name and the 48 it is cut to.++No vector covers retransmission, expiry, or rules 2 and 3; `mac_app/tests/test_pairing_cpace.py`+and the loopback tests in `mac_app/tests/test_pairing.py` do.diff --git a/README.md b/README.mdindex 48350e2..5afb69d 100644--- a/README.md+++ b/README.md@@ -309,8 +309,9 @@ settings show the measured round trip while input is on the PC.<summary><strong>Security</strong></summary>Both apps derive a key from the shared token with HKDF-SHA256 and seal every frame with-ChaCha20-Poly1305. The token is never sent. Pairing agrees a token over X25519, with each side-proving it knows the six-digit code. What that does and does not protect against is in+ChaCha20-Poly1305. The token is never sent. Pairing agrees a token with CPace, a+password-authenticated key exchange over X25519, from the six-digit code, so nothing sent while+pairing can be tested against a list of codes. What that does and does not protect against is in[SECURITY.md](SECURITY.md).</details>diff --git a/SECURITY.md b/SECURITY.mdindex 7ec0335..930fa49 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -18,11 +18,18 @@ them matters. This is what it protects, what it does not, and how to report a prthe key was the same for every connection, and that whole-connection replay worked: someone onyour network who recorded a session could send it again, and the keystrokes, clicks and clipboardin 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 a- token over X25519, and each proves it knows the code with an HMAC keyed from it (scrypt, salted- per code). The code itself never crosses the network. The PC uses up its code on the first- answer it receives, right or wrong, so each code allows one guess, and a new code needs someone- at the PC to press Pair a Mac again.+- **Pairing is a six-digit code that lasts a minute and works once.** The two machines run CPace,+ a password-authenticated key exchange, with the code as the password, and the token comes out+ of it. The code never crosses the network, and neither does anything a list of codes could be+ tested against: someone listening, or answering in either machine's place, learns only whether+ their one guess was right. The PC answers the first machine to try a code and no other, and the+ Mac judges one answer to a code and no other, so a code allows at most one guess against each+ machine, two chances in a million, and a new code needs someone at the PC to press Pair a Mac+ again. The exchange is written out in [PAIRING.md](PAIRING.md). Before 1.4.3 each machine+ proved it knew the code with an HMAC keyed from it, and someone on your network during that+ minute could capture the Mac's proof, try every code against it offline given enough hardware,+ and pair with the PC as the Mac. Update both machines to 1.4.3 or later, and pair again if you+ last paired on a network you do not trust.- **Traffic stays on your network.** The two machines talk to each other directly. There is noserver, no account and no telemetry. On Windows, the firewall rules Beamer adds apply to Privatenetworks only. The one request that leaves your network is the update check: once a day, an@@ -36,11 +43,20 @@ them matters. This is what it protects, what it does not, and how to report a pr- **Anyone on your network can see that Beamer is running.** The PC broadcasts a small beacon everytwo seconds with its name and Beamer's port, and both machines listen on TCP 24820. Anyone cansend to the pairing port on UDP 24821 while a code is on screen.-- **Someone on your network while you pair can interfere.** A junk answer uses up the code and- stops that pairing. An attacker who answers the Mac in the PC's place during that minute receives- a proof they can try all million codes against offline, and with enough hardware could pair as- the other machine. The scheme trusts your network for the minute a code is on screen. Pair on a- network you trust.+- **Someone on your network while you pair can interfere.** A junk message uses up the code and+ stops that pairing, and so does answering the Mac in the PC's place. That is a nuisance, not a+ way in: whoever does it gets one guess at the code against the PC and one against the Mac, two+ chances in a million for each code you show. The PC answers one machine per code, and the Mac+ will not send a code a second time once an answer to it has failed.+- **The step that mixes the code into pairing is not constant-time arithmetic.** How long it+ takes varies by a few millionths of a second with the code. The PC sends its answer a fixed+ time after the request arrives, so that duration cannot be read off the network, and the code+ is used once and gone in a minute; someone who can time code inside your machine has already+ got further than this protects against.+- **The PC's address is not proved by pairing.** The Mac takes the PC's address and port from the+ PC's announcement, which anything on your network can imitate. That can point the Mac at the+ wrong address and stop it connecting; it cannot read or forge the link, whose keys come from+ the token.- **A machine that holds the token is trusted completely.** It can type and click anything on theother machine. On Windows that includes admin windows, because Beamer runs elevated so it canreach them. Treat the token like a password.diff --git a/VERSION b/VERSIONindex 9df886c..428b770 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.4.2+1.4.3diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.pyindex af33cc3..1c44900 100644--- a/mac_app/kvm_bridge_app.py+++ b/mac_app/kvm_bridge_app.py@@ -2356,7 +2356,7 @@ class ControlWindow(AppKit.NSObject):@objc.python_methoddef _say(self, message, ink="ink_2"):- self.message_label.set(message, ink=ink)+ self.message_label.set(self._shown(message), ink=ink)@objc.python_methoddef show(self):@@ -2580,7 +2580,7 @@ class ControlWindow(AppKit.NSObject):paired = bool(cfg.auth_token)refused = state.key == "token"repairing = getattr(self, "_repairing", False)- peer = link_state.peer_name(cfg)+ peer = self._shown(link_state.peer_name(cfg))motion.set_hidden(self.paired_module.view, not paired)motion.set_hidden(self.pair_module.view, paired and not refused and not repairing)self.paired_name.set(peer)@@ -2741,15 +2741,19 @@ class ControlWindow(AppKit.NSObject):self._say_pairing(f"{name} is not showing a code. Start pairing in Beamer on it, then try again.", "fault")elif reason == pairing.ERROR_REFUSED:self._say_pairing("That code was not accepted, and the PC has cancelled it. Start pairing there again for a fresh one.", "fault")+ elif reason == pairing.ERROR_VERSION:+ self._say_pairing("The PC runs a different version of Beamer. Update Beamer on both machines, then pair again.", "fault")elif reason == "no_answer":self._say_pairing(f"{name} did not answer. Check both machines are on the same network, then try again.", "fault")else:self._say_pairing(f"Pairing failed: {reason}", "fault")return+ # The name the exchange proved, not the one the beacon claimed.+ token, name = resultraw = config_to_raw(self.controller.cfg)raw["host"] = pc["address"]raw["port"] = pc["port"]- raw["auth_token"] = result+ raw["auth_token"] = tokenraw["pc_name"] = name# The Mac has just exchanged packets with the PC, so its ARP entry is fresh.raw["mac_address"] = lookup_mac(pc["address"]) or ""@@ -3295,7 +3299,7 @@ class TrayApp(rumps.App):except Exception:self.logger.exception("failed to beep for a user alert")try:- rumps.notification("Beamer", title, message)+ rumps.notification("Beamer", title, pages.redact(message, self.controller.cfg.hide_addresses))except Exception:self.logger.exception("failed to show a user notification")diff --git a/mac_app/pairing.py b/mac_app/pairing.pyindex f733d84..fb0c916 100644--- a/mac_app/pairing.py+++ b/mac_app/pairing.py@@ -1,16 +1,21 @@"""LAN discovery and pairing, shared by mac_app and win_app (two identical copies; the Mactest suite checks they match byte for byte).-The Windows receiver broadcasts a small UDP beacon -- hostname, Beamer TCP port, and a random-pairing id while a code is on screen -- and the Mac lists what it hears. Pairing then runs as-one datagram each way:-- Mac -> PC pair_request {pair, pub: X25519 public key, proof, name}- PC -> Mac pair_reply {pair, ok, pub: X25519 public key, proof}--Both proofs are HMACs keyed from the six-digit code (scrypt, salted with the pairing id) over-the transcript, so each side shows the other that it knows the code. The shared token is-HKDF over the X25519 secret: an eavesdropper who records every datagram cannot derive it.+The host (the PC) broadcasts a small UDP beacon -- hostname, Beamer TCP port, and a random+pairing id while a code is on screen -- and the requester (the Mac) lists what it hears. Pairing+is then a PAKE with the six-digit code as its password: CPace, draft-irtf-cfrg-cpace-21, suite+CPACE-X25519-SHA512 with initiator and responder roles, followed by the explicit key+confirmation of the draft's section 10.4. Four datagrams:++ requester -> host pair_start {pair, v, nonce, share: Ya, name, id}+ host -> requester pair_answer {pair, ok, share: Yb, tag: Tb, name, id}+ requester -> host pair_confirm {pair, tag: Ta}+ host -> requester pair_done {pair, ok, tag: Td}++Both shares are X25519 public values over a generator derived from the code, so neither says+anything about the code to someone who does not already know it. The shared token is HKDF over+CPace's session key. The full specification is PAIRING.md at the repository root;+tests/pairing_vectors.json holds vectors for every step.Where no broadcast reaches the Mac (another subnet, a VPN), the Mac asks a typed address for itsbeacon with a `find` datagram, and pairing continues exactly as above.@@ -19,18 +24,23 @@ What this protects against, and what it does not:- The token never crosses the wire, and neither does the code. The beacon carries nothing atoken or key could be derived from.-- A wrong code fails closed. The PC consumes its code on the first confirmation it receives,- right or wrong, so one code gives one guess; a fresh code needs a person at the PC to press- Pair a Mac again, and that is the rate limit. Codes expire after CODE_LIFETIME_SECONDS.-- A passive listener can, offline, brute-force the code out of a recorded proof. That is why- the code is single-use and why the key stretching is memory-hard: the code is worthless the- moment it is consumed, and the token does not depend on it anyway.-- An ACTIVE attacker on the LAN during the pairing window is not stopped. One that answers the- Mac's request in the PC's place receives the Mac's proof, can crack the six digits in the- time the code is still valid given enough hardware, and pair with either side as the other.- One that merely sends a junk confirmation burns the code and stops that pairing (a denial,- not a compromise). A six-digit code without a PAKE cannot do better; the scheme trusts the- LAN for the minute the code is on screen, and no longer.+- Nothing on the wire can be tested against a list of codes offline, recorded or live. Whoever+ takes part without the code gets one guess against each side: a host answers only the first+ pair_start a code receives, a requester judges only the first pair_answer to its share, and+ it does not send a code again once an answer to it has failed. These rules are what keep an+ attacker to a guess a side, two chances in a million for a code, so none may be relaxed.+- A wrong code fails closed. The requester checks the host's tag before it sends its own, and+ the host stores a token only after the requester's tag checks out. A fresh code needs a person+ at the PC to press Pair a Mac again, and that is the rate limit. Codes expire after+ CODE_LIFETIME_SECONDS.+- Anyone on the LAN can still stop a pairing: a junk pair_start uses up the code. That is a+ denial, not a compromise.+- The host's address and port still come from the beacon, which nothing authenticates. That+ can point the Mac at the wrong address; it cannot read or forge the link.+- The generator is mapped to the curve in Python integers, which are not constant time. The+ code it depends on is single-use and lives a minute, so there is one computation to time per+ code on the PC and one per attempt on the Mac, and the PC's answer leaves a fixed time after+ the request whatever that computation took."""from __future__ import annotations@@ -46,26 +56,53 @@ import socketimport threadingimport time-from cryptography.hazmat.primitives import hashes, serialization-from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey-from cryptography.hazmat.primitives.kdf.hkdf import HKDF+from nacl.bindings import crypto_scalarmult+from nacl.exceptions import CryptoErrorimport protocol# One home for the port, in the module both apps share byte-for-byte.PAIRING_PORT = protocol.PAIRING_PORTBEACON_VERSION = 1+# The pairing exchange's own version, in every beacon and every pair_start. 1 was the+# scrypt-keyed HMAC proof of 1.4.2 and earlier, which carried no number. There is no fallback+# to it: a version that does not match ends the attempt with ERROR_VERSION.+PAIRING_VERSION = 2BEACON_INTERVAL_SECONDS = 2.0# Three missed beacons: long enough to ride out Wi-Fi hiccups, short enough that a PC that# went to sleep leaves the list before anyone tries it.BEACON_STALE_SECONDS = 7.0+# More PCs than any one network shows, and a ceiling on what forged beacons can make a Mac hold.+MAX_SEEN_HOSTS = 64+# A good pair_answer leaves this long after its pair_start arrived, however long it took to+# make. The generator's arithmetic is not constant time, and this keeps its duration out of+# the one thing a stranger can time: the answer.+PAIR_ANSWER_SECONDS = 0.05CODE_LIFETIME_SECONDS = 60.0+# How long a requester will not send a code again after an answer to it failed: past the code's+# own life, after which a guess at it is worth nothing.+FAILED_CODE_SECONDS = 2 * CODE_LIFETIME_SECONDSCODE_DIGITS = 6MAX_DATAGRAM_BYTES = 1024PAIR_REPLY_TIMEOUT_SECONDS = 1.5PAIR_ATTEMPTS = 3+NONCE_BYTES = 16+SHARE_BYTES = 32+TAG_BYTES = 64+# A name is bound into the exchange as sent, so it is cut before it is sent, never after. 48+# characters keep the largest datagram under MAX_DATAGRAM_BYTES even when JSON escapes each one.+MAX_NAME_CHARS = 48+MAX_IDENTITY_BYTES = 32+# A pairing id is 32 hex characters; 1.4.2's was 8. Anything longer or not ASCII is not one.+MAX_PAIR_ID_CHARS = 64MSG_BEACON = "beacon"+MSG_PAIR_START = "pair_start"+MSG_PAIR_ANSWER = "pair_answer"+MSG_PAIR_CONFIRM = "pair_confirm"+MSG_PAIR_DONE = "pair_done"+# The 1.4.2 exchange's two datagrams. A host still answers the request, with a refusal, so an+# older Mac is told something rather than left to time out.MSG_PAIR_REQUEST = "pair_request"MSG_PAIR_REPLY = "pair_reply"# The Mac asking one address for its beacon, for a PC that no broadcast reaches (another subnet,@@ -74,13 +111,22 @@ MSG_FIND = "find"ERROR_NOT_PAIRING = "not_pairing"ERROR_REFUSED = "refused"+ERROR_VERSION = "version"+_ERRORS = (ERROR_NOT_PAIRING, ERROR_REFUSED, ERROR_VERSION)++# What the exchange binds besides the code. The two roles are fixed by who shows the code; the+# identities are parameters, empty until machines have ids of their own (wire v6), so a later+# version changes what is fed in and nothing else.+ROLE_REQUESTER = b"requester"+ROLE_HOST = b"host"+CHANNEL = b"beamer-pair-v2"+TOKEN_INFO = b"beamer-pair-token-v2"+DONE_LABEL = b"beamer-pair-done"-# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing-# pairing and a mixed-version pair for no gain.-TOKEN_INFO = b"beamy-pair-token"-# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing-# pairing and a mixed-version pair for no gain.-CODE_INFO = b"beamy-pair-code"+_DSI = b"CPace255"+_FIELD_PRIME = 2**255 - 19+_CURVE_A = 486662+_SHA512_BLOCK_BYTES = 128class PairingError(Exception):@@ -91,20 +137,6 @@ def new_code() -> str:return "".join(secrets.choice("0123456789") for _ in range(CODE_DIGITS))-def _code_key(code: str, pair_id: str) -> bytes:- # scrypt rather than HKDF on purpose: a recorded proof lets anyone try all million codes- # offline, and 32MB per guess is what keeps that from finishing inside the code's minute.- # maxmem is explicit because OpenSSL's default is exactly the 32MiB this needs, and it- # refuses at the boundary.- return hashlib.scrypt(- code.encode("utf-8"), salt=pair_id.encode("utf-8") + CODE_INFO, n=2**15, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024- )---def _proof(key: bytes, role: bytes, pair_id: str, mac_pub: bytes, pc_pub: bytes = b"") -> bytes:- return hmac.new(key, role + pair_id.encode("utf-8") + mac_pub + pc_pub, hashlib.sha256).digest()--def _b64(data: bytes) -> str:return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")@@ -113,18 +145,101 @@ def _unb64(text: str) -> bytes:if not isinstance(text, str):raise PairingError("expected base64 text")try:- return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))except ValueError as exc:raise PairingError("bad base64") from exc+ # The decoder skips what it does not know, so several spellings give the same bytes. Only+ # the one _b64 writes is taken: a field then has one form on the wire on every platform.+ if _b64(data) != text:+ raise PairingError("bad base64")+ return data+++def _prepend_len(data: bytes) -> bytes:+ """The draft's prepend_len: the length as LEB128, then the bytes."""+ length = len(data)+ encoded = bytearray()+ while True:+ encoded.append(length & 0x7F if length < 128 else (length & 0x7F) | 0x80)+ length >>= 7+ if length == 0:+ return bytes(encoded) + data+++def _lv_cat(*parts: bytes) -> bytes:+ return b"".join(_prepend_len(part) for part in parts)+++def _elligator2(r: int) -> int:+ """The u coordinate Elligator 2 maps a field element to on Curve25519 (RFC 9380 6.7.1 with+ Z = 2, as the draft's appendix A.5 repeats it)."""+ p = _FIELD_PRIME+ v = -_CURVE_A * pow(1 + 2 * r * r, p - 2, p) % p+ square = pow((v * v * v + _CURVE_A * v * v + v) % p, (p - 1) // 2, p) == 1+ return v if square else (-v - _CURVE_A) % p+++def _generator(prs: bytes, channel: bytes, sid: bytes) -> bytes:+ """The draft's calculate_generator for G_X25519 with SHA-512 (sections 8.1 and 8.2)."""+ padding = bytes(max(0, _SHA512_BLOCK_BYTES - 1 - len(_prepend_len(prs)) - len(_prepend_len(_DSI))))+ digest = hashlib.sha512(_lv_cat(_DSI, prs, padding, channel, sid)).digest()[:SHARE_BYTES]+ r = int.from_bytes(digest, "little") & ((1 << 255) - 1)+ return _elligator2(r).to_bytes(SHARE_BYTES, "little")+++def _x25519(scalar: bytes, point: bytes) -> bytes:+ """X25519 (RFC 7748), refusing a point that lands on the neutral element: the draft's+ scalar_mult_vfy, which MUST abort there. libsodium reports exactly that case as an error."""+ try:+ product = crypto_scalarmult(scalar, point)+ except CryptoError as exc:+ raise PairingError(ERROR_REFUSED) from exc+ if product == bytes(SHARE_BYTES):+ raise PairingError(ERROR_REFUSED)+ return product+++def _hkdf(key_material: bytes, salt: bytes, info: bytes) -> bytes:+ """HKDF-SHA256 (RFC 5869) for one 32-byte block."""+ extracted = hmac.new(salt, key_material, hashlib.sha256).digest()+ return hmac.new(extracted, info + b"\x01", hashlib.sha256).digest()+++def _session_id(pair_id: str, nonce: bytes) -> bytes:+ # Random bytes from both ends, as the draft recommends for sid: the host's in the pairing+ # id, the requester's in its nonce.+ return _lv_cat(pair_id.encode("utf-8"), nonce)+++def _party(role: bytes, identity: bytes, name: str) -> bytes:+ """One side's associated data: CPace's ADa or ADb. The role comes first, so the two sides'+ can never be equal, which is what stops a tag being reflected back at its sender."""+ return _lv_cat(role, identity, name.encode("utf-8"))+++def _share(code: str, sid: bytes, scalar: bytes) -> bytes:+ return _x25519(scalar, _generator(code.encode("utf-8"), CHANNEL, sid))-def _public_bytes(key) -> bytes:- return key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)+def _keys(sid: bytes, shared: bytes, ya: bytes, ada: bytes, yb: bytes, adb: bytes) -> tuple:+ """(token, Ta, Tb, Td) for one exchange, from the secret the two shares agree. Ta and Tb are+ the draft's tags over each side's own message; Td is the host's receipt."""+ isk = hashlib.sha512(_lv_cat(_DSI + b"_ISK", sid, shared) + _lv_cat(ya, ada) + _lv_cat(yb, adb)).digest()+ mac_key = hashlib.sha512(b"CPaceMac" + sid + isk).digest()+ def tag(message: bytes) -> bytes:+ return hmac.new(mac_key, message, hashlib.sha512).digest()-def derive_token(private_key, peer_public: bytes, pair_id: str) -> str:- shared = private_key.exchange(X25519PublicKey.from_public_bytes(peer_public))- return _b64(HKDF(algorithm=hashes.SHA256(), length=32, salt=pair_id.encode("utf-8"), info=TOKEN_INFO).derive(shared))+ return _b64(_hkdf(isk, sid, TOKEN_INFO)), tag(_lv_cat(ya, ada)), tag(_lv_cat(yb, adb)), tag(_lv_cat(DONE_LABEL))+++def _failure(kind: str, pair_id: str, error: str) -> dict:+ return {"type": kind, "pair": pair_id, "ok": False, "error": error}+++def _error_of(reply: dict) -> str:+ error = reply.get("error")+ return error if error in _ERRORS else ERROR_REFUSEDdef encode(message: dict) -> bytes:@@ -139,7 +254,9 @@ def decode(data: bytes):return Nonetry:message = json.loads(data.decode("utf-8"))- except (UnicodeDecodeError, ValueError):+ except (UnicodeDecodeError, ValueError, RecursionError):+ # RecursionError is what a datagram of nothing but brackets raises on some Pythons, and+ # left uncaught it would end the socket loop that called this.return Noneif not isinstance(message, dict) or message.get("beamy") != BEACON_VERSION:return None@@ -147,25 +264,34 @@ def decode(data: bytes):def beacon_msg(name: str, port: int, pair_id: str = None) -> dict:- message = {"type": MSG_BEACON, "name": name, "port": int(port)}+ message = {"type": MSG_BEACON, "name": name, "port": int(port), "pairing": PAIRING_VERSION}if pair_id:message["pair"] = pair_idreturn messageclass PairingHost:- """The PC's half: holds at most one live code and answers pair requests. Pure -- the- Announcer owns the socket and the clock is injected for the tests."""+ """The PC's half: holds at most one live code and answers the exchange. Pure -- the+ Announcer owns the socket, and the clock and the randomness are injected for the tests and+ the vectors."""- def __init__(self, clock=time.monotonic):+ def __init__(self, clock=time.monotonic, name: str = "", identity: bytes = b"", entropy=secrets.token_bytes):self.clock = clock+ self.name = name[:MAX_NAME_CHARS]+ self.identity = identity+ self._entropy = entropyself.code = Noneself.pair_id = Noneself.expires_at = 0.0+ # The one pair_start this code answered, as a dict; None until it arrives.+ self._bound = Noneself._last = None+ # True once a pair_answer has just been worked out from the code, until the caller that+ # sends it takes note. A retransmit's answer comes from memory and leaves it False.+ self.fresh_answer = Falseself.paired = None- # How the last code ended -- "paired", "refused" or "expired" -- for the window to say- # so; None while a code is live or after a deliberate cancel.+ # How the last code ended -- "paired", "refused", "version" or "expired" -- for the+ # window to say so; None while a code is live or after a deliberate cancel.self.outcome = None@property@@ -184,9 +310,11 @@ class PairingHost:def begin(self) -> str:self.code = new_code()- self.pair_id = secrets.token_hex(4)+ self.pair_id = self._entropy(16).hex()self.expires_at = self.clock() + CODE_LIFETIME_SECONDS+ self._bound = Noneself._last = None+ self.fresh_answer = Falseself.outcome = Nonereturn self.code@@ -194,86 +322,208 @@ class PairingHost:self.code = Noneself.pair_id = Noneself.expires_at = 0.0+ self._bound = Noneself.outcome = Nonedef handle(self, message: dict):"""The reply to one datagram, or None when it deserves no answer. A successful pairing- leaves the token in `self.paired` as (token, mac_name); the caller stores it."""- if message.get("type") != MSG_PAIR_REQUEST:- return None+ leaves the token in `self.paired` as (token, requester_name); the caller stores it."""+ kind = message.get("type")pair_id = message.get("pair")- if not isinstance(pair_id, str):+ # Every reply echoes the pairing id, so one that is not shaped like an id gets none: a+ # reply is then never much larger than the datagram that drew it.+ if not isinstance(pair_id, str) or not pair_id.isascii() or not 0 < len(pair_id) <= MAX_PAIR_ID_CHARS:return None- if self._last is not None and self._last[0] == (pair_id, message.get("pub"), message.get("proof")):- # A lost reply makes the Mac send the same request again; answer it the same way,- # so a retransmit is not read as a second attempt.+ if kind == MSG_PAIR_START:+ return self._start(message, pair_id)+ if kind == MSG_PAIR_CONFIRM:+ return self._confirm(message, pair_id)+ if kind == MSG_PAIR_REQUEST:+ return self._outdated(pair_id)+ return None++ def _start(self, message: dict, pair_id: str) -> dict:+ sent = [message.get(field) for field in ("pair", "v", "nonce", "share", "name", "id")]+ if self._last is not None and self._last[0] == sent:+ # A lost reply makes the requester send the same datagram again; answer it the same+ # way, so a retransmit is not read as a second attempt.return self._last[1]if not self.active or pair_id != self.pair_id:- return {"type": MSG_PAIR_REPLY, "pair": pair_id, "ok": False, "error": ERROR_NOT_PAIRING}- code, self.code = self.code, None+ return _failure(MSG_PAIR_ANSWER, pair_id, ERROR_NOT_PAIRING)+ if self._bound is not None:+ if self._bound["sent"] == sent:+ return self._bound["answer"]+ # One code answers one share. A second answer would hand whoever sent it a second+ # guess at the code, so it is refused, and the exchange already under way is left+ # alone rather than cancelled by a stranger's datagram.+ return _failure(MSG_PAIR_ANSWER, pair_id, ERROR_REFUSED)+ if message.get("v") != PAIRING_VERSION:+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_VERSION, "version")try:- mac_pub = _unb64(message.get("pub"))- proof = _unb64(message.get("proof"))- X25519PublicKey.from_public_bytes(mac_pub)- except (PairingError, ValueError):- return self._refuse(message, pair_id)- key = _code_key(code, pair_id)- if not hmac.compare_digest(proof, _proof(key, b"mac", pair_id, mac_pub)):- return self._refuse(message, pair_id)- private_key = X25519PrivateKey.generate()- pc_pub = _public_bytes(private_key)- name = message.get("name")- self.paired = (derive_token(private_key, mac_pub, pair_id), name if isinstance(name, str) else "")- reply = {- "type": MSG_PAIR_REPLY,+ nonce = _unb64(message.get("nonce"))+ share = _unb64(message.get("share"))+ identity = _unb64(message.get("id"))+ name = message.get("name")+ if (+ len(nonce) != NONCE_BYTES+ or len(share) != SHARE_BYTES+ or len(identity) > MAX_IDENTITY_BYTES+ or not isinstance(name, str)+ or len(name) > MAX_NAME_CHARS+ ):+ raise PairingError(ERROR_REFUSED)+ sid = _session_id(pair_id, nonce)+ scalar = self._entropy(SHARE_BYTES)+ requester = _party(ROLE_REQUESTER, identity, name)+ host = _party(ROLE_HOST, self.identity, self.name)+ # Everything that can refuse this datagram is settled before the code is touched:+ # a refusal goes back at once, and must not carry the time the generator took.+ shared = _x25519(scalar, share)+ except (PairingError, UnicodeError):+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_REFUSED, "refused")+ try:+ own = _share(self.code, sid, scalar)+ except PairingError:+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_REFUSED, "refused")+ token, requester_tag, host_tag, done_tag = _keys(sid, shared, share, requester, own, host)+ self.fresh_answer = True+ answer = {+ "type": MSG_PAIR_ANSWER,"pair": pair_id,"ok": True,- "pub": _b64(pc_pub),- "proof": _b64(_proof(key, b"pc", pair_id, mac_pub, pc_pub)),+ "share": _b64(own),+ "tag": _b64(host_tag),+ "name": self.name,+ "id": _b64(self.identity),+ }+ self._bound = {+ "sent": sent,+ "answer": answer,+ "requester_tag": requester_tag,+ "done_tag": done_tag,+ "token": token,+ "name": name,}- self._last = ((pair_id, message.get("pub"), message.get("proof")), reply)+ return answer++ def _confirm(self, message: dict, pair_id: str) -> dict:+ sent = [pair_id, message.get("tag")]+ if self._last is not None and self._last[0] == sent:+ return self._last[1]+ if not self.active or pair_id != self.pair_id or self._bound is None:+ return _failure(MSG_PAIR_DONE, pair_id, ERROR_NOT_PAIRING)+ bound = self._bound+ try:+ tag = _unb64(message.get("tag"))+ except PairingError:+ tag = b""+ if not hmac.compare_digest(tag, bound["requester_tag"]):+ return self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_REFUSED, "refused")+ self.paired = (bound["token"], bound["name"])+ reply = {"type": MSG_PAIR_DONE, "pair": pair_id, "ok": True, "tag": _b64(bound["done_tag"])}+ self._last = (sent, reply)self.cancel()self.outcome = "paired"return reply- def _refuse(self, message: dict, pair_id: str) -> dict:- reply = {"type": MSG_PAIR_REPLY, "pair": pair_id, "ok": False, "error": ERROR_REFUSED}- self._last = ((pair_id, message.get("pub"), message.get("proof")), reply)+ def _outdated(self, pair_id: str) -> dict:+ """A 1.4.2 Mac's request. It is answered in the datagram that Mac reads, and the code+ goes, because its window then says the PC cancelled it."""+ if self.active and pair_id == self.pair_id and self._bound is None:+ self.cancel()+ self.outcome = "version"+ return _failure(MSG_PAIR_REPLY, pair_id, ERROR_REFUSED)+ return _failure(MSG_PAIR_REPLY, pair_id, ERROR_REFUSED if self.active else ERROR_NOT_PAIRING)++ def _end(self, kind: str, sent: list, pair_id: str, error: str, outcome: str) -> dict:+ reply = _failure(kind, pair_id, error)+ self._last = (sent, reply)self.cancel()- self.outcome = "refused"+ self.outcome = outcomereturn replyclass PairingClient:- """The Mac's half of one attempt: builds the request, checks the reply, yields the token."""+ """The Mac's half of one attempt: builds the start, checks the answer, confirms, and yields+ the token once the host says it has stored it."""- def __init__(self, pair_id: str, code: str, name: str):+ def __init__(self, pair_id: str, code: str, name: str, identity: bytes = b"", entropy=secrets.token_bytes):self.pair_id = pair_id- self.name = name- self._private_key = X25519PrivateKey.generate()- self._pub = _public_bytes(self._private_key)- self._key = _code_key(code, pair_id)-- def request(self) -> dict:+ self.name = name[:MAX_NAME_CHARS]+ self.identity = identity+ self._nonce = entropy(NONCE_BYTES)+ self._sid = _session_id(pair_id, self._nonce)+ self._scalar = entropy(SHARE_BYTES)+ self._share = _share(code, self._sid, self._scalar)+ self._answered = False+ self._token = None+ self._done_tag = None+ # The host's name and identity as the exchange bound them; None until its tag checks out.+ self.host_name = None+ self.host_identity = None++ def start(self) -> dict:return {- "type": MSG_PAIR_REQUEST,+ "type": MSG_PAIR_START,"pair": self.pair_id,- "pub": _b64(self._pub),- "proof": _b64(_proof(self._key, b"mac", self.pair_id, self._pub)),+ "v": PAIRING_VERSION,+ "nonce": _b64(self._nonce),+ "share": _b64(self._share),"name": self.name,+ "id": _b64(self.identity),}- def accept(self, reply: dict) -> str:- """The agreed token, or PairingError naming why not."""- if reply.get("type") != MSG_PAIR_REPLY or reply.get("pair") != self.pair_id:+ def accept(self, answer: dict) -> dict:+ """The pair_confirm to send back, or PairingError naming why not. It judges one answer+ and no more: each answer it judged would be another guess at the code for whoever is+ answering."""+ if answer.get("type") != MSG_PAIR_ANSWER or answer.get("pair") != self.pair_id:raise PairingError("not a reply to this attempt")- if reply.get("ok") is not True:- raise PairingError(reply.get("error") if reply.get("error") in (ERROR_NOT_PAIRING, ERROR_REFUSED) else ERROR_REFUSED)- pc_pub = _unb64(reply.get("pub"))- proof = _unb64(reply.get("proof"))- if not hmac.compare_digest(proof, _proof(self._key, b"pc", self.pair_id, self._pub, pc_pub)):+ if self._answered:raise PairingError(ERROR_REFUSED)- return derive_token(self._private_key, pc_pub, self.pair_id)+ self._answered = True+ if answer.get("ok") is not True:+ raise PairingError(_error_of(answer))+ try:+ share = _unb64(answer.get("share"))+ tag = _unb64(answer.get("tag"))+ identity = _unb64(answer.get("id"))+ name = answer.get("name")+ if len(share) != SHARE_BYTES or len(identity) > MAX_IDENTITY_BYTES or not isinstance(name, str) or len(name) > MAX_NAME_CHARS:+ raise PairingError(ERROR_REFUSED)+ requester = _party(ROLE_REQUESTER, self.identity, self.name)+ host = _party(ROLE_HOST, identity, name)+ shared = _x25519(self._scalar, share)+ token, requester_tag, host_tag, done_tag = _keys(self._sid, shared, self._share, requester, share, host)+ except (PairingError, UnicodeError) as exc:+ raise PairingError(ERROR_REFUSED) from exc+ if not hmac.compare_digest(tag, host_tag):+ raise PairingError(ERROR_REFUSED)+ self._token = token+ self._done_tag = done_tag+ self.host_name = name+ self.host_identity = identity+ return {"type": MSG_PAIR_CONFIRM, "pair": self.pair_id, "tag": _b64(requester_tag)}++ def abort(self) -> dict:+ """What to send a host whose answer failed: a confirmation that cannot pass, so the PC+ drops the code and says a wrong one was entered instead of showing it for the rest of+ its minute."""+ return {"type": MSG_PAIR_CONFIRM, "pair": self.pair_id, "tag": ""}++ def finish(self, done: dict) -> str:+ """The agreed token, once the host's pair_done proves it stored the same one."""+ if done.get("type") != MSG_PAIR_DONE or done.get("pair") != self.pair_id or self._token is None:+ raise PairingError("not a reply to this attempt")+ if done.get("ok") is not True:+ raise PairingError(_error_of(done))+ try:+ tag = _unb64(done.get("tag"))+ except PairingError as exc:+ raise PairingError(ERROR_REFUSED) from exc+ if not hmac.compare_digest(tag, self._done_tag):+ raise PairingError(ERROR_REFUSED)+ return self._tokendef _udp_socket(bind_port: int) -> socket.socket:@@ -352,7 +602,7 @@ class Announcer:self.bind_port = bind_portself.announce_to = announce_toself.name = name or machine_name()- self.host = PairingHost()+ self.host = PairingHost(name=self.name)self._lock = threading.Lock()self._stop = threading.Event()self._thread = None@@ -401,6 +651,22 @@ class Announcer:pair_id = self.host.pair_id if self.host.active else Nonereturn encode(beacon_msg(self.name, self.port_getter(), pair_id))+ @staticmethod+ def _due(last: dict, host: str, now: float) -> bool:+ """Whether `host` may be sent another datagram of a rationed kind, noting it if so."""+ interval = BEACON_INTERVAL_SECONDS / 4+ if now - last.get(host, -BEACON_INTERVAL_SECONDS) < interval:+ return False+ if len(last) > 256:+ # Only what has lapsed is forgotten. Emptying the table would let a burst from+ # made-up addresses wipe the record of the one being aimed at.+ for lapsed in [known for known, sent in last.items() if now - sent >= interval]:+ del last[lapsed]+ if len(last) > 256:+ return False+ last[host] = now+ return True+def _run(self) -> None:try:sock = _udp_socket(self.bind_port)@@ -411,6 +677,7 @@ class Announcer:self.error = Nonenext_beacon = 0.0answered = {}+ refused = {}try:while not self._stop.is_set():now = time.monotonic()@@ -448,24 +715,35 @@ class Announcer:self.error = str(exc)self.logger.error("pairing beacon stopped: %s", exc)break+ arrived = time.monotonic()message = decode(data)if message is None:continueif message.get("type") == MSG_FIND:# At most one answer per address per interval, so the port is no amplifier.- if now - answered.get(address[0], -BEACON_INTERVAL_SECONDS) >= BEACON_INTERVAL_SECONDS / 4:- if len(answered) > 256:- answered.clear()- answered[address[0]] = now+ if self._due(answered, address[0], arrived):try:sock.sendto(self._beacon(), address)except OSError as exc:self.logger.warning("beacon to %s not sent: %s", address[0], exc)continuewith self._lock:- reply = self.host.handle(message)+ try:+ reply = self.host.handle(message)+ except Exception:+ # Whatever one datagram does, the next beacon still goes out.+ self.logger.exception("pairing datagram dropped")+ reply = Nonepaired, self.host.paired = self.host.paired, None- if reply is not None:+ fresh, self.host.fresh_answer = self.host.fresh_answer, False+ # A refusal is larger than the smallest datagram that draws one, so it is rationed+ # the same way. A requester that misses one asks again after its own timeout.+ if reply is not None and (reply.get("ok") is True or self._due(refused, address[0], arrived)):+ if fresh:+ # Only the answer just worked out from the code is held back. A+ # retransmit's comes from memory, and holding each of those would let a+ # stream of replays stall this loop.+ self._stop.wait(max(0.0, arrived + PAIR_ANSWER_SECONDS - time.monotonic()))try:sock.sendto(encode(reply), address)except OSError as exc:@@ -493,7 +771,11 @@ class Discovery:self.clock = clockself._lock = threading.Lock()self._seen = {}- self._replies = queue.Queue()+ self._replies = queue.Queue(maxsize=64)+ self._awaiting = None+ self._pairing = threading.Lock()+ # Codes an answer has failed under, each with the time it may be tried again.+ self._failed = {}self._stop = threading.Event()self._thread = Noneself._sock = None@@ -542,7 +824,8 @@ class Discovery:self._thread = Nonedef pcs(self) -> list:- """Every PC heard from recently: dicts of name, address, port, reply_port, pairing."""+ """Every PC heard from recently: dicts of name, address, port, reply_port, pair_id and+ pairing, the version of the exchange it speaks."""cutoff = self.clock() - BEACON_STALE_SECONDSwith self._lock:stale = [key for key, entry in self._seen.items() if entry["seen_at"] < cutoff]@@ -553,22 +836,68 @@ class Discovery:key=lambda entry: (entry["name"].lower(), entry["address"]),)- def pair(self, pc: dict, code: str, name: str = None) -> str:- """Runs the exchange with `pc` (an entry from pcs()) and returns the token. Blocks for- up to PAIR_ATTEMPTS replies' worth; call it off the main thread."""+ def pair(self, pc: dict, code: str, name: str = None) -> tuple:+ """Runs the exchange with `pc` (an entry from pcs()) and returns (token, host_name),+ the name being the one the exchange proved. Blocks for up to PAIR_ATTEMPTS replies'+ worth, once for the answer and once for the receipt; call it off the main thread."""sock = self._sockif sock is None:raise PairingError("discovery is not running")- client = PairingClient(pc["pair_id"], code, name or machine_name())+ if pc.get("pairing") != PAIRING_VERSION:+ # Said here, before anything is sent: there is no older exchange to fall back to.+ raise PairingError(ERROR_VERSION)+ if not isinstance(pc.get("pair_id"), str):+ raise PairingError(ERROR_NOT_PAIRING)target = (pc["address"], pc["reply_port"])- while True:+ if not self._pairing.acquire(blocking=False):+ # One attempt at a time: a second would take the first one's replies, and could+ # slip past the record of failed codes below.+ raise PairingError("busy")+ try:+ now = self.clock()+ self._failed = {failed: until for failed, until in self._failed.items() if until > now}+ if code in self._failed:+ # An answer to this code was judged and failed, so whoever answered has had a+ # guess at it. The real host has bound the code to that attempt or dropped it;+ # sending another share would pair with nobody and only buy the answerer a+ # second guess. It is the code that is remembered, not the pairing id, which a+ # beacon can forge.+ raise PairingError(ERROR_REFUSED)+ client = PairingClient(pc["pair_id"], code, name or machine_name())+ while True:+ try:+ self._replies.get_nowait()+ except queue.Empty:+ break+ self._awaiting = (target[0], client.pair_id)+ answer = self._ask(sock, target, client.pair_id, client.start(), MSG_PAIR_ANSWER)try:- self._replies.get_nowait()- except queue.Empty:- break- request = encode(client.request())+ confirm = client.accept(answer)+ except PairingError:+ # Only an answer that claimed to be good can have tested a guess. A refusal+ # tests nothing, and a stale pairing id draws one from an honest PC.+ if answer.get("ok") is True:+ self._failed[code] = self.clock() + FAILED_CODE_SECONDS+ try:+ sock.sendto(encode(client.abort()), target)+ except OSError:+ pass+ raise+ token = client.finish(self._ask(sock, target, client.pair_id, confirm, MSG_PAIR_DONE))+ return token, client.host_name+ finally:+ self._awaiting = None+ self._pairing.release()++ def _ask(self, sock, target, pair_id: str, message: dict, reply_type: str) -> dict:+ """Sends one datagram until the first reply of `reply_type` from `target` comes back.+ The first one decides: the caller judges it and never waits for a better one."""+ datagram = encode(message)for _attempt in range(PAIR_ATTEMPTS):- sock.sendto(request, target)+ try:+ sock.sendto(datagram, target)+ except OSError as exc:+ raise PairingError("no_answer") from excdeadline = self.clock() + PAIR_REPLY_TIMEOUT_SECONDSwhile True:remaining = deadline - self.clock()@@ -578,9 +907,9 @@ class Discovery:reply, address = self._replies.get(timeout=remaining)except queue.Empty:break- if address[0] != target[0] or reply.get("pair") != client.pair_id:+ if address[0] != target[0] or reply.get("pair") != pair_id or reply.get("type") != reply_type:continue- return client.accept(reply)+ return replyraise PairingError("no_answer")def _run(self) -> None:@@ -612,9 +941,17 @@ class Discovery:continuekind = message.get("type")if kind == MSG_BEACON:- self._note_beacon(message, address)- elif kind == MSG_PAIR_REPLY:- self._replies.put((message, address))+ try:+ self._note_beacon(message, address)+ except Exception:+ self.logger.exception("beacon dropped")+ elif kind in (MSG_PAIR_ANSWER, MSG_PAIR_DONE) and self._awaiting == (address[0], message.get("pair")):+ # Only what the attempt under way is waiting for is kept, and only so much+ # of it, so nothing a stranger sends piles up in memory.+ try:+ self._replies.put_nowait((message, address))+ except queue.Full:+ passexcept Exception as exc:self.error = str(exc)self.logger.exception("discovery stopped")@@ -637,15 +974,36 @@ class Discovery:name = message.get("name")port = message.get("port")pair_id = message.get("pair")+ version = message.get("pairing")if not isinstance(name, str) or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:return+ try:+ name.encode("utf-8")+ except UnicodeError:+ # Half a surrogate pair is JSON a parser accepts and text no window can show.+ returnentry = {"name": name[:64] or address[0],"address": address[0],"port": port,"reply_port": address[1],- "pair_id": pair_id if isinstance(pair_id, str) and pair_id else None,+ "pair_id": pair_id if isinstance(pair_id, str) and pair_id.isascii() and 0 < len(pair_id) <= MAX_PAIR_ID_CHARS else None,+ # A beacon from 1.4.2 or earlier carries no number: that is version 1.+ "pairing": version if isinstance(version, int) and not isinstance(version, bool) else 1,"seen_at": self.clock(),}with self._lock:+ if address[0] not in self._seen and len(self._seen) >= MAX_SEEN_HOSTS:+ # The list is only read while the window is open, so what has gone quiet is+ # cleared here too. Beacons from made-up addresses then cost a fixed amount of+ # memory and no more.+ cutoff = self.clock() - BEACON_STALE_SECONDS+ for stale in [key for key, known in self._seen.items() if known["seen_at"] < cutoff]:+ del self._seen[stale]+ if len(self._seen) >= MAX_SEEN_HOSTS:+ # Still full: whoever has been quiet longest gives way. A flood of forgeries+ # can crowd real PCs off the list that way, which is a denial like any+ # other here, so the one address the user typed is never the one to go.+ wanted = self._finding[0] if self._finding else None+ del self._seen[min((key for key in self._seen if key != wanted), key=lambda key: self._seen[key]["seen_at"])]self._seen[address[0]] = entrydiff --git a/mac_app/receiver.py b/mac_app/receiver.pyindex 4b063e8..ea1a8af 100644--- a/mac_app/receiver.py+++ b/mac_app/receiver.py@@ -29,6 +29,7 @@ ACK_IDLE_SECONDS = 0.4ACK_COALESCE_SECONDS = 0.015HELLO_TIMEOUT_SECONDS = 5.0SESSION_READ_TIMEOUT_SECONDS = 2.5+LOCK_CHECK_SECONDS = 0.5INJECTION_ERROR_STATUS_INTERVAL_SECONDS = 5.0# Windows hands the port back only when whatever holds it lets go — WinNAT's# dynamic reservations move on every reboot and can land on ours — so a bind@@ -236,6 +237,15 @@ class ReceiverServer:# seconds, and replaying seconds of stale mouse moves and keystrokes# onto the desktop the moment it appears is worse than losing them.self._unlocking = threading.Event()+ # When the console was last tested for the lock screen and first seen on it while the peer+ # drives this PC, and whether its input has been sent home for that lock. See+ # _home_if_locked.+ self._lock_checked_at = float("-inf")+ self._locked_since = None+ self._sent_home_for_lock = False+ # Set from the moment a focus brings the peer's input here until the unlock it may need+ # has been asked for, so the lock check cannot act in between. See _handle_focus.+ self._arriving = threading.Event()# `clipboard` defaults to the real clipboard_win module, imported# lazily (not at module load) so receiver.py stays importable -- and# its non-clipboard logic testable -- on a machine without@@ -685,12 +695,44 @@ class ReceiverServer:client_stop.set()self._close_socket(connection)return+ self._home_if_locked()except Exception as exc:LOGGER.exception("ACK thread failed")self._set_status(ServerState.ERROR, f"ACK worker failed: {exc}")client_stop.set()self._close_socket(connection)+ def _home_if_locked(self) -> None:+ """Send the peer's input home when this PC is on its lock screen. Beamer can neither inject+ into the secure desktop nor watch the return edge there, so a Mac left driving a locked PC+ had no way back until someone unlocked it by hand (issue #5).++ Timed, not per tick: the ACK thread wakes on every injected event, and is_locked walks the+ process list. Locked on two checks LOCK_CHECK_SECONDS apart, and never while an unlock is+ in flight: a switch to a locked PC reaches _begin_unlock a moment after focus, and an+ unlock provider that can clear the lock screen must be given the chance."""+ if not self._peer_driving or self._unlocking.is_set() or self._arriving.is_set():+ self._locked_since = None+ return+ now = time.monotonic()+ if now - self._lock_checked_at < LOCK_CHECK_SECONDS:+ return+ self._lock_checked_at = now+ try:+ locked = self._unlock_module().is_locked() is True+ except Exception:+ locked = False+ if not locked:+ self._locked_since = None+ return+ if self._locked_since is None:+ self._locked_since = now+ return+ if self._sent_home_for_lock:+ return+ LOGGER.info("Windows is locked while the %s drives it; sending its input home", self._peer_name)+ self._sent_home_for_lock = self.send_home()+def _clipboard_module(self):if self._clipboard is not None:return self._clipboard@@ -816,6 +858,9 @@ class ReceiverServer:returnif target == self._self_target:self._peer_driving = True+ self._sent_home_for_lock = False+ # A lock seen on the last visit says nothing about this one.+ self._locked_since = Noneelif target == self._peer_target:self._peer_driving = Falsetry:@@ -1013,12 +1058,21 @@ class ReceiverServer:# chord with the first local keystroke.self._drop_return()self._release_peer_keys()- self._notify_focus(target)if target == self._self_target:- self._arm_return(data)- self._place_pointer(data)- self._begin_unlock(peer, host)+ # Raised before anyone hears the peer is driving, and held until the unlock has been+ # asked for. Placing the pointer or an owner's callback can take a second, and in+ # that second the lock check saw a locked PC with the peer driving and sent its+ # input home before the provider that could have unlocked it was tried.+ self._arriving.set()+ try:+ self._notify_focus(target)+ self._arm_return(data)+ self._place_pointer(data)+ self._begin_unlock(peer, host)+ finally:+ self._arriving.clear()return+ self._notify_focus(target)if target != self._peer_target:returnclipboard = self._clipboard_module()diff --git a/mac_app/requirements-mac.txt b/mac_app/requirements-mac.txtindex e95ef8f..b0e3993 100644--- a/mac_app/requirements-mac.txt+++ b/mac_app/requirements-mac.txt@@ -4,4 +4,5 @@ pyobjc-framework-ApplicationServices==12.2.2rumps==0.4.0py2app==0.28.10cryptography>=42+PyNaCl>=1.6dmgbuild==1.6.7diff --git a/mac_app/setup.py b/mac_app/setup.pyindex 070a1ee..bf7c82f 100644--- a/mac_app/setup.py+++ b/mac_app/setup.py@@ -69,7 +69,8 @@ setup("argv_emulation": False,# cryptography ships a compiled _rust extension plus cffi; py2app's own recipe pulls# both in, but naming the package keeps its data files and submodules in the bundle.- "packages": ["rumps", "cryptography", "cffi"],+ # PyNaCl (nacl) is the same shape: a compiled _sodium extension reached through cffi.+ "packages": ["rumps", "cryptography", "cffi", "nacl"],# effects.py imports its fx_* modules by name at first use, which py2app's import scan# cannot see, so they are named here or the bundle ships without a single effect."includes": [diff --git a/mac_app/tests/pairing_vectors.json b/mac_app/tests/pairing_vectors.jsonnew file mode 100644index 0000000..7426de5--- /dev/null+++ b/mac_app/tests/pairing_vectors.json@@ -0,0 +1,252 @@+{+ "$comment": "Hex is bytes in wire order, except the two elligator2 fields, which are integers printed big-endian as RFC 9380 prints them. Messages are shown before the \"beamy\": 1 every datagram adds.",+ "suite": "CPACE-X25519-SHA512, draft-irtf-cfrg-cpace-21, initiator-responder, key confirmation per section 10.4",+ "specification": "PAIRING.md",+ "pairing_version": 2,+ "constants": {+ "dsi_ascii": "CPace255",+ "channel_ascii": "beamer-pair-v2",+ "role_requester_ascii": "requester",+ "role_host_ascii": "host",+ "token_info_ascii": "beamer-pair-token-v2",+ "done_label_ascii": "beamer-pair-done",+ "nonce_bytes": 16,+ "max_name_chars": 48,+ "max_identity_bytes": 32+ },+ "cpace_draft": {+ "prs_ascii": "Password",+ "ci_hex": "0b415f696e69746961746f720b425f726573706f6e646572",+ "sid_hex": "7e4b4791d6a8ef019b936c79fb7f2c57",+ "generator_hex": "d04bf6d41f6a289632a2e929fa29bebd51092512a7829fdde7d314b62f05a73f",+ "ada_ascii": "ADa",+ "ya_scalar_hex": "21b4f4bd9e64ed355c3eb676a28ebedaf6d8f17bdc365995b319097153044080",+ "ya_hex": "1d13c89278cdadd826f6d8d7f887701430f8380ddc17611cdd6dc989ce0c9f32",+ "adb_ascii": "ADb",+ "yb_scalar_hex": "848b0779ff415f0af4ea14df9dd1d3c29ac41d836c7808896c4eba19c51ac40a",+ "yb_hex": "248cccf6d5cdc3646f0ad593f9e6cef4e69d4945f8372e623512ecea32185623",+ "k_hex": "5b067effbdc0b2a0e1d907b21ebb25cfedb96a852179a847c37e43ee71322c6b",+ "isk_hex": "6e19b875f7a561d6b3ca3dbb9ef42ac55de3e717881018204b8922b4d5e53bb2aa82c300bea7b65d2b671da71922ddf6472301b79bc270adfa8bf413285f2263"+ },+ "elligator2": [+ {+ "field_element_hex_be": "608d892b641f0328523802a6603427c26e55e6f27e71a91a478148d45b5093cd",+ "u_hex_be": "51125222da5e763d97f3c10fcc92ea6860b9ccbbd2eb1285728f566721c1e65b"+ },+ {+ "field_element_hex_be": "46f5b22494bfeaa7f232cc8d054be68561af50230234d7d1d63d1d9abeca8da5",+ "u_hex_be": "7d56d1e08cb0ccb92baf069c18c49bb5a0dcd927eff8dcf75ca921ef7f3e6eeb"+ },+ {+ "field_element_hex_be": "235fe40c443766ce7e18111c33862d66c3b33267efa50d50f9e8e5d252a40aaa",+ "u_hex_be": "3fbe66b9c9883d79e8407150e7c2a1c8680bee496c62fabe4619a72b3cabe90f"+ },+ {+ "field_element_hex_be": "001e92a544463bda9bd04ddbe3d6eed248f82de32f522669efc5ddce95f46f5b",+ "u_hex_be": "227e0bb89de700385d19ec40e857db6e6a3e634b1c32962f370d26f84ff19683"+ },+ {+ "field_element_hex_be": "1a68a1af9f663592291af987203393f707305c7bac9c8d63d6a729bdc553dc19",+ "u_hex_be": "3bcd651ee54d5f7b6013898aab251ee8ecc0688166fce6e9548d38472f6bd196"+ }+ ],+ "low_order_shares": {+ "scalar_hex": "af46e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449aff",+ "must_refuse": [+ "0000000000000000000000000000000000000000000000000000000000000000",+ "0100000000000000000000000000000000000000000000000000000000000000",+ "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",+ "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",+ "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",+ "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",+ "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"+ ],+ "must_give": [+ {+ "share_hex": "daffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",+ "product_hex": "d8e2c776bbacd510d09fd9278b7edcd25fc5ae9adfba3b6e040e8d3b71b21806"+ },+ {+ "share_hex": "dbffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",+ "product_hex": "c85c655ebe8be44ba9c0ffde69f2fe10194458d137f09bbff725ce58803cdb38"+ },+ {+ "share_hex": "d9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",+ "product_hex": "db64dafa9b8fdd136914e61461935fe92aa372cb056314e1231bc4ec12417456"+ },+ {+ "share_hex": "cdeb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880",+ "product_hex": "e062dcd5376d58297be2618c7498f55baa07d7e03184e8aada20bca28888bf7a"+ },+ {+ "share_hex": "4c9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7",+ "product_hex": "993c6ad11c4c29da9a56f7691fd0ff8d732e49de6250b6c2e80003ff4629a175"+ }+ ]+ },+ "exchanges": [+ {+ "comment": "1.4.3: no machine ids yet, so both identities are empty",+ "code": "482913",+ "pair_id": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "requester": {+ "name": "Vector Mac",+ "id_hex": "",+ "nonce_hex": "edad1eba42ed11cfd8ba0daba74a4bc8",+ "scalar_hex": "842bca52bbbdc727263dfa19a0c2851f18862e0c31e7a1b706d6ce9d1934c604"+ },+ "host": {+ "name": "VECTOR-PC",+ "id_hex": "",+ "scalar_hex": "a2fa23319131feac78653467b4863a444f5da2af0158d1d5e1e239710d691580"+ },+ "sid_hex": "20656236636632656533633163386362643231363162363762343162653330303310edad1eba42ed11cfd8ba0daba74a4bc8",+ "ada_hex": "09726571756573746572000a566563746f72204d6163",+ "adb_hex": "04686f73740009564543544f522d5043",+ "generator_string_hex": "084350616365323535063438323931336f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76323220656236636632656533633163386362643231363162363762343162653330303310edad1eba42ed11cfd8ba0daba74a4bc8",+ "generator_hex": "1a750835aae9d408194e8e1393132e02c2495de72b6f265184749f056130ca10",+ "ya_hex": "2649f89325b72e646000fa5dc7c4221bf869de4938a88fecedbda398cbf34150",+ "yb_hex": "2d0dc754bb17865b276c39ba6ff00c0954b4804371a46742c3a2287c04e01347",+ "k_hex": "796f912ddb354ceba9a7642244ed553149bfc23f22f374bff3ad8315df817b2b",+ "isk_hex": "7dc167e8b761b5808f8e873878556f5dd1c52bdd62f3c348ea60a60512ea4294e19f6e72a0c54dacf5656a8debd79bf9615bee6fe5a59bbc98be15cf3b0bd077",+ "mac_key_hex": "8c619a26e16124af43935ba791b7de2b733ee32f13bae3c0943d574dbbbf1a0b6cd32997bf518db4b33a513f306c85ed9ac595806c3fc298488922660cce9f9c",+ "ta_hex": "630c08e363d467fa00c19d741672d4eac8bc9676c2b52bdb9f4939d842b12686c4d27c8ab900a85a411977042a9f4e97be520d9e64eeeeb59038a0330aec8f5d",+ "tb_hex": "1eeaafd522d6884f57057475a3bde52e3e14debcd79088aae52c5aa1edb858bdb12c4fb02a5427c42c46fdec565b43fd9a1c45b8b22d91ff733d43ac14396919",+ "td_hex": "cad8b6dd3af2c1f1b78c16c6eb86fdf897bb4f1b69f5559461491722a845ac83b5332c48433b5c4228accb93b3f177e264acbef9be9f4e21b985c165cea3dc2e",+ "token": "4xGHJR0vazj3INjxHjXpkTzLvzDEtxKZ8TiQQp8QhCw",+ "messages": {+ "pair_start": {+ "type": "pair_start",+ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "v": 2,+ "nonce": "7a0eukLtEc_Yug2rp0pLyA",+ "share": "Jkn4kyW3LmRgAPpdx8QiG_hp3kk4qI_s7b2jmMvzQVA",+ "name": "Vector Mac",+ "id": ""+ },+ "pair_answer": {+ "type": "pair_answer",+ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "ok": true,+ "share": "LQ3HVLsXhlsnbDm6b_AMCVS0gENxpGdCw6IofATgE0c",+ "tag": "Huqv1SLWiE9XBXR1o73lLj4U3rzXkIiq5Sxaoe24WL2xLE-wKlQnxCxG_exWW0P9mhxFuLItkf9zPUOsFDlpGQ",+ "name": "VECTOR-PC",+ "id": ""+ },+ "pair_confirm": {+ "type": "pair_confirm",+ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "tag": "YwwI42PUZ_oAwZ10FnLU6si8lnbCtSvbn0k52EKxJobE0nyKuQCoWkEZdwQqn06XvlINnmTu7rWQOKAzCuyPXQ"+ },+ "pair_done": {+ "type": "pair_done",+ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "ok": true,+ "tag": "yti23TrywfG3jBbG64b9-Je7Txtp9VWUYUkXIqhFrIO1MyxIQztcQiisy5Oz8XfiZKy--b6fTiG5hcFlzqPcLg"+ }+ }+ },+ {+ "comment": "The wire v6 shape: a 16-byte id each side, and a name with characters outside ASCII and outside the BMP",+ "code": "007045",+ "pair_id": "d397348abeb0691c3292a1f36093d950",+ "requester": {+ "name": "Zo\u00eb\u2019s \ud835\udd39eamer Mac",+ "id_hex": "74f70aa0e96f874c9866b11545950f8b",+ "nonce_hex": "e979b12f908a2f0ad16eb37876b5f0b5",+ "scalar_hex": "85b6b2942677e61db3636c9e6faea4586cc708ac4051afc481e17810a672266a"+ },+ "host": {+ "name": "VECTOR-PC",+ "id_hex": "ee3e1ebd5eacd2c487f2403bac611cdb",+ "scalar_hex": "4ee3c8b532aca27be39b1ac34ea82bd4084684dbd0e54987b192b5cd30541dbc"+ },+ "sid_hex": "20643339373334386162656230363931633332393261316633363039336439353010e979b12f908a2f0ad16eb37876b5f0b5",+ "ada_hex": "097265717565737465721074f70aa0e96f874c9866b11545950f8b165a6fc3abe280997320f09d94b965616d6572204d6163",+ "adb_hex": "04686f737410ee3e1ebd5eacd2c487f2403bac611cdb09564543544f522d5043",+ "generator_string_hex": "084350616365323535063030373034356f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76323220643339373334386162656230363931633332393261316633363039336439353010e979b12f908a2f0ad16eb37876b5f0b5",+ "generator_hex": "73b80492ce8c3d166117a405dc4bc62d593149cda94e53f3012d102fb539c069",+ "ya_hex": "46d1977042bd7aabd494df39930b1f6efb83078fe7cf605ffcf1580c8613d005",+ "yb_hex": "5fdbb545d4175d7f1e83613994e2abfdff7f7f46fb62e5c9b3f74c08e0ab8147",+ "k_hex": "f94259fbe1b827b22fc38e9beed8c77501ceca3373fe2abcc79e03ab0b245a77",+ "isk_hex": "9010d318e53253ad83ae8c3354e7d32229b7427d144d99fdba9681482a3ca81c4edc4ef433d1c2253949288c22464ff4b61b66158e983910b9c088de2826bf30",+ "mac_key_hex": "5d539ab7dd2da83e6411669bb70f95578cc61ed2f7f55462352953e3a687edcf8ea0b08bc5737d1ed2dd285cf61968efaed83d4e5acdb9136b7056f03a9681f4",+ "ta_hex": "d084e7d4b3e4d3008f2082cfeb9f421496fd1ea514717eb6f1fabb9e951deb88f734c2806c0a7153914cf5ed37635fa40dd46295c5ff0b7e8dd942f103504a41",+ "tb_hex": "2e636a9a44c7dde48f4d2dee732bd556abf31b4ba2e97121e0af076e1eb6d8297c0d4ad517513caef69c111e46c4097b940740f38e4251c10bc0a03da9b4d556",+ "td_hex": "f3ab76e44dca6d3aad881499c4941f6b5a5cd7e95971b75d0163b1f127fbb6785e728d53863a1d5e7c7ba96c8247a629f106833397415f73eb223febc28272fd",+ "token": "RG0uipRsvpPDZlGTPq3dXODw6X-a1M5f2QnB9jPcldo",+ "messages": {+ "pair_start": {+ "type": "pair_start",+ "pair": "d397348abeb0691c3292a1f36093d950",+ "v": 2,+ "nonce": "6XmxL5CKLwrRbrN4drXwtQ",+ "share": "RtGXcEK9eqvUlN85kwsfbvuDB4_nz2Bf_PFYDIYT0AU",+ "name": "Zo\u00eb\u2019s \ud835\udd39eamer Mac",+ "id": "dPcKoOlvh0yYZrEVRZUPiw"+ },+ "pair_answer": {+ "type": "pair_answer",+ "pair": "d397348abeb0691c3292a1f36093d950",+ "ok": true,+ "share": "X9u1RdQXXX8eg2E5lOKr_f9_f0b7YuXJs_dMCOCrgUc",+ "tag": "LmNqmkTH3eSPTS3ucyvVVqvzG0ui6XEh4K8Hbh622Cl8DUrVF1E8rvacER5GxAl7lAdA845CUcELwKA9qbTVVg",+ "name": "VECTOR-PC",+ "id": "7j4evV6s0sSH8kA7rGEc2w"+ },+ "pair_confirm": {+ "type": "pair_confirm",+ "pair": "d397348abeb0691c3292a1f36093d950",+ "tag": "0ITn1LPk0wCPIILP659CFJb9HqUUcX628fq7npUd64j3NMKAbApxU5FM9e03Y1-kDdRilcX_C36N2ULxA1BKQQ"+ },+ "pair_done": {+ "type": "pair_done",+ "pair": "d397348abeb0691c3292a1f36093d950",+ "ok": true,+ "tag": "86t25E3KbTqtiBSZxJQfa1pc1-lZcbddAWOx8Sf7tnheco1ThjodXnx7qWyCR6Yp8QaDM5dBX3PrIj_rwoJy_Q"+ }+ }+ }+ ],+ "wrong_code": {+ "host_code": "482913",+ "requester_code": "482914",+ "pair_id": "6bc698c0065affb622fff9fb87cac02a",+ "requester": {+ "name": "Vector Mac",+ "id_hex": "",+ "nonce_hex": "d90bf42db9e188ff2f817cd143f514f2",+ "scalar_hex": "5318fc1f72d7f28d4053a37001e4b96339c154095161d9e3686d068e993cd2a5"+ },+ "pair_start": {+ "type": "pair_start",+ "pair": "6bc698c0065affb622fff9fb87cac02a",+ "v": 2,+ "nonce": "2Qv0LbnhiP8vgXzRQ_UU8g",+ "share": "Qq9Jel7gwUBo6te3H1ucksTPo9W9_KNE3wS6H1i8IFY",+ "name": "Vector Mac",+ "id": ""+ },+ "pair_answer": {+ "type": "pair_answer",+ "pair": "6bc698c0065affb622fff9fb87cac02a",+ "ok": true,+ "share": "CAKZVA2Yp_gG6soy4krssop3x0uLbG4BIPWF2JQLCxA",+ "tag": "EDuxWV1wqH2EdQtuQCC4DyFXZb9kibeRaxATuacSQv0hr3hVqhsBkS8bt90zJirBrkZWRSBWaRWNemqnNfu31g",+ "name": "VECTOR-PC",+ "id": ""+ },+ "requester_must": "refused",+ "pair_confirm_abort": {+ "type": "pair_confirm",+ "pair": "6bc698c0065affb622fff9fb87cac02a",+ "tag": ""+ }+ },+ "name_cut": {+ "name": "\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e",+ "code_points": 60,+ "sent": "\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e",+ "sent_code_points": 48+ }+}diff --git a/mac_app/tests/test_hide_addresses_window.py b/mac_app/tests/test_hide_addresses_window.pyindex 1caa023..e1970c5 100644--- a/mac_app/tests/test_hide_addresses_window.py+++ b/mac_app/tests/test_hide_addresses_window.py@@ -60,6 +60,19 @@ class HideAddressesWindowTests(unittest.TestCase):self.assertEqual(self.window.find_field.stringValue(), "192.0.2.10")self.assertFalse(self.window.find_boxes[0].isHidden())+ def test_the_footer_hides_an_address_in_a_failed_switch(self):+ # Codex, 29-09-2026: a failed switch put the connection status, which names the PC's+ # address, in the footer as it was.+ self.window._say("Connecting to 192.0.2.20:24820", "fault")+ self.assertNotIn("192.0.2.20", self.window.message_label.view.stringValue())++ def test_an_unnamed_pc_is_not_named_by_its_address(self):+ # peer_name falls back to the address when the PC has no name.+ self.window.controller.cfg.pc_name = ""+ self.window._refresh_paired(mock.Mock(key="token"))+ self.assertNotIn("192.0.2.20", self.window.paired_name.view.stringValue())+ self.assertNotIn("192.0.2.20", self.window.paired_note.view.stringValue())+class ReloadTests(unittest.TestCase):def test_a_reload_sets_the_controller_before_the_window_reads_it(self):@@ -75,5 +88,15 @@ class ReloadTests(unittest.TestCase):self.assertEqual(calls, ["controller", "window"])+class NotificationTests(unittest.TestCase):+ def test_a_notification_hides_the_pcs_address(self):+ tray = mock.Mock()+ tray.controller.cfg.hide_addresses = True+ with mock.patch.object(kvm_bridge_app.rumps, "notification") as notification, \+ mock.patch.object(kvm_bridge_app.AppKit, "NSBeep"):+ kvm_bridge_app.TrayApp._notify_user_main(tray, "Cannot switch", "Connecting to 192.0.2.20:24820")+ self.assertNotIn("192.0.2.20", notification.call_args.args[2])++if __name__ == "__main__":unittest.main()diff --git a/mac_app/tests/test_pairing.py b/mac_app/tests/test_pairing.pyindex 43668ee..4966479 100644--- a/mac_app/tests/test_pairing.py+++ b/mac_app/tests/test_pairing.py@@ -8,7 +8,7 @@ import unittestfrom unittest import mockimport pairing-from pairing import Announcer, Discovery, PairingClient, PairingHost, beacon_msg, encode+from pairing import Announcer, Discovery, PairingHost_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))@@ -46,30 +46,6 @@ class ParityTests(unittest.TestCase):self.assertTrue(filecmp.cmp(mac, win, shallow=False), "mac_app/pairing.py and win_app/pairing.py differ")-class ExchangeTests(unittest.TestCase):- def test_wire_never_carries_the_code_or_the_token(self):- host = PairingHost()- code = host.begin()- client = PairingClient(host.pair_id, code, "Test Mac")- request = client.request()- reply = host.handle(request)- token = client.accept(reply)- self.assertEqual(token, host.paired[0])- wire = encode(beacon_msg("PC", 51820, host.pair_id)) + encode(request) + encode(reply)- self.assertNotIn(code.encode(), wire)- self.assertNotIn(token.encode(), wire)-- def test_wrong_code_fails_closed_for_the_client_too(self):- host = PairingHost()- code = host.begin()- wrong = str((int(code) + 7) % 10**6).zfill(6)- client = PairingClient(host.pair_id, wrong, "Test Mac")- with self.assertRaises(pairing.PairingError) as caught:- client.accept(host.handle(client.request()))- self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)- self.assertFalse(host.active)--class LoopbackTests(unittest.TestCase):"""The two socket loops against each other on 127.0.0.1, with the broadcast addressreplaced so nothing leaves this machine."""@@ -100,7 +76,8 @@ class LoopbackTests(unittest.TestCase):code = self.announcer.begin_pairing()self.assertTrue(wait_until(lambda: self.discovery.pcs()[0]["pair_id"] is not None))pc = self.discovery.pcs()[0]- token = self.discovery.pair(pc, code, name="Loopback Mac")+ token, host_name = self.discovery.pair(pc, code, name="Loopback Mac")+ self.assertEqual(host_name, "TEST-PC")self.assertTrue(wait_until(lambda: self.paired))self.assertEqual(self.paired[0], (token, "Loopback Mac", "127.0.0.1"))self.assertIsNone(self.announcer.code)@@ -113,9 +90,23 @@ class LoopbackTests(unittest.TestCase):with self.assertRaises(pairing.PairingError) as caught:self.discovery.pair(self.discovery.pcs()[0], wrong)self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ # The Mac's abort is what tells the PC, so its window can say a wrong code was entered.+ self.assertTrue(wait_until(lambda: self.announcer.outcome == "refused"))self.assertEqual(self.paired, [])self.assertIsNone(self.announcer.code)+ def test_a_used_code_does_not_pair_a_second_mac(self):+ self.assertTrue(wait_until(lambda: self.discovery.pcs()))+ code = self.announcer.begin_pairing()+ self.assertTrue(wait_until(lambda: self.discovery.pcs()[0]["pair_id"] is not None))+ pc = self.discovery.pcs()[0]+ self.discovery.pair(pc, code, name="First Mac")+ with self.assertRaises(pairing.PairingError) as caught:+ self.discovery.pair(pc, code, name="Second Mac")+ self.assertEqual(str(caught.exception), pairing.ERROR_NOT_PAIRING)+ self.assertTrue(wait_until(lambda: self.paired))+ self.assertEqual([name for _token, name, _address in self.paired], ["First Mac"])+def test_pairing_without_a_code_on_the_pc_says_so(self):self.assertTrue(wait_until(lambda: self.discovery.pcs()))pc = dict(self.discovery.pcs()[0], pair_id="00000000")@@ -123,6 +114,156 @@ class LoopbackTests(unittest.TestCase):self.discovery.pair(pc, "123456")self.assertEqual(str(caught.exception), pairing.ERROR_NOT_PAIRING)+ def test_a_good_answer_leaves_a_fixed_time_after_its_start(self):+ # However quickly the code's generator was worked out, the answer says nothing of it.+ self.assertTrue(wait_until(lambda: self.discovery.pcs()))+ code = self.announcer.begin_pairing()+ requester = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ requester.bind(("127.0.0.1", 0))+ requester.settimeout(2.0)+ self.addCleanup(requester.close)+ client = pairing.PairingClient(self.announcer.host.pair_id, code, "Timing Mac")+ sent = time.monotonic()+ requester.sendto(pairing.encode(client.start()), ("127.0.0.1", self.pc_port))+ data, _address = requester.recvfrom(2048)+ self.assertGreaterEqual(time.monotonic() - sent, pairing.PAIR_ANSWER_SECONDS * 0.9)+ self.assertTrue(pairing.decode(data)["ok"])+ # The same datagram again is answered from memory, and those are not held back: a+ # stream of replays would otherwise stall the loop that has the confirmation to read.+ sent = time.monotonic()+ for _ in range(40):+ requester.sendto(pairing.encode(client.start()), ("127.0.0.1", self.pc_port))+ for _ in range(40):+ requester.recvfrom(2048)+ self.assertLess(time.monotonic() - sent, pairing.PAIR_ANSWER_SECONDS * 20)++ def test_refusals_are_rationed_so_the_port_is_no_amplifier(self):+ # A beacon heard is proof both loops have bound their sockets.+ self.assertTrue(wait_until(lambda: self.discovery.pcs()))+ stranger = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ stranger.bind(("127.0.0.1", 0))+ stranger.settimeout(1.0)+ self.addCleanup(stranger.close)+ junk = pairing.encode({"type": "pair_start", "pair": "nobody"})+ for _ in range(20):+ stranger.sendto(junk, ("127.0.0.1", self.pc_port))+ replies = 0+ while True:+ try:+ stranger.recvfrom(2048)+ except socket.timeout:+ break+ replies += 1+ self.assertEqual(replies, 1)++ def test_replies_nobody_is_waiting_for_are_not_kept(self):+ self.assertTrue(wait_until(lambda: self.discovery.pcs()))+ stranger = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ self.addCleanup(stranger.close)+ for _ in range(50):+ stranger.sendto(pairing.encode({"type": "pair_answer", "pair": "nobody", "ok": True}), ("127.0.0.1", self.mac_port))+ # A beacon sent after them is proof the loop has read them all.+ stranger.sendto(pairing.encode(pairing.beacon_msg("LATER-PC", 51820)), ("127.0.0.1", self.mac_port))+ self.assertTrue(wait_until(lambda: any(pc["name"] == "LATER-PC" for pc in self.discovery.pcs())))+ self.assertEqual(self.discovery._replies.qsize(), 0)+++class ImpostorTests(unittest.TestCase):+ """Something on the network answering in the PC's place, over a real socket."""++ def setUp(self):+ self.impostor = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ self.impostor.bind(("127.0.0.1", 0))+ self.impostor.settimeout(5.0)+ self.addCleanup(self.impostor.close)+ self.discovery = Discovery(logger=quiet_logger(), bind_port=free_udp_port())+ self.discovery.start()+ self.addCleanup(self.discovery.stop)+ self.assertTrue(wait_until(lambda: self.discovery._sock is not None))+ self.real = PairingHost(name="REAL-PC")+ self.code = self.real.begin()+ self.pc = {+ # Not the name the host will prove: a beacon can say anything.+ "name": "BEACON-NAME",+ "address": "127.0.0.1",+ "port": 51820,+ "reply_port": self.impostor.getsockname()[1],+ "pair_id": self.real.pair_id,+ "pairing": pairing.PAIRING_VERSION,+ }++ def _pair_in_background(self):+ results = []++ def work():+ try:+ results.append(self.discovery.pair(self.pc, self.code, name="Test Mac"))+ except pairing.PairingError as exc:+ results.append(exc)++ thread = threading.Thread(target=work, daemon=True)+ thread.start()+ return thread, results++ def test_the_first_answer_decides_and_a_wrong_one_is_never_confirmed(self):+ thread, results = self._pair_in_background()+ data, mac = self.impostor.recvfrom(2048)+ good = self.real.handle(pairing.decode(data))+ forged = dict(good, tag=pairing._b64(bytes(pairing.TAG_BYTES)))+ # The forgery first, then the answer that would have passed: the Mac must not wait+ # for it, or every answer sent would be another guess at the code.+ self.impostor.sendto(pairing.encode(forged), mac)+ self.impostor.sendto(pairing.encode(good), mac)+ thread.join(5.0)+ self.assertEqual([str(result) for result in results], [pairing.ERROR_REFUSED])+ data, _mac = self.impostor.recvfrom(2048)+ abort = pairing.decode(data)+ self.assertEqual((abort["type"], abort["pair"], abort["tag"]), ("pair_confirm", self.real.pair_id, ""))+ # That code is now spent on this Mac: trying it again sends nothing, so whoever answered+ # gets no second guess out of a second try, even behind a beacon with a new pairing id.+ for pc in (self.pc, dict(self.pc, pair_id="ab" * 16)):+ with self.assertRaises(pairing.PairingError) as caught:+ self.discovery.pair(pc, self.code, name="Test Mac")+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.impostor.settimeout(0.5)+ with self.assertRaises(socket.timeout):+ self.impostor.recvfrom(2048)++ def test_a_refusal_from_the_pc_does_not_spend_the_code(self):+ # A stale pairing id draws not_pairing from an honest PC, and tests no guess.+ thread, results = self._pair_in_background()+ data, mac = self.impostor.recvfrom(2048)+ self.impostor.sendto(pairing.encode({"type": "pair_answer", "pair": self.real.pair_id, "ok": False, "error": "not_pairing"}), mac)+ thread.join(5.0)+ self.assertEqual([str(result) for result in results], [pairing.ERROR_NOT_PAIRING])+ thread, results = self._pair_in_background()+ data, mac = self.impostor.recvfrom(2048)+ self.assertEqual(pairing.decode(data)["type"], "pair_start")+ self.impostor.sendto(pairing.encode(self.real.handle(pairing.decode(data))), mac)+ data, mac = self.impostor.recvfrom(2048)+ self.impostor.sendto(pairing.encode(self.real.handle(pairing.decode(data))), mac)+ thread.join(5.0)+ self.assertEqual(results, [(self.real.paired[0], "REAL-PC")])++ def test_a_spent_code_may_be_sent_again_once_it_could_no_longer_be_live(self):+ self.discovery._failed[self.code] = self.discovery.clock() - 1.0+ thread, _results = self._pair_in_background()+ data, _mac = self.impostor.recvfrom(2048)+ self.assertEqual(pairing.decode(data)["type"], "pair_start")+ self.assertEqual(self.discovery._failed, {})++ def test_a_forged_receipt_does_not_yield_a_token(self):+ thread, results = self._pair_in_background()+ data, mac = self.impostor.recvfrom(2048)+ self.impostor.sendto(pairing.encode(self.real.handle(pairing.decode(data))), mac)+ data, mac = self.impostor.recvfrom(2048)+ confirm = pairing.decode(data)+ self.assertEqual(confirm["type"], "pair_confirm")+ forged = {"type": "pair_done", "pair": confirm["pair"], "ok": True, "tag": confirm["tag"]}+ self.impostor.sendto(pairing.encode(forged), mac)+ thread.join(5.0)+ self.assertEqual([str(result) for result in results], [pairing.ERROR_REFUSED])+class FindTests(unittest.TestCase):"""A PC whose beacons never reach the Mac, found by its address instead."""@@ -152,7 +293,7 @@ class FindTests(unittest.TestCase):self.assertEqual(self.discovery.pcs()[0]["name"], "FAR-PC")code = self.announcer.begin_pairing()self.assertTrue(wait_until(lambda: self.discovery.pcs()[0]["pair_id"] is not None, timeout=4.0))- token = self.discovery.pair(self.discovery.pcs()[0], code, name="Far Mac")+ token, _host_name = self.discovery.pair(self.discovery.pcs()[0], code, name="Far Mac")self.assertTrue(wait_until(lambda: self.paired))self.assertEqual(self.paired[0], (token, "Far Mac", "127.0.0.1"))@@ -163,6 +304,8 @@ class FindTests(unittest.TestCase):self.assertIsNone(self.discovery._finding)def test_a_name_that_never_resolves_does_not_hold_up_beacons(self):+ # The beacon below is sent once, so the loop must have its socket before it goes.+ self.assertTrue(wait_until(lambda: self.discovery._sock is not None))resolving = threading.Event()real = socket.getaddrinfodiff --git a/mac_app/tests/test_pairing_cpace.py b/mac_app/tests/test_pairing_cpace.pynew file mode 100644index 0000000..078bbd6--- /dev/null+++ b/mac_app/tests/test_pairing_cpace.py@@ -0,0 +1,640 @@+"""The pairing exchange itself: CPace against the published vectors, the committed vectors+replayed value by value, and the rules that hold an attacker to one guess at the code.++Pure: no sockets and no clock but the fake one, so it runs the same in both apps' suites.+"""++import json+import os+import unittest++import pairing+from pairing import PairingClient, PairingError, PairingHost, encode++_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))++with open(os.path.join(_TESTS_DIR, "pairing_vectors.json"), encoding="utf-8") as _handle:+ VECTORS = json.load(_handle)+++class FakeClock:+ def __init__(self, value=1000.0):+ self.value = value++ def __call__(self):+ return self.value++ def advance(self, seconds):+ self.value += seconds+++def scripted(*values):+ queue = list(values)+ return lambda length: queue.pop(0)+++def other_code(code):+ return str((int(code) + 1) % 10**6).zfill(6)+++def paired(host, code, name="Test Mac"):+ """One honest exchange, as (client, start, answer, confirm, done, token)."""+ client = PairingClient(host.pair_id, code, name)+ start = client.start()+ answer = host.handle(start)+ confirm = client.accept(answer)+ done = host.handle(confirm)+ return client, start, answer, confirm, done, client.finish(done)+++class PublishedVectorTests(unittest.TestCase):+ """The numbers other people published, so the core is right before Beamer adds to it."""++ def test_length_prefixes_match_the_draft(self):+ self.assertEqual(pairing._prepend_len(b"").hex(), "00")+ self.assertEqual(pairing._prepend_len(b"1234").hex(), "0431323334")+ self.assertEqual(pairing._prepend_len(bytes(128))[:2].hex(), "8001")+ self.assertEqual(pairing._prepend_len(bytes(300))[:2].hex(), "ac02")+ self.assertEqual(pairing._lv_cat(b"1234", b"5", b"", b"678").hex(), "043132333401350003363738")++ def test_the_draft_exchange_is_reproduced_step_by_step(self):+ draft = VECTORS["cpace_draft"]+ sid = bytes.fromhex(draft["sid_hex"])+ generator = pairing._generator(draft["prs_ascii"].encode(), bytes.fromhex(draft["ci_hex"]), sid)+ self.assertEqual(generator.hex(), draft["generator_hex"])+ ya_scalar = bytes.fromhex(draft["ya_scalar_hex"])+ yb_scalar = bytes.fromhex(draft["yb_scalar_hex"])+ ya = pairing._x25519(ya_scalar, generator)+ yb = pairing._x25519(yb_scalar, generator)+ self.assertEqual((ya.hex(), yb.hex()), (draft["ya_hex"], draft["yb_hex"]))+ self.assertEqual(pairing._x25519(ya_scalar, yb).hex(), draft["k_hex"])+ self.assertEqual(pairing._x25519(yb_scalar, ya).hex(), draft["k_hex"])++ def test_elligator_matches_rfc_9380(self):+ for vector in VECTORS["elligator2"]:+ with self.subTest(element=vector["field_element_hex_be"]):+ self.assertEqual(pairing._elligator2(int(vector["field_element_hex_be"], 16)), int(vector["u_hex_be"], 16))++ def test_low_order_shares_are_refused(self):+ low = VECTORS["low_order_shares"]+ scalar = bytes.fromhex(low["scalar_hex"])+ for share in low["must_refuse"]:+ with self.subTest(share=share):+ with self.assertRaises(PairingError):+ pairing._x25519(scalar, bytes.fromhex(share))+ for vector in low["must_give"]:+ with self.subTest(share=vector["share_hex"]):+ self.assertEqual(pairing._x25519(scalar, bytes.fromhex(vector["share_hex"])).hex(), vector["product_hex"])++ def test_base64_has_one_spelling(self):+ for length in range(40):+ data = bytes(range(length))+ self.assertEqual(pairing._unb64(pairing._b64(data)), data)+ for text in ("AA==", "AA=", "A", "AAB", "AB+/", " AAAA", "AAAA\n", "!!!!", "====", "AA!A", None, 7, b"AAAA"):+ with self.subTest(text=text):+ with self.assertRaises(PairingError):+ pairing._unb64(text)++ def test_hkdf_matches_rfc_5869(self):+ # Test case 1, whose first 32 bytes are the single block this HKDF produces.+ block = pairing._hkdf(bytes([0x0B]) * 22, bytes(range(13)), bytes(range(0xF0, 0xFA)))+ self.assertEqual(block.hex(), "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf")+++class PhoneVectorTests(unittest.TestCase):+ """pairing_vectors.json is what a second implementation is built against; these replay+ it through this module, so a change to the exchange cannot leave the file behind."""++ def test_constants_are_the_ones_in_the_file(self):+ constants = VECTORS["constants"]+ self.assertEqual(VECTORS["pairing_version"], pairing.PAIRING_VERSION)+ self.assertEqual(constants["channel_ascii"].encode(), pairing.CHANNEL)+ self.assertEqual(constants["role_requester_ascii"].encode(), pairing.ROLE_REQUESTER)+ self.assertEqual(constants["role_host_ascii"].encode(), pairing.ROLE_HOST)+ self.assertEqual(constants["token_info_ascii"].encode(), pairing.TOKEN_INFO)+ self.assertEqual(constants["done_label_ascii"].encode(), pairing.DONE_LABEL)+ self.assertEqual(constants["max_name_chars"], pairing.MAX_NAME_CHARS)++ def test_each_exchange_replays_to_the_same_messages_and_token(self):+ for vector in VECTORS["exchanges"]:+ with self.subTest(exchange=vector["comment"]):+ requester, host_side = vector["requester"], vector["host"]+ host = PairingHost(+ name=host_side["name"],+ identity=bytes.fromhex(host_side["id_hex"]),+ entropy=scripted(bytes.fromhex(vector["pair_id"]), bytes.fromhex(host_side["scalar_hex"])),+ )+ host.begin()+ host.code = vector["code"]+ self.assertEqual(host.pair_id, vector["pair_id"])+ client = PairingClient(+ host.pair_id,+ vector["code"],+ requester["name"],+ identity=bytes.fromhex(requester["id_hex"]),+ entropy=scripted(bytes.fromhex(requester["nonce_hex"]), bytes.fromhex(requester["scalar_hex"])),+ )+ messages = vector["messages"]+ self.assertEqual(client.start(), messages["pair_start"])+ answer = host.handle(messages["pair_start"])+ self.assertEqual(answer, messages["pair_answer"])+ confirm = client.accept(answer)+ self.assertEqual(confirm, messages["pair_confirm"])+ done = host.handle(confirm)+ self.assertEqual(done, messages["pair_done"])+ self.assertEqual(client.finish(done), vector["token"])+ self.assertEqual(host.paired, (vector["token"], requester["name"]))++ def test_each_exchange_s_intermediate_values_follow_the_specification(self):+ for vector in VECTORS["exchanges"]:+ with self.subTest(exchange=vector["comment"]):+ requester, host_side = vector["requester"], vector["host"]+ sid = pairing._session_id(vector["pair_id"], bytes.fromhex(requester["nonce_hex"]))+ self.assertEqual(sid.hex(), vector["sid_hex"])+ ada = pairing._party(pairing.ROLE_REQUESTER, bytes.fromhex(requester["id_hex"]), requester["name"])+ adb = pairing._party(pairing.ROLE_HOST, bytes.fromhex(host_side["id_hex"]), host_side["name"])+ self.assertEqual((ada.hex(), adb.hex()), (vector["ada_hex"], vector["adb_hex"]))+ self.assertEqual(pairing._generator(vector["code"].encode(), pairing.CHANNEL, sid).hex(), vector["generator_hex"])+ ya = pairing._share(vector["code"], sid, bytes.fromhex(requester["scalar_hex"]))+ yb = pairing._share(vector["code"], sid, bytes.fromhex(host_side["scalar_hex"]))+ self.assertEqual((ya.hex(), yb.hex()), (vector["ya_hex"], vector["yb_hex"]))+ for scalar, peer in ((requester["scalar_hex"], yb), (host_side["scalar_hex"], ya)):+ shared = pairing._x25519(bytes.fromhex(scalar), peer)+ token, ta, tb, td = pairing._keys(sid, shared, ya, ada, yb, adb)+ self.assertEqual(token, vector["token"])+ self.assertEqual((ta.hex(), tb.hex(), td.hex()), (vector["ta_hex"], vector["tb_hex"], vector["td_hex"]))++ def test_the_wrong_code_vector_is_refused_and_aborted(self):+ vector = VECTORS["wrong_code"]+ requester = vector["requester"]+ client = PairingClient(+ vector["pair_id"],+ vector["requester_code"],+ requester["name"],+ entropy=scripted(bytes.fromhex(requester["nonce_hex"]), bytes.fromhex(requester["scalar_hex"])),+ )+ self.assertEqual(client.start(), vector["pair_start"])+ with self.assertRaises(PairingError) as caught:+ client.accept(vector["pair_answer"])+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.assertEqual(client.abort(), vector["pair_confirm_abort"])+ self.assertEqual(vector["requester_must"], pairing.ERROR_REFUSED)++ def test_a_name_is_cut_by_code_points(self):+ vector = VECTORS["name_cut"]+ client = PairingClient("00" * 16, "482913", vector["name"])+ self.assertEqual(client.start()["name"], vector["sent"])+ self.assertEqual((len(vector["name"]), len(vector["sent"])), (vector["code_points"], pairing.MAX_NAME_CHARS))+++class ExchangeTests(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ self.host = PairingHost(self.clock, name="TEST-PC")+ self.code = self.host.begin()++ def test_right_code_agrees_one_token_without_sending_it_or_the_code(self):+ _client, start, answer, confirm, done, token = paired(self.host, self.code)+ self.assertEqual(self.host.paired, (token, "Test Mac"))+ self.assertGreaterEqual(len(token), 40)+ self.assertEqual(self.host.outcome, "paired")+ self.assertFalse(self.host.active)+ wire = b"".join(encode(message) for message in (start, answer, confirm, done))+ self.assertNotIn(token.encode(), wire)+ self.assertNotIn(self.code.encode(), wire)++ def test_the_host_stores_nothing_until_the_requester_confirms(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(client.start())+ self.assertTrue(answer["ok"])+ self.assertIsNone(self.host.paired)+ self.assertTrue(self.host.active)++ def test_two_exchanges_never_share_a_token_or_a_share(self):+ _client, first_start, _answer, _confirm, _done, first = paired(self.host, self.code)+ code = self.host.begin()+ _client, second_start, _answer, _confirm, _done, second = paired(self.host, code)+ self.assertNotEqual(first, second)+ self.assertNotEqual(first_start["share"], second_start["share"])++ def test_a_requester_with_the_wrong_code_refuses_the_answer_and_never_confirms(self):+ client = PairingClient(self.host.pair_id, other_code(self.code), "Test Mac")+ answer = self.host.handle(client.start())+ self.assertTrue(answer["ok"], "the host cannot tell a wrong code from its answer alone")+ with self.assertRaises(PairingError) as caught:+ client.accept(answer)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.assertIsNone(self.host.paired)++ def test_the_abort_ends_the_code_and_says_a_wrong_one_was_entered(self):+ client = PairingClient(self.host.pair_id, other_code(self.code), "Test Mac")+ self.host.handle(client.start())+ done = self.host.handle(client.abort())+ self.assertEqual(done, {"type": "pair_done", "pair": client.pair_id, "ok": False, "error": "refused"})+ self.assertFalse(self.host.active)+ self.assertEqual(self.host.outcome, "refused")+ self.assertIsNone(self.host.paired)++ def test_a_host_with_another_code_is_refused(self):+ impostor = PairingHost(FakeClock(), name="TEST-PC")+ impostor.begin()+ impostor.code = other_code(self.code)+ impostor.pair_id = self.host.pair_id+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ with self.assertRaises(PairingError):+ client.accept(impostor.handle(client.start()))+ with self.assertRaises(PairingError):+ client.finish({"type": "pair_done", "pair": client.pair_id, "ok": True, "tag": ""})+++class OneGuessTests(unittest.TestCase):+ """Each rule here is what stops a second guess at the code; loosening one is a hole."""++ def setUp(self):+ self.clock = FakeClock()+ self.host = PairingHost(self.clock, name="TEST-PC")+ self.code = self.host.begin()++ def test_a_code_answers_one_share_even_for_the_right_code(self):+ attacker = PairingClient(self.host.pair_id, other_code(self.code), "Attacker")+ self.assertTrue(self.host.handle(attacker.start())["ok"])+ honest = PairingClient(self.host.pair_id, self.code, "Test Mac")+ reply = self.host.handle(honest.start())+ self.assertEqual(reply, {"type": "pair_answer", "pair": honest.pair_id, "ok": False, "error": "refused"})+ second = PairingClient(self.host.pair_id, other_code(other_code(self.code)), "Attacker")+ self.assertFalse(self.host.handle(second.start())["ok"])++ def test_a_second_share_does_not_disturb_the_exchange_under_way(self):+ honest = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(honest.start())+ stranger = PairingClient(self.host.pair_id, other_code(self.code), "Attacker")+ self.assertFalse(self.host.handle(stranger.start())["ok"])+ done = self.host.handle(honest.accept(answer))+ self.assertEqual(self.host.paired[0], honest.finish(done))++ def test_a_requester_judges_one_answer_and_no_more(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ good = self.host.handle(client.start())+ forged = dict(good, tag=pairing._b64(bytes(pairing.TAG_BYTES)))+ with self.assertRaises(PairingError):+ client.accept(forged)+ with self.assertRaises(PairingError) as caught:+ client.accept(good)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)++ def test_an_error_answer_also_spends_the_attempt(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ good = self.host.handle(client.start())+ with self.assertRaises(PairingError):+ client.accept({"type": "pair_answer", "pair": client.pair_id, "ok": False, "error": "not_pairing"})+ with self.assertRaises(PairingError):+ client.accept(good)++ def test_a_wrong_confirmation_ends_the_code_and_stores_nothing(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(client.start())+ confirm = client.accept(answer)+ forged = dict(confirm, tag=pairing._b64(bytes(pairing.TAG_BYTES)))+ self.assertEqual(self.host.handle(forged)["error"], "refused")+ self.assertIsNone(self.host.paired)+ self.assertEqual(self.host.handle(confirm)["error"], "not_pairing")+ self.assertIsNone(self.host.paired)++ def test_the_host_s_own_tag_reflected_back_is_not_a_confirmation(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(client.start())+ done = self.host.handle({"type": "pair_confirm", "pair": client.pair_id, "tag": answer["tag"]})+ self.assertEqual(done["error"], "refused")+ self.assertIsNone(self.host.paired)++ def test_a_confirmation_with_no_exchange_under_way_does_nothing(self):+ done = self.host.handle({"type": "pair_confirm", "pair": self.host.pair_id, "tag": ""})+ self.assertEqual(done["error"], "not_pairing")+ self.assertTrue(self.host.active)++ def test_an_unknown_pairing_id_does_not_touch_the_code(self):+ stranger = PairingClient("deadbeef", self.code, "Test Mac")+ self.assertEqual(self.host.handle(stranger.start())["error"], "not_pairing")+ self.assertTrue(self.host.active)+ paired(self.host, self.code)++ def test_a_tampered_share_or_name_is_refused(self):+ for field, value in (("share", pairing._b64(bytes(range(1, 33)))), ("name", "EVIL-PC"), ("id", pairing._b64(b"x"))):+ with self.subTest(field=field):+ host = PairingHost(FakeClock(), name="TEST-PC")+ code = host.begin()+ client = PairingClient(host.pair_id, code, "Test Mac")+ answer = dict(host.handle(client.start()), **{field: value})+ with self.assertRaises(PairingError):+ client.accept(answer)++ def test_a_name_changed_on_the_way_to_the_host_fails_the_exchange(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(dict(client.start(), name="Someone Else"))+ with self.assertRaises(PairingError):+ client.accept(answer)++ def test_identities_are_bound_into_the_token(self):+ host = PairingHost(FakeClock(), name="TEST-PC", identity=b"h" * 16)+ code = host.begin()+ client = PairingClient(host.pair_id, code, "Test Mac", identity=b"r" * 16)+ start = client.start()+ answer = host.handle(start)+ self.assertEqual((start["id"], answer["id"]), (pairing._b64(b"r" * 16), pairing._b64(b"h" * 16)))+ self.assertEqual(client.finish(host.handle(client.accept(answer))), host.paired[0])+ host = PairingHost(FakeClock(), name="TEST-PC", identity=b"h" * 16)+ code = host.begin()+ client = PairingClient(host.pair_id, code, "Test Mac", identity=b"r" * 16)+ answer = host.handle(dict(client.start(), id=pairing._b64(b"q" * 16)))+ with self.assertRaises(PairingError):+ client.accept(answer)+++class HostStateTests(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ self.host = PairingHost(self.clock, name="TEST-PC")+ self.code = self.host.begin()++ def test_retransmitted_datagrams_get_the_same_replies(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ start = client.start()+ answer = self.host.handle(start)+ self.assertEqual(self.host.handle(start), answer)+ confirm = client.accept(answer)+ done = self.host.handle(confirm)+ self.assertEqual(self.host.handle(confirm), done)+ self.assertTrue(done["ok"])++ def test_a_refused_start_is_answered_the_same_way_again(self):+ start = dict(PairingClient(self.host.pair_id, self.code, "Test Mac").start(), share="!!")+ reply = self.host.handle(start)+ self.assertEqual(reply["error"], "refused")+ self.assertEqual(self.host.handle(start), reply)++ def test_an_expired_code_is_not_answered(self):+ pair_id = self.host.pair_id+ self.clock.advance(pairing.CODE_LIFETIME_SECONDS)+ client = PairingClient(pair_id, self.code, "Test Mac")+ self.assertEqual(self.host.handle(client.start())["error"], "not_pairing")+ self.assertEqual(self.host.outcome, "expired")++ def test_an_exchange_the_code_outlives_is_not_completed(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ confirm = client.accept(self.host.handle(client.start()))+ self.clock.advance(pairing.CODE_LIFETIME_SECONDS)+ self.assertEqual(self.host.handle(confirm)["error"], "not_pairing")+ self.assertIsNone(self.host.paired)++ def test_a_new_code_forgets_the_last_exchange(self):+ client, start, _answer, confirm, _done, _token = paired(self.host, self.code)+ self.host.paired = None+ self.host.begin()+ self.assertEqual(self.host.handle(start)["error"], "not_pairing")+ self.assertEqual(self.host.handle(confirm)["error"], "not_pairing")+ self.assertIsNone(self.host.paired)++ def test_malformed_starts_are_refused_without_an_exception(self):+ good = PairingClient(self.host.pair_id, self.code, "Test Mac").start()+ bad_fields = [+ ("nonce", "!!"), ("nonce", pairing._b64(b"short")), ("nonce", None), ("nonce", ["a"]),+ ("share", "??"), ("share", pairing._b64(bytes(31))), ("share", 7), ("share", {"a": 1}),+ ("share", pairing._b64(bytes(32))), ("share", pairing._b64(b"\x01" + bytes(31))),+ ("name", None), ("name", 12), ("name", "x" * (pairing.MAX_NAME_CHARS + 1)), ("name", "\ud800"),+ ("id", None), ("id", pairing._b64(bytes(pairing.MAX_IDENTITY_BYTES + 1))), ("id", "é"),+ ]+ for field, value in bad_fields:+ with self.subTest(field=field, value=value):+ host = PairingHost(FakeClock(), name="TEST-PC")+ host.begin()+ host.code = self.code+ host.pair_id = self.host.pair_id+ reply = host.handle(dict(good, **{field: value}))+ self.assertEqual(reply, {"type": "pair_answer", "pair": host.pair_id or good["pair"], "ok": False, "error": "refused"})+ self.assertFalse(host.active)+ self.assertIsNone(host.paired)++ def test_a_refusal_never_touches_the_code(self):+ # A refusal goes back at once, so nothing worked out from the code may come before it:+ # how long that took would be in the reply's timing.+ good = PairingClient(self.host.pair_id, self.code, "Test Mac").start()+ calls = []+ real = pairing._generator+ pairing._generator = lambda *args: calls.append(args) or real(*args)+ try:+ for field, value in (("share", pairing._b64(bytes(32))), ("share", pairing._b64(b"\x01" + bytes(31))),+ ("name", "\ud800"), ("nonce", "!!"), ("id", "=")):+ host = PairingHost(FakeClock(), name="TEST-PC")+ host.begin()+ host.code = self.code+ reply = host.handle(dict(good, pair=host.pair_id, **{field: value}))+ self.assertEqual(reply["error"], "refused")+ self.assertFalse(host.fresh_answer)+ self.assertEqual(calls, [])+ self.assertTrue(self.host.handle(good)["ok"])+ self.assertEqual(len(calls), 1)+ finally:+ pairing._generator = real++ def test_only_a_newly_made_answer_is_marked_fresh(self):+ start = PairingClient(self.host.pair_id, self.code, "Test Mac").start()+ self.assertFalse(self.host.fresh_answer)+ self.host.handle(start)+ self.assertTrue(self.host.fresh_answer)+ self.host.fresh_answer = False+ self.assertTrue(self.host.handle(start)["ok"])+ self.assertFalse(self.host.fresh_answer)++ def test_datagrams_that_are_not_for_the_host_get_no_answer(self):+ self.assertIsNone(self.host.handle({"type": "beacon", "name": "x", "port": 1}))+ self.assertIsNone(self.host.handle({"type": "pair_start", "pair": 7}))+ for pair_id in ("", "x" * 65, "\u00e9" * 8, "\ud83d"):+ self.assertIsNone(self.host.handle({"type": "pair_start", "pair": pair_id}))+ self.assertIsNone(self.host.handle({"type": "pair_request", "pair": pair_id}))+ self.assertIsNone(self.host.handle({"type": "pair_answer", "pair": self.host.pair_id}))+ self.assertTrue(self.host.active)++ def test_another_pairing_version_is_told_so(self):+ start = dict(PairingClient(self.host.pair_id, self.code, "Test Mac").start(), v=3)+ self.assertEqual(self.host.handle(start)["error"], "version")+ self.assertEqual(self.host.outcome, "version")+ self.assertFalse(self.host.active)++ def test_a_1_4_2_request_is_refused_in_the_reply_that_mac_reads(self):+ request = {"type": "pair_request", "pair": self.host.pair_id, "pub": "AAAA", "proof": "BBBB", "name": "Old Mac"}+ reply = self.host.handle(request)+ self.assertEqual(reply, {"type": "pair_reply", "pair": request["pair"], "ok": False, "error": "refused"})+ self.assertEqual(self.host.outcome, "version")+ self.assertIsNone(self.host.paired)+ self.assertEqual(self.host.handle(request)["error"], "not_pairing")++ def test_a_1_4_2_request_does_not_disturb_an_exchange_under_way(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(client.start())+ self.host.handle({"type": "pair_request", "pair": self.host.pair_id, "pub": "AAAA", "proof": "BBBB"})+ done = self.host.handle(client.accept(answer))+ self.assertEqual(self.host.paired[0], client.finish(done))+++class ClientStateTests(unittest.TestCase):+ def setUp(self):+ self.host = PairingHost(FakeClock(), name="TEST-PC")+ self.code = self.host.begin()+ self.client = PairingClient(self.host.pair_id, self.code, "Test Mac")++ def test_malformed_answers_are_refused_without_an_exception(self):+ good = self.host.handle(self.client.start())+ bad_fields = [+ ("share", None), ("share", pairing._b64(bytes(32))), ("share", pairing._b64(bytes(33))), ("share", [1]),+ ("tag", None), ("tag", "!!"), ("tag", ""), ("name", 5), ("name", "\udfff"),+ ("name", "x" * (pairing.MAX_NAME_CHARS + 1)), ("id", 1.5), ("ok", 1), ("ok", "true"),+ ]+ for field, value in bad_fields:+ with self.subTest(field=field, value=value):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ with self.assertRaises(PairingError):+ client.accept(dict(good, **{field: value}))++ def test_a_reply_to_another_attempt_is_not_judged(self):+ good = self.host.handle(self.client.start())+ for stray in (dict(good, pair="someone-else"), dict(good, type="pair_done"), {"type": "pair_reply", "pair": self.client.pair_id}):+ with self.assertRaises(PairingError) as caught:+ self.client.accept(stray)+ self.assertEqual(str(caught.exception), "not a reply to this attempt")+ self.client.accept(good)++ def test_the_token_is_only_handed_over_for_the_host_s_own_receipt(self):+ confirm = self.client.accept(self.host.handle(self.client.start()))+ done = self.host.handle(confirm)+ for forged in (dict(done, tag=confirm["tag"]), dict(done, tag=""), dict(done, tag=None)):+ with self.assertRaises(PairingError) as caught:+ self.client.finish(forged)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ with self.assertRaises(PairingError) as caught:+ self.client.finish({"type": "pair_done", "pair": self.client.pair_id, "ok": False, "error": "not_pairing"})+ self.assertEqual(str(caught.exception), pairing.ERROR_NOT_PAIRING)+ self.assertEqual(self.client.finish(done), self.host.paired[0])++ def test_the_host_s_name_is_known_only_once_its_tag_checks_out(self):+ answer = self.host.handle(self.client.start())+ self.assertIsNone(self.client.host_name)+ self.client.accept(answer)+ self.assertEqual((self.client.host_name, self.client.host_identity), ("TEST-PC", b""))++ def test_no_token_before_the_answer_was_accepted(self):+ with self.assertRaises(PairingError):+ self.client.finish({"type": "pair_done", "pair": self.client.pair_id, "ok": True, "tag": ""})++ def test_names_are_cut_before_they_are_sent_and_bound_as_sent(self):+ long_name = "M" * 200+ host = PairingHost(FakeClock(), name="P" * 200)+ code = host.begin()+ _client, start, answer, _confirm, _done, token = paired(host, code, name=long_name)+ self.assertEqual(start["name"], long_name[: pairing.MAX_NAME_CHARS])+ self.assertEqual(answer["name"], "P" * pairing.MAX_NAME_CHARS)+ self.assertEqual(host.paired, (token, long_name[: pairing.MAX_NAME_CHARS]))++ def test_the_largest_datagrams_fit(self):+ name = "\U0001d539" * pairing.MAX_NAME_CHARS+ host = PairingHost(FakeClock(), name=name, identity=bytes(pairing.MAX_IDENTITY_BYTES))+ code = host.begin()+ client = PairingClient(host.pair_id, code, name, identity=bytes(pairing.MAX_IDENTITY_BYTES))+ start = client.start()+ answer = host.handle(start)+ confirm = client.accept(answer)+ done = host.handle(confirm)+ for message in (start, answer, confirm, done, pairing.beacon_msg(name, 65535, host.pair_id or start["pair"])):+ self.assertLessEqual(len(encode(message)), pairing.MAX_DATAGRAM_BYTES)+ self.assertEqual(pairing.decode(encode(message))["type"], message["type"])+ self.assertEqual(client.finish(done), host.paired[0])+++class VersionTests(unittest.TestCase):+ def test_every_beacon_says_which_exchange_the_host_speaks(self):+ self.assertEqual(pairing.beacon_msg("TEST-PC", 51820)["pairing"], pairing.PAIRING_VERSION)+ self.assertEqual(pairing.beacon_msg("TEST-PC", 51820, "abcd")["pairing"], pairing.PAIRING_VERSION)++ def test_a_host_on_another_version_is_never_sent_anything(self):+ class Recorder:+ sent = []++ def sendto(self, data, address):+ self.sent.append((data, address))++ discovery = pairing.Discovery(bind_port=0)+ discovery._sock = Recorder()+ for version in (1, 3, None):+ pc = {"name": "OLD-PC", "address": "127.0.0.1", "port": 1, "reply_port": 1, "pair_id": "abcd", "pairing": version}+ with self.assertRaises(PairingError) as caught:+ discovery.pair(pc, "123456")+ self.assertEqual(str(caught.exception), pairing.ERROR_VERSION)+ self.assertEqual(Recorder.sent, [])++ def test_a_pairing_id_that_could_not_be_hashed_is_not_offered(self):+ discovery = pairing.Discovery(bind_port=0)+ for number, pair_id in enumerate(("\ud800", "é" * 8, "a" * 65, "", 7)):+ beacon = dict(pairing.beacon_msg("PC", 24820), pair=pair_id)+ discovery._note_beacon(beacon, (f"127.0.0.{number + 1}", 24821))+ self.assertEqual([pc["pair_id"] for pc in discovery.pcs()], [None] * 5)++ def test_a_beacon_whose_name_cannot_be_shown_is_dropped(self):+ discovery = pairing.Discovery(bind_port=0)+ discovery._note_beacon(pairing.beacon_msg("\ud800", 24820), ("127.0.0.1", 24821))+ self.assertEqual(discovery.pcs(), [])++ def test_only_one_attempt_runs_at_a_time(self):+ discovery = pairing.Discovery(bind_port=0)+ discovery._sock = object()+ discovery._pairing.acquire()+ pc = {"name": "PC", "address": "127.0.0.1", "port": 1, "reply_port": 1, "pair_id": "ab" * 16, "pairing": pairing.PAIRING_VERSION}+ with self.assertRaises(PairingError) as caught:+ discovery.pair(pc, "123456")+ self.assertEqual(str(caught.exception), "busy")++ def test_the_ration_is_not_wiped_by_a_burst_of_made_up_addresses(self):+ last = {}+ self.assertTrue(pairing.Announcer._due(last, "target", 100.0))+ for number in range(400):+ pairing.Announcer._due(last, f"spoofed-{number}", 100.1)+ self.assertFalse(pairing.Announcer._due(last, "target", 100.2))+ self.assertTrue(pairing.Announcer._due(last, "target", 101.0))+ self.assertLessEqual(len(last), 258)++ def test_forged_beacons_cannot_make_the_list_grow_without_end(self):+ clock = FakeClock()+ discovery = pairing.Discovery(bind_port=0, clock=clock)+ for number in range(500):+ discovery._note_beacon(pairing.beacon_msg(f"PC-{number}", 24820), (f"10.1.{number // 250}.{number % 250 + 1}", 24821))+ self.assertEqual(len(discovery._seen), pairing.MAX_SEEN_HOSTS)+ # A full list lets a newcomer in, the longest quiet making way for it.+ discovery._note_beacon(pairing.beacon_msg("REAL-PC", 24820), ("10.9.9.9", 24821))+ self.assertIn("REAL-PC", [pc["name"] for pc in discovery.pcs()])+ # A flood can still crowd it off again. The way through is the PC's address, typed:+ # that one is never the one to go.+ discovery._finding = ("10.9.9.9", 24821)+ for second in range(6):+ clock.advance(1.0)+ if second % 2 == 0:+ discovery._note_beacon(pairing.beacon_msg("REAL-PC", 24820), ("10.9.9.9", 24821))+ for number in range(200):+ discovery._note_beacon(pairing.beacon_msg("FORGED", 24820), (f"10.3.{second}.{number + 1}", 24821))+ self.assertIn("REAL-PC", [pc["name"] for pc in discovery.pcs()])+ self.assertEqual(len(discovery._seen), pairing.MAX_SEEN_HOSTS)+ discovery._finding = None+ clock.advance(pairing.BEACON_STALE_SECONDS + 1)+ discovery._note_beacon(pairing.beacon_msg("LATE-PC", 24820), ("10.2.0.1", 24821))+ self.assertEqual([pc["name"] for pc in discovery.pcs()], ["LATE-PC"])++ def test_a_datagram_of_nothing_but_brackets_is_just_ignored(self):+ self.assertIsNone(pairing.decode(b"[" * pairing.MAX_DATAGRAM_BYTES))+ self.assertIsNone(pairing.decode(b'{"a":' * 170))++ def test_a_beacon_without_a_version_is_the_old_exchange(self):+ discovery = pairing.Discovery(bind_port=0)+ discovery._note_beacon({"type": "beacon", "name": "OLD-PC", "port": 24820, "pair": "abcd"}, ("127.0.0.1", 24821))+ discovery._note_beacon(pairing.beacon_msg("NEW-PC", 24820, "abcd"), ("127.0.0.2", 24821))+ self.assertEqual({pc["name"]: pc["pairing"] for pc in discovery.pcs()}, {"OLD-PC": 1, "NEW-PC": pairing.PAIRING_VERSION})+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_replay.py b/mac_app/tests/test_replay.pyindex a0c1a97..fea24b7 100644--- a/mac_app/tests/test_replay.py+++ b/mac_app/tests/test_replay.py@@ -52,8 +52,13 @@ def replay(port, data):"""Send `data` as a fresh connection and return every byte the responder sent back before itclosed."""with socket.create_connection(("127.0.0.1", port), timeout=3.0) as attacker:- attacker.sendall(bytes(data))- attacker.shutdown(socket.SHUT_WR)+ # A responder that refuses early closes before the whole recording is sent; what it+ # said before closing is still in the buffer to read.+ try:+ attacker.sendall(bytes(data))+ attacker.shutdown(socket.SHUT_WR)+ except (BrokenPipeError, ConnectionResetError):+ passreply = bytearray()while True:try:diff --git a/mac_app/tests/test_shared_copies.py b/mac_app/tests/test_shared_copies.pyindex ec5e1ad..6e7cd04 100644--- a/mac_app/tests/test_shared_copies.py+++ b/mac_app/tests/test_shared_copies.py@@ -24,7 +24,10 @@ SHARED_MODULES = ("effects.py", "fx_ink.py", "fx_instrument.py", "fx_membrane.py", "fx_sparks.py", "fx_warp.py","ignored.py", "pairing.py", "protocol.py", "receiver.py", "return_edge.py", "updates.py", "wol.py",)-SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py", "test_switch_arrival.py", "test_updates.py")+SHARED_TESTS = (+ "pairing_vectors.json", "test_ignored.py", "test_pairing_cpace.py", "test_shared_copies.py", "test_switch_arrival.py",+ "test_updates.py",+)def _digest(path):diff --git a/win_app/build.spec b/win_app/build.specindex 454377e..5e28fa4 100644--- a/win_app/build.spec+++ b/win_app/build.spec@@ -9,7 +9,7 @@ analysis = Analysis(binaries=[],datas=[(str(source_dir / "Beamer.ico"), "."), (str(source_dir / "assets"), "assets"), (str(source_dir.parent / "VERSION"), ".")],# effects.py imports its fx_* modules by name, which PyInstaller's analysis cannot see.- hiddenimports=["cryptography"] + sorted(path.stem for path in source_dir.glob("fx_*.py")),+ hiddenimports=["cryptography", "nacl", "_cffi_backend"] + sorted(path.stem for path in source_dir.glob("fx_*.py")),hookspath=[],hooksconfig={},runtime_hooks=[],diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pyindex 6c12fc8..eccd33c 100644--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@ -568,7 +568,7 @@ class WindowsApplication(QWidget):returnif message.startswith("Cannot switch"):QApplication.beep()- self.tray.showMessage(title, message, QIcon(str(ICON_PATH)), 4000)+ self.tray.showMessage(title, self._shown(message), QIcon(str(ICON_PATH)), 4000)def _on_mac_learned(self, address: str) -> None:if self._config is None or self._config.mac_hardware_address == address:@@ -1563,6 +1563,8 @@ class WindowsApplication(QWidget):outcome = self.announcer.outcomeif outcome == "refused":self._say_pairing("A wrong code was entered, so that code is cancelled. Pair again for a fresh one.", "note-fault")+ elif outcome == "version":+ self._say_pairing("The Mac runs a different version of Beamer. Update Beamer on both machines, then pair again.", "note-fault")elif outcome == "expired":self._say_pairing("The code expired. Pair again for a fresh one.", "note-amber")elif outcome is None:@@ -2379,7 +2381,7 @@ class WindowsApplication(QWidget):# not connected, or the hooks failing to install -- and stays quiet in the boring case.send_hint = "" if self.sender.redirecting or self._sending_detail in ("Off", "Not connected to the Mac"- ) else self._sending_detail+ ) else self._shown(self._sending_detail)if send_hint != self.send_hint.text():self.send_hint.setText(send_hint)# Hidden while empty, or its spacing leaves a gap between the two switches.diff --git a/win_app/pairing.py b/win_app/pairing.pyindex f733d84..fb0c916 100644--- a/win_app/pairing.py+++ b/win_app/pairing.py@@ -1,16 +1,21 @@"""LAN discovery and pairing, shared by mac_app and win_app (two identical copies; the Mactest suite checks they match byte for byte).-The Windows receiver broadcasts a small UDP beacon -- hostname, Beamer TCP port, and a random-pairing id while a code is on screen -- and the Mac lists what it hears. Pairing then runs as-one datagram each way:-- Mac -> PC pair_request {pair, pub: X25519 public key, proof, name}- PC -> Mac pair_reply {pair, ok, pub: X25519 public key, proof}--Both proofs are HMACs keyed from the six-digit code (scrypt, salted with the pairing id) over-the transcript, so each side shows the other that it knows the code. The shared token is-HKDF over the X25519 secret: an eavesdropper who records every datagram cannot derive it.+The host (the PC) broadcasts a small UDP beacon -- hostname, Beamer TCP port, and a random+pairing id while a code is on screen -- and the requester (the Mac) lists what it hears. Pairing+is then a PAKE with the six-digit code as its password: CPace, draft-irtf-cfrg-cpace-21, suite+CPACE-X25519-SHA512 with initiator and responder roles, followed by the explicit key+confirmation of the draft's section 10.4. Four datagrams:++ requester -> host pair_start {pair, v, nonce, share: Ya, name, id}+ host -> requester pair_answer {pair, ok, share: Yb, tag: Tb, name, id}+ requester -> host pair_confirm {pair, tag: Ta}+ host -> requester pair_done {pair, ok, tag: Td}++Both shares are X25519 public values over a generator derived from the code, so neither says+anything about the code to someone who does not already know it. The shared token is HKDF over+CPace's session key. The full specification is PAIRING.md at the repository root;+tests/pairing_vectors.json holds vectors for every step.Where no broadcast reaches the Mac (another subnet, a VPN), the Mac asks a typed address for itsbeacon with a `find` datagram, and pairing continues exactly as above.@@ -19,18 +24,23 @@ What this protects against, and what it does not:- The token never crosses the wire, and neither does the code. The beacon carries nothing atoken or key could be derived from.-- A wrong code fails closed. The PC consumes its code on the first confirmation it receives,- right or wrong, so one code gives one guess; a fresh code needs a person at the PC to press- Pair a Mac again, and that is the rate limit. Codes expire after CODE_LIFETIME_SECONDS.-- A passive listener can, offline, brute-force the code out of a recorded proof. That is why- the code is single-use and why the key stretching is memory-hard: the code is worthless the- moment it is consumed, and the token does not depend on it anyway.-- An ACTIVE attacker on the LAN during the pairing window is not stopped. One that answers the- Mac's request in the PC's place receives the Mac's proof, can crack the six digits in the- time the code is still valid given enough hardware, and pair with either side as the other.- One that merely sends a junk confirmation burns the code and stops that pairing (a denial,- not a compromise). A six-digit code without a PAKE cannot do better; the scheme trusts the- LAN for the minute the code is on screen, and no longer.+- Nothing on the wire can be tested against a list of codes offline, recorded or live. Whoever+ takes part without the code gets one guess against each side: a host answers only the first+ pair_start a code receives, a requester judges only the first pair_answer to its share, and+ it does not send a code again once an answer to it has failed. These rules are what keep an+ attacker to a guess a side, two chances in a million for a code, so none may be relaxed.+- A wrong code fails closed. The requester checks the host's tag before it sends its own, and+ the host stores a token only after the requester's tag checks out. A fresh code needs a person+ at the PC to press Pair a Mac again, and that is the rate limit. Codes expire after+ CODE_LIFETIME_SECONDS.+- Anyone on the LAN can still stop a pairing: a junk pair_start uses up the code. That is a+ denial, not a compromise.+- The host's address and port still come from the beacon, which nothing authenticates. That+ can point the Mac at the wrong address; it cannot read or forge the link.+- The generator is mapped to the curve in Python integers, which are not constant time. The+ code it depends on is single-use and lives a minute, so there is one computation to time per+ code on the PC and one per attempt on the Mac, and the PC's answer leaves a fixed time after+ the request whatever that computation took."""from __future__ import annotations@@ -46,26 +56,53 @@ import socketimport threadingimport time-from cryptography.hazmat.primitives import hashes, serialization-from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey-from cryptography.hazmat.primitives.kdf.hkdf import HKDF+from nacl.bindings import crypto_scalarmult+from nacl.exceptions import CryptoErrorimport protocol# One home for the port, in the module both apps share byte-for-byte.PAIRING_PORT = protocol.PAIRING_PORTBEACON_VERSION = 1+# The pairing exchange's own version, in every beacon and every pair_start. 1 was the+# scrypt-keyed HMAC proof of 1.4.2 and earlier, which carried no number. There is no fallback+# to it: a version that does not match ends the attempt with ERROR_VERSION.+PAIRING_VERSION = 2BEACON_INTERVAL_SECONDS = 2.0# Three missed beacons: long enough to ride out Wi-Fi hiccups, short enough that a PC that# went to sleep leaves the list before anyone tries it.BEACON_STALE_SECONDS = 7.0+# More PCs than any one network shows, and a ceiling on what forged beacons can make a Mac hold.+MAX_SEEN_HOSTS = 64+# A good pair_answer leaves this long after its pair_start arrived, however long it took to+# make. The generator's arithmetic is not constant time, and this keeps its duration out of+# the one thing a stranger can time: the answer.+PAIR_ANSWER_SECONDS = 0.05CODE_LIFETIME_SECONDS = 60.0+# How long a requester will not send a code again after an answer to it failed: past the code's+# own life, after which a guess at it is worth nothing.+FAILED_CODE_SECONDS = 2 * CODE_LIFETIME_SECONDSCODE_DIGITS = 6MAX_DATAGRAM_BYTES = 1024PAIR_REPLY_TIMEOUT_SECONDS = 1.5PAIR_ATTEMPTS = 3+NONCE_BYTES = 16+SHARE_BYTES = 32+TAG_BYTES = 64+# A name is bound into the exchange as sent, so it is cut before it is sent, never after. 48+# characters keep the largest datagram under MAX_DATAGRAM_BYTES even when JSON escapes each one.+MAX_NAME_CHARS = 48+MAX_IDENTITY_BYTES = 32+# A pairing id is 32 hex characters; 1.4.2's was 8. Anything longer or not ASCII is not one.+MAX_PAIR_ID_CHARS = 64MSG_BEACON = "beacon"+MSG_PAIR_START = "pair_start"+MSG_PAIR_ANSWER = "pair_answer"+MSG_PAIR_CONFIRM = "pair_confirm"+MSG_PAIR_DONE = "pair_done"+# The 1.4.2 exchange's two datagrams. A host still answers the request, with a refusal, so an+# older Mac is told something rather than left to time out.MSG_PAIR_REQUEST = "pair_request"MSG_PAIR_REPLY = "pair_reply"# The Mac asking one address for its beacon, for a PC that no broadcast reaches (another subnet,@@ -74,13 +111,22 @@ MSG_FIND = "find"ERROR_NOT_PAIRING = "not_pairing"ERROR_REFUSED = "refused"+ERROR_VERSION = "version"+_ERRORS = (ERROR_NOT_PAIRING, ERROR_REFUSED, ERROR_VERSION)++# What the exchange binds besides the code. The two roles are fixed by who shows the code; the+# identities are parameters, empty until machines have ids of their own (wire v6), so a later+# version changes what is fed in and nothing else.+ROLE_REQUESTER = b"requester"+ROLE_HOST = b"host"+CHANNEL = b"beamer-pair-v2"+TOKEN_INFO = b"beamer-pair-token-v2"+DONE_LABEL = b"beamer-pair-done"-# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing-# pairing and a mixed-version pair for no gain.-TOKEN_INFO = b"beamy-pair-token"-# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing-# pairing and a mixed-version pair for no gain.-CODE_INFO = b"beamy-pair-code"+_DSI = b"CPace255"+_FIELD_PRIME = 2**255 - 19+_CURVE_A = 486662+_SHA512_BLOCK_BYTES = 128class PairingError(Exception):@@ -91,20 +137,6 @@ def new_code() -> str:return "".join(secrets.choice("0123456789") for _ in range(CODE_DIGITS))-def _code_key(code: str, pair_id: str) -> bytes:- # scrypt rather than HKDF on purpose: a recorded proof lets anyone try all million codes- # offline, and 32MB per guess is what keeps that from finishing inside the code's minute.- # maxmem is explicit because OpenSSL's default is exactly the 32MiB this needs, and it- # refuses at the boundary.- return hashlib.scrypt(- code.encode("utf-8"), salt=pair_id.encode("utf-8") + CODE_INFO, n=2**15, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024- )---def _proof(key: bytes, role: bytes, pair_id: str, mac_pub: bytes, pc_pub: bytes = b"") -> bytes:- return hmac.new(key, role + pair_id.encode("utf-8") + mac_pub + pc_pub, hashlib.sha256).digest()--def _b64(data: bytes) -> str:return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")@@ -113,18 +145,101 @@ def _unb64(text: str) -> bytes:if not isinstance(text, str):raise PairingError("expected base64 text")try:- return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))except ValueError as exc:raise PairingError("bad base64") from exc+ # The decoder skips what it does not know, so several spellings give the same bytes. Only+ # the one _b64 writes is taken: a field then has one form on the wire on every platform.+ if _b64(data) != text:+ raise PairingError("bad base64")+ return data+++def _prepend_len(data: bytes) -> bytes:+ """The draft's prepend_len: the length as LEB128, then the bytes."""+ length = len(data)+ encoded = bytearray()+ while True:+ encoded.append(length & 0x7F if length < 128 else (length & 0x7F) | 0x80)+ length >>= 7+ if length == 0:+ return bytes(encoded) + data+++def _lv_cat(*parts: bytes) -> bytes:+ return b"".join(_prepend_len(part) for part in parts)+++def _elligator2(r: int) -> int:+ """The u coordinate Elligator 2 maps a field element to on Curve25519 (RFC 9380 6.7.1 with+ Z = 2, as the draft's appendix A.5 repeats it)."""+ p = _FIELD_PRIME+ v = -_CURVE_A * pow(1 + 2 * r * r, p - 2, p) % p+ square = pow((v * v * v + _CURVE_A * v * v + v) % p, (p - 1) // 2, p) == 1+ return v if square else (-v - _CURVE_A) % p+++def _generator(prs: bytes, channel: bytes, sid: bytes) -> bytes:+ """The draft's calculate_generator for G_X25519 with SHA-512 (sections 8.1 and 8.2)."""+ padding = bytes(max(0, _SHA512_BLOCK_BYTES - 1 - len(_prepend_len(prs)) - len(_prepend_len(_DSI))))+ digest = hashlib.sha512(_lv_cat(_DSI, prs, padding, channel, sid)).digest()[:SHARE_BYTES]+ r = int.from_bytes(digest, "little") & ((1 << 255) - 1)+ return _elligator2(r).to_bytes(SHARE_BYTES, "little")+++def _x25519(scalar: bytes, point: bytes) -> bytes:+ """X25519 (RFC 7748), refusing a point that lands on the neutral element: the draft's+ scalar_mult_vfy, which MUST abort there. libsodium reports exactly that case as an error."""+ try:+ product = crypto_scalarmult(scalar, point)+ except CryptoError as exc:+ raise PairingError(ERROR_REFUSED) from exc+ if product == bytes(SHARE_BYTES):+ raise PairingError(ERROR_REFUSED)+ return product+++def _hkdf(key_material: bytes, salt: bytes, info: bytes) -> bytes:+ """HKDF-SHA256 (RFC 5869) for one 32-byte block."""+ extracted = hmac.new(salt, key_material, hashlib.sha256).digest()+ return hmac.new(extracted, info + b"\x01", hashlib.sha256).digest()+++def _session_id(pair_id: str, nonce: bytes) -> bytes:+ # Random bytes from both ends, as the draft recommends for sid: the host's in the pairing+ # id, the requester's in its nonce.+ return _lv_cat(pair_id.encode("utf-8"), nonce)+++def _party(role: bytes, identity: bytes, name: str) -> bytes:+ """One side's associated data: CPace's ADa or ADb. The role comes first, so the two sides'+ can never be equal, which is what stops a tag being reflected back at its sender."""+ return _lv_cat(role, identity, name.encode("utf-8"))+++def _share(code: str, sid: bytes, scalar: bytes) -> bytes:+ return _x25519(scalar, _generator(code.encode("utf-8"), CHANNEL, sid))-def _public_bytes(key) -> bytes:- return key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)+def _keys(sid: bytes, shared: bytes, ya: bytes, ada: bytes, yb: bytes, adb: bytes) -> tuple:+ """(token, Ta, Tb, Td) for one exchange, from the secret the two shares agree. Ta and Tb are+ the draft's tags over each side's own message; Td is the host's receipt."""+ isk = hashlib.sha512(_lv_cat(_DSI + b"_ISK", sid, shared) + _lv_cat(ya, ada) + _lv_cat(yb, adb)).digest()+ mac_key = hashlib.sha512(b"CPaceMac" + sid + isk).digest()+ def tag(message: bytes) -> bytes:+ return hmac.new(mac_key, message, hashlib.sha512).digest()-def derive_token(private_key, peer_public: bytes, pair_id: str) -> str:- shared = private_key.exchange(X25519PublicKey.from_public_bytes(peer_public))- return _b64(HKDF(algorithm=hashes.SHA256(), length=32, salt=pair_id.encode("utf-8"), info=TOKEN_INFO).derive(shared))+ return _b64(_hkdf(isk, sid, TOKEN_INFO)), tag(_lv_cat(ya, ada)), tag(_lv_cat(yb, adb)), tag(_lv_cat(DONE_LABEL))+++def _failure(kind: str, pair_id: str, error: str) -> dict:+ return {"type": kind, "pair": pair_id, "ok": False, "error": error}+++def _error_of(reply: dict) -> str:+ error = reply.get("error")+ return error if error in _ERRORS else ERROR_REFUSEDdef encode(message: dict) -> bytes:@@ -139,7 +254,9 @@ def decode(data: bytes):return Nonetry:message = json.loads(data.decode("utf-8"))- except (UnicodeDecodeError, ValueError):+ except (UnicodeDecodeError, ValueError, RecursionError):+ # RecursionError is what a datagram of nothing but brackets raises on some Pythons, and+ # left uncaught it would end the socket loop that called this.return Noneif not isinstance(message, dict) or message.get("beamy") != BEACON_VERSION:return None@@ -147,25 +264,34 @@ def decode(data: bytes):def beacon_msg(name: str, port: int, pair_id: str = None) -> dict:- message = {"type": MSG_BEACON, "name": name, "port": int(port)}+ message = {"type": MSG_BEACON, "name": name, "port": int(port), "pairing": PAIRING_VERSION}if pair_id:message["pair"] = pair_idreturn messageclass PairingHost:- """The PC's half: holds at most one live code and answers pair requests. Pure -- the- Announcer owns the socket and the clock is injected for the tests."""+ """The PC's half: holds at most one live code and answers the exchange. Pure -- the+ Announcer owns the socket, and the clock and the randomness are injected for the tests and+ the vectors."""- def __init__(self, clock=time.monotonic):+ def __init__(self, clock=time.monotonic, name: str = "", identity: bytes = b"", entropy=secrets.token_bytes):self.clock = clock+ self.name = name[:MAX_NAME_CHARS]+ self.identity = identity+ self._entropy = entropyself.code = Noneself.pair_id = Noneself.expires_at = 0.0+ # The one pair_start this code answered, as a dict; None until it arrives.+ self._bound = Noneself._last = None+ # True once a pair_answer has just been worked out from the code, until the caller that+ # sends it takes note. A retransmit's answer comes from memory and leaves it False.+ self.fresh_answer = Falseself.paired = None- # How the last code ended -- "paired", "refused" or "expired" -- for the window to say- # so; None while a code is live or after a deliberate cancel.+ # How the last code ended -- "paired", "refused", "version" or "expired" -- for the+ # window to say so; None while a code is live or after a deliberate cancel.self.outcome = None@property@@ -184,9 +310,11 @@ class PairingHost:def begin(self) -> str:self.code = new_code()- self.pair_id = secrets.token_hex(4)+ self.pair_id = self._entropy(16).hex()self.expires_at = self.clock() + CODE_LIFETIME_SECONDS+ self._bound = Noneself._last = None+ self.fresh_answer = Falseself.outcome = Nonereturn self.code@@ -194,86 +322,208 @@ class PairingHost:self.code = Noneself.pair_id = Noneself.expires_at = 0.0+ self._bound = Noneself.outcome = Nonedef handle(self, message: dict):"""The reply to one datagram, or None when it deserves no answer. A successful pairing- leaves the token in `self.paired` as (token, mac_name); the caller stores it."""- if message.get("type") != MSG_PAIR_REQUEST:- return None+ leaves the token in `self.paired` as (token, requester_name); the caller stores it."""+ kind = message.get("type")pair_id = message.get("pair")- if not isinstance(pair_id, str):+ # Every reply echoes the pairing id, so one that is not shaped like an id gets none: a+ # reply is then never much larger than the datagram that drew it.+ if not isinstance(pair_id, str) or not pair_id.isascii() or not 0 < len(pair_id) <= MAX_PAIR_ID_CHARS:return None- if self._last is not None and self._last[0] == (pair_id, message.get("pub"), message.get("proof")):- # A lost reply makes the Mac send the same request again; answer it the same way,- # so a retransmit is not read as a second attempt.+ if kind == MSG_PAIR_START:+ return self._start(message, pair_id)+ if kind == MSG_PAIR_CONFIRM:+ return self._confirm(message, pair_id)+ if kind == MSG_PAIR_REQUEST:+ return self._outdated(pair_id)+ return None++ def _start(self, message: dict, pair_id: str) -> dict:+ sent = [message.get(field) for field in ("pair", "v", "nonce", "share", "name", "id")]+ if self._last is not None and self._last[0] == sent:+ # A lost reply makes the requester send the same datagram again; answer it the same+ # way, so a retransmit is not read as a second attempt.return self._last[1]if not self.active or pair_id != self.pair_id:- return {"type": MSG_PAIR_REPLY, "pair": pair_id, "ok": False, "error": ERROR_NOT_PAIRING}- code, self.code = self.code, None+ return _failure(MSG_PAIR_ANSWER, pair_id, ERROR_NOT_PAIRING)+ if self._bound is not None:+ if self._bound["sent"] == sent:+ return self._bound["answer"]+ # One code answers one share. A second answer would hand whoever sent it a second+ # guess at the code, so it is refused, and the exchange already under way is left+ # alone rather than cancelled by a stranger's datagram.+ return _failure(MSG_PAIR_ANSWER, pair_id, ERROR_REFUSED)+ if message.get("v") != PAIRING_VERSION:+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_VERSION, "version")try:- mac_pub = _unb64(message.get("pub"))- proof = _unb64(message.get("proof"))- X25519PublicKey.from_public_bytes(mac_pub)- except (PairingError, ValueError):- return self._refuse(message, pair_id)- key = _code_key(code, pair_id)- if not hmac.compare_digest(proof, _proof(key, b"mac", pair_id, mac_pub)):- return self._refuse(message, pair_id)- private_key = X25519PrivateKey.generate()- pc_pub = _public_bytes(private_key)- name = message.get("name")- self.paired = (derive_token(private_key, mac_pub, pair_id), name if isinstance(name, str) else "")- reply = {- "type": MSG_PAIR_REPLY,+ nonce = _unb64(message.get("nonce"))+ share = _unb64(message.get("share"))+ identity = _unb64(message.get("id"))+ name = message.get("name")+ if (+ len(nonce) != NONCE_BYTES+ or len(share) != SHARE_BYTES+ or len(identity) > MAX_IDENTITY_BYTES+ or not isinstance(name, str)+ or len(name) > MAX_NAME_CHARS+ ):+ raise PairingError(ERROR_REFUSED)+ sid = _session_id(pair_id, nonce)+ scalar = self._entropy(SHARE_BYTES)+ requester = _party(ROLE_REQUESTER, identity, name)+ host = _party(ROLE_HOST, self.identity, self.name)+ # Everything that can refuse this datagram is settled before the code is touched:+ # a refusal goes back at once, and must not carry the time the generator took.+ shared = _x25519(scalar, share)+ except (PairingError, UnicodeError):+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_REFUSED, "refused")+ try:+ own = _share(self.code, sid, scalar)+ except PairingError:+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_REFUSED, "refused")+ token, requester_tag, host_tag, done_tag = _keys(sid, shared, share, requester, own, host)+ self.fresh_answer = True+ answer = {+ "type": MSG_PAIR_ANSWER,"pair": pair_id,"ok": True,- "pub": _b64(pc_pub),- "proof": _b64(_proof(key, b"pc", pair_id, mac_pub, pc_pub)),+ "share": _b64(own),+ "tag": _b64(host_tag),+ "name": self.name,+ "id": _b64(self.identity),+ }+ self._bound = {+ "sent": sent,+ "answer": answer,+ "requester_tag": requester_tag,+ "done_tag": done_tag,+ "token": token,+ "name": name,}- self._last = ((pair_id, message.get("pub"), message.get("proof")), reply)+ return answer++ def _confirm(self, message: dict, pair_id: str) -> dict:+ sent = [pair_id, message.get("tag")]+ if self._last is not None and self._last[0] == sent:+ return self._last[1]+ if not self.active or pair_id != self.pair_id or self._bound is None:+ return _failure(MSG_PAIR_DONE, pair_id, ERROR_NOT_PAIRING)+ bound = self._bound+ try:+ tag = _unb64(message.get("tag"))+ except PairingError:+ tag = b""+ if not hmac.compare_digest(tag, bound["requester_tag"]):+ return self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_REFUSED, "refused")+ self.paired = (bound["token"], bound["name"])+ reply = {"type": MSG_PAIR_DONE, "pair": pair_id, "ok": True, "tag": _b64(bound["done_tag"])}+ self._last = (sent, reply)self.cancel()self.outcome = "paired"return reply- def _refuse(self, message: dict, pair_id: str) -> dict:- reply = {"type": MSG_PAIR_REPLY, "pair": pair_id, "ok": False, "error": ERROR_REFUSED}- self._last = ((pair_id, message.get("pub"), message.get("proof")), reply)+ def _outdated(self, pair_id: str) -> dict:+ """A 1.4.2 Mac's request. It is answered in the datagram that Mac reads, and the code+ goes, because its window then says the PC cancelled it."""+ if self.active and pair_id == self.pair_id and self._bound is None:+ self.cancel()+ self.outcome = "version"+ return _failure(MSG_PAIR_REPLY, pair_id, ERROR_REFUSED)+ return _failure(MSG_PAIR_REPLY, pair_id, ERROR_REFUSED if self.active else ERROR_NOT_PAIRING)++ def _end(self, kind: str, sent: list, pair_id: str, error: str, outcome: str) -> dict:+ reply = _failure(kind, pair_id, error)+ self._last = (sent, reply)self.cancel()- self.outcome = "refused"+ self.outcome = outcomereturn replyclass PairingClient:- """The Mac's half of one attempt: builds the request, checks the reply, yields the token."""+ """The Mac's half of one attempt: builds the start, checks the answer, confirms, and yields+ the token once the host says it has stored it."""- def __init__(self, pair_id: str, code: str, name: str):+ def __init__(self, pair_id: str, code: str, name: str, identity: bytes = b"", entropy=secrets.token_bytes):self.pair_id = pair_id- self.name = name- self._private_key = X25519PrivateKey.generate()- self._pub = _public_bytes(self._private_key)- self._key = _code_key(code, pair_id)-- def request(self) -> dict:+ self.name = name[:MAX_NAME_CHARS]+ self.identity = identity+ self._nonce = entropy(NONCE_BYTES)+ self._sid = _session_id(pair_id, self._nonce)+ self._scalar = entropy(SHARE_BYTES)+ self._share = _share(code, self._sid, self._scalar)+ self._answered = False+ self._token = None+ self._done_tag = None+ # The host's name and identity as the exchange bound them; None until its tag checks out.+ self.host_name = None+ self.host_identity = None++ def start(self) -> dict:return {- "type": MSG_PAIR_REQUEST,+ "type": MSG_PAIR_START,"pair": self.pair_id,- "pub": _b64(self._pub),- "proof": _b64(_proof(self._key, b"mac", self.pair_id, self._pub)),+ "v": PAIRING_VERSION,+ "nonce": _b64(self._nonce),+ "share": _b64(self._share),"name": self.name,+ "id": _b64(self.identity),}- def accept(self, reply: dict) -> str:- """The agreed token, or PairingError naming why not."""- if reply.get("type") != MSG_PAIR_REPLY or reply.get("pair") != self.pair_id:+ def accept(self, answer: dict) -> dict:+ """The pair_confirm to send back, or PairingError naming why not. It judges one answer+ and no more: each answer it judged would be another guess at the code for whoever is+ answering."""+ if answer.get("type") != MSG_PAIR_ANSWER or answer.get("pair") != self.pair_id:raise PairingError("not a reply to this attempt")- if reply.get("ok") is not True:- raise PairingError(reply.get("error") if reply.get("error") in (ERROR_NOT_PAIRING, ERROR_REFUSED) else ERROR_REFUSED)- pc_pub = _unb64(reply.get("pub"))- proof = _unb64(reply.get("proof"))- if not hmac.compare_digest(proof, _proof(self._key, b"pc", self.pair_id, self._pub, pc_pub)):+ if self._answered:raise PairingError(ERROR_REFUSED)- return derive_token(self._private_key, pc_pub, self.pair_id)+ self._answered = True+ if answer.get("ok") is not True:+ raise PairingError(_error_of(answer))+ try:+ share = _unb64(answer.get("share"))+ tag = _unb64(answer.get("tag"))+ identity = _unb64(answer.get("id"))+ name = answer.get("name")+ if len(share) != SHARE_BYTES or len(identity) > MAX_IDENTITY_BYTES or not isinstance(name, str) or len(name) > MAX_NAME_CHARS:+ raise PairingError(ERROR_REFUSED)+ requester = _party(ROLE_REQUESTER, self.identity, self.name)+ host = _party(ROLE_HOST, identity, name)+ shared = _x25519(self._scalar, share)+ token, requester_tag, host_tag, done_tag = _keys(self._sid, shared, self._share, requester, share, host)+ except (PairingError, UnicodeError) as exc:+ raise PairingError(ERROR_REFUSED) from exc+ if not hmac.compare_digest(tag, host_tag):+ raise PairingError(ERROR_REFUSED)+ self._token = token+ self._done_tag = done_tag+ self.host_name = name+ self.host_identity = identity+ return {"type": MSG_PAIR_CONFIRM, "pair": self.pair_id, "tag": _b64(requester_tag)}++ def abort(self) -> dict:+ """What to send a host whose answer failed: a confirmation that cannot pass, so the PC+ drops the code and says a wrong one was entered instead of showing it for the rest of+ its minute."""+ return {"type": MSG_PAIR_CONFIRM, "pair": self.pair_id, "tag": ""}++ def finish(self, done: dict) -> str:+ """The agreed token, once the host's pair_done proves it stored the same one."""+ if done.get("type") != MSG_PAIR_DONE or done.get("pair") != self.pair_id or self._token is None:+ raise PairingError("not a reply to this attempt")+ if done.get("ok") is not True:+ raise PairingError(_error_of(done))+ try:+ tag = _unb64(done.get("tag"))+ except PairingError as exc:+ raise PairingError(ERROR_REFUSED) from exc+ if not hmac.compare_digest(tag, self._done_tag):+ raise PairingError(ERROR_REFUSED)+ return self._tokendef _udp_socket(bind_port: int) -> socket.socket:@@ -352,7 +602,7 @@ class Announcer:self.bind_port = bind_portself.announce_to = announce_toself.name = name or machine_name()- self.host = PairingHost()+ self.host = PairingHost(name=self.name)self._lock = threading.Lock()self._stop = threading.Event()self._thread = None@@ -401,6 +651,22 @@ class Announcer:pair_id = self.host.pair_id if self.host.active else Nonereturn encode(beacon_msg(self.name, self.port_getter(), pair_id))+ @staticmethod+ def _due(last: dict, host: str, now: float) -> bool:+ """Whether `host` may be sent another datagram of a rationed kind, noting it if so."""+ interval = BEACON_INTERVAL_SECONDS / 4+ if now - last.get(host, -BEACON_INTERVAL_SECONDS) < interval:+ return False+ if len(last) > 256:+ # Only what has lapsed is forgotten. Emptying the table would let a burst from+ # made-up addresses wipe the record of the one being aimed at.+ for lapsed in [known for known, sent in last.items() if now - sent >= interval]:+ del last[lapsed]+ if len(last) > 256:+ return False+ last[host] = now+ return True+def _run(self) -> None:try:sock = _udp_socket(self.bind_port)@@ -411,6 +677,7 @@ class Announcer:self.error = Nonenext_beacon = 0.0answered = {}+ refused = {}try:while not self._stop.is_set():now = time.monotonic()@@ -448,24 +715,35 @@ class Announcer:self.error = str(exc)self.logger.error("pairing beacon stopped: %s", exc)break+ arrived = time.monotonic()message = decode(data)if message is None:continueif message.get("type") == MSG_FIND:# At most one answer per address per interval, so the port is no amplifier.- if now - answered.get(address[0], -BEACON_INTERVAL_SECONDS) >= BEACON_INTERVAL_SECONDS / 4:- if len(answered) > 256:- answered.clear()- answered[address[0]] = now+ if self._due(answered, address[0], arrived):try:sock.sendto(self._beacon(), address)except OSError as exc:self.logger.warning("beacon to %s not sent: %s", address[0], exc)continuewith self._lock:- reply = self.host.handle(message)+ try:+ reply = self.host.handle(message)+ except Exception:+ # Whatever one datagram does, the next beacon still goes out.+ self.logger.exception("pairing datagram dropped")+ reply = Nonepaired, self.host.paired = self.host.paired, None- if reply is not None:+ fresh, self.host.fresh_answer = self.host.fresh_answer, False+ # A refusal is larger than the smallest datagram that draws one, so it is rationed+ # the same way. A requester that misses one asks again after its own timeout.+ if reply is not None and (reply.get("ok") is True or self._due(refused, address[0], arrived)):+ if fresh:+ # Only the answer just worked out from the code is held back. A+ # retransmit's comes from memory, and holding each of those would let a+ # stream of replays stall this loop.+ self._stop.wait(max(0.0, arrived + PAIR_ANSWER_SECONDS - time.monotonic()))try:sock.sendto(encode(reply), address)except OSError as exc:@@ -493,7 +771,11 @@ class Discovery:self.clock = clockself._lock = threading.Lock()self._seen = {}- self._replies = queue.Queue()+ self._replies = queue.Queue(maxsize=64)+ self._awaiting = None+ self._pairing = threading.Lock()+ # Codes an answer has failed under, each with the time it may be tried again.+ self._failed = {}self._stop = threading.Event()self._thread = Noneself._sock = None@@ -542,7 +824,8 @@ class Discovery:self._thread = Nonedef pcs(self) -> list:- """Every PC heard from recently: dicts of name, address, port, reply_port, pairing."""+ """Every PC heard from recently: dicts of name, address, port, reply_port, pair_id and+ pairing, the version of the exchange it speaks."""cutoff = self.clock() - BEACON_STALE_SECONDSwith self._lock:stale = [key for key, entry in self._seen.items() if entry["seen_at"] < cutoff]@@ -553,22 +836,68 @@ class Discovery:key=lambda entry: (entry["name"].lower(), entry["address"]),)- def pair(self, pc: dict, code: str, name: str = None) -> str:- """Runs the exchange with `pc` (an entry from pcs()) and returns the token. Blocks for- up to PAIR_ATTEMPTS replies' worth; call it off the main thread."""+ def pair(self, pc: dict, code: str, name: str = None) -> tuple:+ """Runs the exchange with `pc` (an entry from pcs()) and returns (token, host_name),+ the name being the one the exchange proved. Blocks for up to PAIR_ATTEMPTS replies'+ worth, once for the answer and once for the receipt; call it off the main thread."""sock = self._sockif sock is None:raise PairingError("discovery is not running")- client = PairingClient(pc["pair_id"], code, name or machine_name())+ if pc.get("pairing") != PAIRING_VERSION:+ # Said here, before anything is sent: there is no older exchange to fall back to.+ raise PairingError(ERROR_VERSION)+ if not isinstance(pc.get("pair_id"), str):+ raise PairingError(ERROR_NOT_PAIRING)target = (pc["address"], pc["reply_port"])- while True:+ if not self._pairing.acquire(blocking=False):+ # One attempt at a time: a second would take the first one's replies, and could+ # slip past the record of failed codes below.+ raise PairingError("busy")+ try:+ now = self.clock()+ self._failed = {failed: until for failed, until in self._failed.items() if until > now}+ if code in self._failed:+ # An answer to this code was judged and failed, so whoever answered has had a+ # guess at it. The real host has bound the code to that attempt or dropped it;+ # sending another share would pair with nobody and only buy the answerer a+ # second guess. It is the code that is remembered, not the pairing id, which a+ # beacon can forge.+ raise PairingError(ERROR_REFUSED)+ client = PairingClient(pc["pair_id"], code, name or machine_name())+ while True:+ try:+ self._replies.get_nowait()+ except queue.Empty:+ break+ self._awaiting = (target[0], client.pair_id)+ answer = self._ask(sock, target, client.pair_id, client.start(), MSG_PAIR_ANSWER)try:- self._replies.get_nowait()- except queue.Empty:- break- request = encode(client.request())+ confirm = client.accept(answer)+ except PairingError:+ # Only an answer that claimed to be good can have tested a guess. A refusal+ # tests nothing, and a stale pairing id draws one from an honest PC.+ if answer.get("ok") is True:+ self._failed[code] = self.clock() + FAILED_CODE_SECONDS+ try:+ sock.sendto(encode(client.abort()), target)+ except OSError:+ pass+ raise+ token = client.finish(self._ask(sock, target, client.pair_id, confirm, MSG_PAIR_DONE))+ return token, client.host_name+ finally:+ self._awaiting = None+ self._pairing.release()++ def _ask(self, sock, target, pair_id: str, message: dict, reply_type: str) -> dict:+ """Sends one datagram until the first reply of `reply_type` from `target` comes back.+ The first one decides: the caller judges it and never waits for a better one."""+ datagram = encode(message)for _attempt in range(PAIR_ATTEMPTS):- sock.sendto(request, target)+ try:+ sock.sendto(datagram, target)+ except OSError as exc:+ raise PairingError("no_answer") from excdeadline = self.clock() + PAIR_REPLY_TIMEOUT_SECONDSwhile True:remaining = deadline - self.clock()@@ -578,9 +907,9 @@ class Discovery:reply, address = self._replies.get(timeout=remaining)except queue.Empty:break- if address[0] != target[0] or reply.get("pair") != client.pair_id:+ if address[0] != target[0] or reply.get("pair") != pair_id or reply.get("type") != reply_type:continue- return client.accept(reply)+ return replyraise PairingError("no_answer")def _run(self) -> None:@@ -612,9 +941,17 @@ class Discovery:continuekind = message.get("type")if kind == MSG_BEACON:- self._note_beacon(message, address)- elif kind == MSG_PAIR_REPLY:- self._replies.put((message, address))+ try:+ self._note_beacon(message, address)+ except Exception:+ self.logger.exception("beacon dropped")+ elif kind in (MSG_PAIR_ANSWER, MSG_PAIR_DONE) and self._awaiting == (address[0], message.get("pair")):+ # Only what the attempt under way is waiting for is kept, and only so much+ # of it, so nothing a stranger sends piles up in memory.+ try:+ self._replies.put_nowait((message, address))+ except queue.Full:+ passexcept Exception as exc:self.error = str(exc)self.logger.exception("discovery stopped")@@ -637,15 +974,36 @@ class Discovery:name = message.get("name")port = message.get("port")pair_id = message.get("pair")+ version = message.get("pairing")if not isinstance(name, str) or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:return+ try:+ name.encode("utf-8")+ except UnicodeError:+ # Half a surrogate pair is JSON a parser accepts and text no window can show.+ returnentry = {"name": name[:64] or address[0],"address": address[0],"port": port,"reply_port": address[1],- "pair_id": pair_id if isinstance(pair_id, str) and pair_id else None,+ "pair_id": pair_id if isinstance(pair_id, str) and pair_id.isascii() and 0 < len(pair_id) <= MAX_PAIR_ID_CHARS else None,+ # A beacon from 1.4.2 or earlier carries no number: that is version 1.+ "pairing": version if isinstance(version, int) and not isinstance(version, bool) else 1,"seen_at": self.clock(),}with self._lock:+ if address[0] not in self._seen and len(self._seen) >= MAX_SEEN_HOSTS:+ # The list is only read while the window is open, so what has gone quiet is+ # cleared here too. Beacons from made-up addresses then cost a fixed amount of+ # memory and no more.+ cutoff = self.clock() - BEACON_STALE_SECONDS+ for stale in [key for key, known in self._seen.items() if known["seen_at"] < cutoff]:+ del self._seen[stale]+ if len(self._seen) >= MAX_SEEN_HOSTS:+ # Still full: whoever has been quiet longest gives way. A flood of forgeries+ # can crowd real PCs off the list that way, which is a denial like any+ # other here, so the one address the user typed is never the one to go.+ wanted = self._finding[0] if self._finding else None+ del self._seen[min((key for key in self._seen if key != wanted), key=lambda key: self._seen[key]["seen_at"])]self._seen[address[0]] = entrydiff --git a/win_app/receiver.py b/win_app/receiver.pyindex 4b063e8..ea1a8af 100644--- a/win_app/receiver.py+++ b/win_app/receiver.py@@ -29,6 +29,7 @@ ACK_IDLE_SECONDS = 0.4ACK_COALESCE_SECONDS = 0.015HELLO_TIMEOUT_SECONDS = 5.0SESSION_READ_TIMEOUT_SECONDS = 2.5+LOCK_CHECK_SECONDS = 0.5INJECTION_ERROR_STATUS_INTERVAL_SECONDS = 5.0# Windows hands the port back only when whatever holds it lets go — WinNAT's# dynamic reservations move on every reboot and can land on ours — so a bind@@ -236,6 +237,15 @@ class ReceiverServer:# seconds, and replaying seconds of stale mouse moves and keystrokes# onto the desktop the moment it appears is worse than losing them.self._unlocking = threading.Event()+ # When the console was last tested for the lock screen and first seen on it while the peer+ # drives this PC, and whether its input has been sent home for that lock. See+ # _home_if_locked.+ self._lock_checked_at = float("-inf")+ self._locked_since = None+ self._sent_home_for_lock = False+ # Set from the moment a focus brings the peer's input here until the unlock it may need+ # has been asked for, so the lock check cannot act in between. See _handle_focus.+ self._arriving = threading.Event()# `clipboard` defaults to the real clipboard_win module, imported# lazily (not at module load) so receiver.py stays importable -- and# its non-clipboard logic testable -- on a machine without@@ -685,12 +695,44 @@ class ReceiverServer:client_stop.set()self._close_socket(connection)return+ self._home_if_locked()except Exception as exc:LOGGER.exception("ACK thread failed")self._set_status(ServerState.ERROR, f"ACK worker failed: {exc}")client_stop.set()self._close_socket(connection)+ def _home_if_locked(self) -> None:+ """Send the peer's input home when this PC is on its lock screen. Beamer can neither inject+ into the secure desktop nor watch the return edge there, so a Mac left driving a locked PC+ had no way back until someone unlocked it by hand (issue #5).++ Timed, not per tick: the ACK thread wakes on every injected event, and is_locked walks the+ process list. Locked on two checks LOCK_CHECK_SECONDS apart, and never while an unlock is+ in flight: a switch to a locked PC reaches _begin_unlock a moment after focus, and an+ unlock provider that can clear the lock screen must be given the chance."""+ if not self._peer_driving or self._unlocking.is_set() or self._arriving.is_set():+ self._locked_since = None+ return+ now = time.monotonic()+ if now - self._lock_checked_at < LOCK_CHECK_SECONDS:+ return+ self._lock_checked_at = now+ try:+ locked = self._unlock_module().is_locked() is True+ except Exception:+ locked = False+ if not locked:+ self._locked_since = None+ return+ if self._locked_since is None:+ self._locked_since = now+ return+ if self._sent_home_for_lock:+ return+ LOGGER.info("Windows is locked while the %s drives it; sending its input home", self._peer_name)+ self._sent_home_for_lock = self.send_home()+def _clipboard_module(self):if self._clipboard is not None:return self._clipboard@@ -816,6 +858,9 @@ class ReceiverServer:returnif target == self._self_target:self._peer_driving = True+ self._sent_home_for_lock = False+ # A lock seen on the last visit says nothing about this one.+ self._locked_since = Noneelif target == self._peer_target:self._peer_driving = Falsetry:@@ -1013,12 +1058,21 @@ class ReceiverServer:# chord with the first local keystroke.self._drop_return()self._release_peer_keys()- self._notify_focus(target)if target == self._self_target:- self._arm_return(data)- self._place_pointer(data)- self._begin_unlock(peer, host)+ # Raised before anyone hears the peer is driving, and held until the unlock has been+ # asked for. Placing the pointer or an owner's callback can take a second, and in+ # that second the lock check saw a locked PC with the peer driving and sent its+ # input home before the provider that could have unlocked it was tried.+ self._arriving.set()+ try:+ self._notify_focus(target)+ self._arm_return(data)+ self._place_pointer(data)+ self._begin_unlock(peer, host)+ finally:+ self._arriving.clear()return+ self._notify_focus(target)if target != self._peer_target:returnclipboard = self._clipboard_module()diff --git a/win_app/requirements-win.txt b/win_app/requirements-win.txtindex 75c91de..6341dae 100644--- a/win_app/requirements-win.txt+++ b/win_app/requirements-win.txt@@ -2,3 +2,4 @@ PySide6-Essentials>=6.11.1pyinstaller>=6.0pyinstaller-hooks-contrib>=2024.1cryptography>=42+PyNaCl>=1.6diff --git a/win_app/tests/pairing_vectors.json b/win_app/tests/pairing_vectors.jsonnew file mode 100644index 0000000..7426de5--- /dev/null+++ b/win_app/tests/pairing_vectors.json@@ -0,0 +1,252 @@+{+ "$comment": "Hex is bytes in wire order, except the two elligator2 fields, which are integers printed big-endian as RFC 9380 prints them. Messages are shown before the \"beamy\": 1 every datagram adds.",+ "suite": "CPACE-X25519-SHA512, draft-irtf-cfrg-cpace-21, initiator-responder, key confirmation per section 10.4",+ "specification": "PAIRING.md",+ "pairing_version": 2,+ "constants": {+ "dsi_ascii": "CPace255",+ "channel_ascii": "beamer-pair-v2",+ "role_requester_ascii": "requester",+ "role_host_ascii": "host",+ "token_info_ascii": "beamer-pair-token-v2",+ "done_label_ascii": "beamer-pair-done",+ "nonce_bytes": 16,+ "max_name_chars": 48,+ "max_identity_bytes": 32+ },+ "cpace_draft": {+ "prs_ascii": "Password",+ "ci_hex": "0b415f696e69746961746f720b425f726573706f6e646572",+ "sid_hex": "7e4b4791d6a8ef019b936c79fb7f2c57",+ "generator_hex": "d04bf6d41f6a289632a2e929fa29bebd51092512a7829fdde7d314b62f05a73f",+ "ada_ascii": "ADa",+ "ya_scalar_hex": "21b4f4bd9e64ed355c3eb676a28ebedaf6d8f17bdc365995b319097153044080",+ "ya_hex": "1d13c89278cdadd826f6d8d7f887701430f8380ddc17611cdd6dc989ce0c9f32",+ "adb_ascii": "ADb",+ "yb_scalar_hex": "848b0779ff415f0af4ea14df9dd1d3c29ac41d836c7808896c4eba19c51ac40a",+ "yb_hex": "248cccf6d5cdc3646f0ad593f9e6cef4e69d4945f8372e623512ecea32185623",+ "k_hex": "5b067effbdc0b2a0e1d907b21ebb25cfedb96a852179a847c37e43ee71322c6b",+ "isk_hex": "6e19b875f7a561d6b3ca3dbb9ef42ac55de3e717881018204b8922b4d5e53bb2aa82c300bea7b65d2b671da71922ddf6472301b79bc270adfa8bf413285f2263"+ },+ "elligator2": [+ {+ "field_element_hex_be": "608d892b641f0328523802a6603427c26e55e6f27e71a91a478148d45b5093cd",+ "u_hex_be": "51125222da5e763d97f3c10fcc92ea6860b9ccbbd2eb1285728f566721c1e65b"+ },+ {+ "field_element_hex_be": "46f5b22494bfeaa7f232cc8d054be68561af50230234d7d1d63d1d9abeca8da5",+ "u_hex_be": "7d56d1e08cb0ccb92baf069c18c49bb5a0dcd927eff8dcf75ca921ef7f3e6eeb"+ },+ {+ "field_element_hex_be": "235fe40c443766ce7e18111c33862d66c3b33267efa50d50f9e8e5d252a40aaa",+ "u_hex_be": "3fbe66b9c9883d79e8407150e7c2a1c8680bee496c62fabe4619a72b3cabe90f"+ },+ {+ "field_element_hex_be": "001e92a544463bda9bd04ddbe3d6eed248f82de32f522669efc5ddce95f46f5b",+ "u_hex_be": "227e0bb89de700385d19ec40e857db6e6a3e634b1c32962f370d26f84ff19683"+ },+ {+ "field_element_hex_be": "1a68a1af9f663592291af987203393f707305c7bac9c8d63d6a729bdc553dc19",+ "u_hex_be": "3bcd651ee54d5f7b6013898aab251ee8ecc0688166fce6e9548d38472f6bd196"+ }+ ],+ "low_order_shares": {+ "scalar_hex": "af46e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449aff",+ "must_refuse": [+ "0000000000000000000000000000000000000000000000000000000000000000",+ "0100000000000000000000000000000000000000000000000000000000000000",+ "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",+ "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",+ "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",+ "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",+ "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"+ ],+ "must_give": [+ {+ "share_hex": "daffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",+ "product_hex": "d8e2c776bbacd510d09fd9278b7edcd25fc5ae9adfba3b6e040e8d3b71b21806"+ },+ {+ "share_hex": "dbffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",+ "product_hex": "c85c655ebe8be44ba9c0ffde69f2fe10194458d137f09bbff725ce58803cdb38"+ },+ {+ "share_hex": "d9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",+ "product_hex": "db64dafa9b8fdd136914e61461935fe92aa372cb056314e1231bc4ec12417456"+ },+ {+ "share_hex": "cdeb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880",+ "product_hex": "e062dcd5376d58297be2618c7498f55baa07d7e03184e8aada20bca28888bf7a"+ },+ {+ "share_hex": "4c9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7",+ "product_hex": "993c6ad11c4c29da9a56f7691fd0ff8d732e49de6250b6c2e80003ff4629a175"+ }+ ]+ },+ "exchanges": [+ {+ "comment": "1.4.3: no machine ids yet, so both identities are empty",+ "code": "482913",+ "pair_id": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "requester": {+ "name": "Vector Mac",+ "id_hex": "",+ "nonce_hex": "edad1eba42ed11cfd8ba0daba74a4bc8",+ "scalar_hex": "842bca52bbbdc727263dfa19a0c2851f18862e0c31e7a1b706d6ce9d1934c604"+ },+ "host": {+ "name": "VECTOR-PC",+ "id_hex": "",+ "scalar_hex": "a2fa23319131feac78653467b4863a444f5da2af0158d1d5e1e239710d691580"+ },+ "sid_hex": "20656236636632656533633163386362643231363162363762343162653330303310edad1eba42ed11cfd8ba0daba74a4bc8",+ "ada_hex": "09726571756573746572000a566563746f72204d6163",+ "adb_hex": "04686f73740009564543544f522d5043",+ "generator_string_hex": "084350616365323535063438323931336f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76323220656236636632656533633163386362643231363162363762343162653330303310edad1eba42ed11cfd8ba0daba74a4bc8",+ "generator_hex": "1a750835aae9d408194e8e1393132e02c2495de72b6f265184749f056130ca10",+ "ya_hex": "2649f89325b72e646000fa5dc7c4221bf869de4938a88fecedbda398cbf34150",+ "yb_hex": "2d0dc754bb17865b276c39ba6ff00c0954b4804371a46742c3a2287c04e01347",+ "k_hex": "796f912ddb354ceba9a7642244ed553149bfc23f22f374bff3ad8315df817b2b",+ "isk_hex": "7dc167e8b761b5808f8e873878556f5dd1c52bdd62f3c348ea60a60512ea4294e19f6e72a0c54dacf5656a8debd79bf9615bee6fe5a59bbc98be15cf3b0bd077",+ "mac_key_hex": "8c619a26e16124af43935ba791b7de2b733ee32f13bae3c0943d574dbbbf1a0b6cd32997bf518db4b33a513f306c85ed9ac595806c3fc298488922660cce9f9c",+ "ta_hex": "630c08e363d467fa00c19d741672d4eac8bc9676c2b52bdb9f4939d842b12686c4d27c8ab900a85a411977042a9f4e97be520d9e64eeeeb59038a0330aec8f5d",+ "tb_hex": "1eeaafd522d6884f57057475a3bde52e3e14debcd79088aae52c5aa1edb858bdb12c4fb02a5427c42c46fdec565b43fd9a1c45b8b22d91ff733d43ac14396919",+ "td_hex": "cad8b6dd3af2c1f1b78c16c6eb86fdf897bb4f1b69f5559461491722a845ac83b5332c48433b5c4228accb93b3f177e264acbef9be9f4e21b985c165cea3dc2e",+ "token": "4xGHJR0vazj3INjxHjXpkTzLvzDEtxKZ8TiQQp8QhCw",+ "messages": {+ "pair_start": {+ "type": "pair_start",+ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "v": 2,+ "nonce": "7a0eukLtEc_Yug2rp0pLyA",+ "share": "Jkn4kyW3LmRgAPpdx8QiG_hp3kk4qI_s7b2jmMvzQVA",+ "name": "Vector Mac",+ "id": ""+ },+ "pair_answer": {+ "type": "pair_answer",+ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "ok": true,+ "share": "LQ3HVLsXhlsnbDm6b_AMCVS0gENxpGdCw6IofATgE0c",+ "tag": "Huqv1SLWiE9XBXR1o73lLj4U3rzXkIiq5Sxaoe24WL2xLE-wKlQnxCxG_exWW0P9mhxFuLItkf9zPUOsFDlpGQ",+ "name": "VECTOR-PC",+ "id": ""+ },+ "pair_confirm": {+ "type": "pair_confirm",+ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "tag": "YwwI42PUZ_oAwZ10FnLU6si8lnbCtSvbn0k52EKxJobE0nyKuQCoWkEZdwQqn06XvlINnmTu7rWQOKAzCuyPXQ"+ },+ "pair_done": {+ "type": "pair_done",+ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",+ "ok": true,+ "tag": "yti23TrywfG3jBbG64b9-Je7Txtp9VWUYUkXIqhFrIO1MyxIQztcQiisy5Oz8XfiZKy--b6fTiG5hcFlzqPcLg"+ }+ }+ },+ {+ "comment": "The wire v6 shape: a 16-byte id each side, and a name with characters outside ASCII and outside the BMP",+ "code": "007045",+ "pair_id": "d397348abeb0691c3292a1f36093d950",+ "requester": {+ "name": "Zo\u00eb\u2019s \ud835\udd39eamer Mac",+ "id_hex": "74f70aa0e96f874c9866b11545950f8b",+ "nonce_hex": "e979b12f908a2f0ad16eb37876b5f0b5",+ "scalar_hex": "85b6b2942677e61db3636c9e6faea4586cc708ac4051afc481e17810a672266a"+ },+ "host": {+ "name": "VECTOR-PC",+ "id_hex": "ee3e1ebd5eacd2c487f2403bac611cdb",+ "scalar_hex": "4ee3c8b532aca27be39b1ac34ea82bd4084684dbd0e54987b192b5cd30541dbc"+ },+ "sid_hex": "20643339373334386162656230363931633332393261316633363039336439353010e979b12f908a2f0ad16eb37876b5f0b5",+ "ada_hex": "097265717565737465721074f70aa0e96f874c9866b11545950f8b165a6fc3abe280997320f09d94b965616d6572204d6163",+ "adb_hex": "04686f737410ee3e1ebd5eacd2c487f2403bac611cdb09564543544f522d5043",+ "generator_string_hex": "084350616365323535063030373034356f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76323220643339373334386162656230363931633332393261316633363039336439353010e979b12f908a2f0ad16eb37876b5f0b5",+ "generator_hex": "73b80492ce8c3d166117a405dc4bc62d593149cda94e53f3012d102fb539c069",+ "ya_hex": "46d1977042bd7aabd494df39930b1f6efb83078fe7cf605ffcf1580c8613d005",+ "yb_hex": "5fdbb545d4175d7f1e83613994e2abfdff7f7f46fb62e5c9b3f74c08e0ab8147",+ "k_hex": "f94259fbe1b827b22fc38e9beed8c77501ceca3373fe2abcc79e03ab0b245a77",+ "isk_hex": "9010d318e53253ad83ae8c3354e7d32229b7427d144d99fdba9681482a3ca81c4edc4ef433d1c2253949288c22464ff4b61b66158e983910b9c088de2826bf30",+ "mac_key_hex": "5d539ab7dd2da83e6411669bb70f95578cc61ed2f7f55462352953e3a687edcf8ea0b08bc5737d1ed2dd285cf61968efaed83d4e5acdb9136b7056f03a9681f4",+ "ta_hex": "d084e7d4b3e4d3008f2082cfeb9f421496fd1ea514717eb6f1fabb9e951deb88f734c2806c0a7153914cf5ed37635fa40dd46295c5ff0b7e8dd942f103504a41",+ "tb_hex": "2e636a9a44c7dde48f4d2dee732bd556abf31b4ba2e97121e0af076e1eb6d8297c0d4ad517513caef69c111e46c4097b940740f38e4251c10bc0a03da9b4d556",+ "td_hex": "f3ab76e44dca6d3aad881499c4941f6b5a5cd7e95971b75d0163b1f127fbb6785e728d53863a1d5e7c7ba96c8247a629f106833397415f73eb223febc28272fd",+ "token": "RG0uipRsvpPDZlGTPq3dXODw6X-a1M5f2QnB9jPcldo",+ "messages": {+ "pair_start": {+ "type": "pair_start",+ "pair": "d397348abeb0691c3292a1f36093d950",+ "v": 2,+ "nonce": "6XmxL5CKLwrRbrN4drXwtQ",+ "share": "RtGXcEK9eqvUlN85kwsfbvuDB4_nz2Bf_PFYDIYT0AU",+ "name": "Zo\u00eb\u2019s \ud835\udd39eamer Mac",+ "id": "dPcKoOlvh0yYZrEVRZUPiw"+ },+ "pair_answer": {+ "type": "pair_answer",+ "pair": "d397348abeb0691c3292a1f36093d950",+ "ok": true,+ "share": "X9u1RdQXXX8eg2E5lOKr_f9_f0b7YuXJs_dMCOCrgUc",+ "tag": "LmNqmkTH3eSPTS3ucyvVVqvzG0ui6XEh4K8Hbh622Cl8DUrVF1E8rvacER5GxAl7lAdA845CUcELwKA9qbTVVg",+ "name": "VECTOR-PC",+ "id": "7j4evV6s0sSH8kA7rGEc2w"+ },+ "pair_confirm": {+ "type": "pair_confirm",+ "pair": "d397348abeb0691c3292a1f36093d950",+ "tag": "0ITn1LPk0wCPIILP659CFJb9HqUUcX628fq7npUd64j3NMKAbApxU5FM9e03Y1-kDdRilcX_C36N2ULxA1BKQQ"+ },+ "pair_done": {+ "type": "pair_done",+ "pair": "d397348abeb0691c3292a1f36093d950",+ "ok": true,+ "tag": "86t25E3KbTqtiBSZxJQfa1pc1-lZcbddAWOx8Sf7tnheco1ThjodXnx7qWyCR6Yp8QaDM5dBX3PrIj_rwoJy_Q"+ }+ }+ }+ ],+ "wrong_code": {+ "host_code": "482913",+ "requester_code": "482914",+ "pair_id": "6bc698c0065affb622fff9fb87cac02a",+ "requester": {+ "name": "Vector Mac",+ "id_hex": "",+ "nonce_hex": "d90bf42db9e188ff2f817cd143f514f2",+ "scalar_hex": "5318fc1f72d7f28d4053a37001e4b96339c154095161d9e3686d068e993cd2a5"+ },+ "pair_start": {+ "type": "pair_start",+ "pair": "6bc698c0065affb622fff9fb87cac02a",+ "v": 2,+ "nonce": "2Qv0LbnhiP8vgXzRQ_UU8g",+ "share": "Qq9Jel7gwUBo6te3H1ucksTPo9W9_KNE3wS6H1i8IFY",+ "name": "Vector Mac",+ "id": ""+ },+ "pair_answer": {+ "type": "pair_answer",+ "pair": "6bc698c0065affb622fff9fb87cac02a",+ "ok": true,+ "share": "CAKZVA2Yp_gG6soy4krssop3x0uLbG4BIPWF2JQLCxA",+ "tag": "EDuxWV1wqH2EdQtuQCC4DyFXZb9kibeRaxATuacSQv0hr3hVqhsBkS8bt90zJirBrkZWRSBWaRWNemqnNfu31g",+ "name": "VECTOR-PC",+ "id": ""+ },+ "requester_must": "refused",+ "pair_confirm_abort": {+ "type": "pair_confirm",+ "pair": "6bc698c0065affb622fff9fb87cac02a",+ "tag": ""+ }+ },+ "name_cut": {+ "name": "\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e",+ "code_points": 60,+ "sent": "\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e",+ "sent_code_points": 48+ }+}diff --git a/win_app/tests/test_hide_addresses_win.py b/win_app/tests/test_hide_addresses_win.pyindex 4e0da36..00819f2 100644--- a/win_app/tests/test_hide_addresses_win.py+++ b/win_app/tests/test_hide_addresses_win.py@@ -40,6 +40,25 @@ class HideAddressesWindowTest(unittest.TestCase):self.assertTrue(self.window.hide_switch.isChecked())self.assertEqual(self.window.host_entry.echoMode(), QLineEdit.EchoMode.Password)+ def test_the_directions_note_hides_the_macs_address(self):+ # The feature shoot, 29-09-2026: with it on, the note under Send input to your Mac still+ # read "Connected to the Mac at" and its address.+ self.config.write_text(json.dumps(dict(self.raw, hide_addresses=True)))+ self.window.reload_config()+ self.window._sending_detail = "Connected to the Mac at 192.0.2.10"+ self.window._refresh_window()+ self.assertIn("Connected to the Mac at", self.window.send_hint.text())+ self.assertNotIn("192.0.2.10", self.window.send_hint.text())++ def test_a_tray_alert_hides_the_macs_address(self):+ # "Cannot switch — <status>" carries the sender's status, which can name the Mac's address.+ self.config.write_text(json.dumps(dict(self.raw, hide_addresses=True)))+ self.window.reload_config()+ shown = []+ self.window.tray.showMessage = lambda title, message, *rest: shown.append(message)+ self.window._on_alert("Beamer", "Cannot switch — Connected to the Mac at 192.0.2.10")+ self.assertEqual(shown, ["Cannot switch — Connected to the Mac at •••"])+if __name__ == "__main__":unittest.main()diff --git a/win_app/tests/test_pairing.py b/win_app/tests/test_pairing.pyindex 0321263..7f90516 100644--- a/win_app/tests/test_pairing.py+++ b/win_app/tests/test_pairing.py@@ -2,7 +2,7 @@ import jsonimport unittestimport pairing-from pairing import PairingClient, PairingHost, beacon_msg, decode, encode+from pairing import PairingHost, beacon_msg, decode, encodeclass FakeClock:@@ -16,19 +16,13 @@ class FakeClock:self.value += seconds-def exchange(host, code, pair_id=None):- client = PairingClient(pair_id or host.pair_id, code, "Test Mac")- request = client.request()- return client, request, host.handle(request)--class BeaconTests(unittest.TestCase):- def test_beacon_carries_only_name_port_and_pairing_id(self):+ def test_beacon_carries_only_name_port_version_and_pairing_id(self):host = PairingHost(FakeClock())code = host.begin()raw = encode(beacon_msg("TEST-PC", 51820, host.pair_id))message = json.loads(raw)- self.assertEqual(set(message), {"beamy", "type", "name", "port", "pair"})+ self.assertEqual(set(message), {"beamy", "type", "name", "port", "pairing", "pair"})self.assertEqual(message["pair"], host.pair_id)self.assertNotIn(code.encode(), raw)self.assertEqual(decode(raw), message)@@ -43,66 +37,19 @@ class BeaconTests(unittest.TestCase):self.assertIsNone(decode(b"x" * (pairing.MAX_DATAGRAM_BYTES + 1)))-class PairingHostTests(unittest.TestCase):+class CodeLifetimeTests(unittest.TestCase):+ """The exchange itself is covered by test_pairing_cpace.py, which both apps share."""+def setUp(self):self.clock = FakeClock()self.host = PairingHost(self.clock)- def test_right_code_agrees_one_token_on_both_sides_without_sending_it(self):- code = self.host.begin()- client, request, reply = exchange(self.host, code)- self.assertTrue(reply["ok"])- token = client.accept(reply)- self.assertEqual(self.host.paired[0], token)- self.assertEqual(self.host.paired[1], "Test Mac")- self.assertGreaterEqual(len(token), 40)- wire = encode(request) + encode(reply)- self.assertNotIn(token.encode(), wire)- self.assertNotIn(code.encode(), wire)- self.assertFalse(self.host.active)-- def test_wrong_code_is_refused_and_burns_the_code(self):- code = self.host.begin()- wrong = str((int(code) + 1) % 10**6).zfill(6)- client, _request, reply = exchange(self.host, wrong)- self.assertEqual(reply, {"type": "pair_reply", "pair": client.pair_id, "ok": False, "error": "refused"})- with self.assertRaises(pairing.PairingError):- client.accept(reply)- self.assertIsNone(self.host.paired)- self.assertFalse(self.host.active)- # The right code, one second later, is no longer accepted either.- _client, _request, retry = exchange(self.host, code, client.pair_id)- self.assertFalse(retry["ok"])- self.assertEqual(retry["error"], "not_pairing")-- def test_expired_code_is_refused(self):- code = self.host.begin()- pair_id = self.host.pair_id- self.clock.advance(pairing.CODE_LIFETIME_SECONDS)- _client, _request, reply = exchange(self.host, code, pair_id)- self.assertFalse(reply["ok"])- self.assertEqual(reply["error"], "not_pairing")- self.assertIsNone(self.host.paired)-- def test_unknown_pairing_id_does_not_burn_the_code(self):- code = self.host.begin()- _client, _request, reply = exchange(self.host, code, "deadbeef")- self.assertEqual(reply["error"], "not_pairing")- self.assertTrue(self.host.active)- _client, _request, reply = exchange(self.host, code)- self.assertTrue(reply["ok"])-- def test_retransmitted_request_gets_the_same_reply(self):- code = self.host.begin()- client, request, reply = exchange(self.host, code)- self.assertEqual(self.host.handle(request), reply)- self.assertEqual(client.accept(reply), client.accept(self.host.handle(request)))-- def test_malformed_request_burns_the_code(self):+ def test_each_code_gets_its_own_pairing_id(self):self.host.begin()- reply = self.host.handle({"type": "pair_request", "pair": self.host.pair_id, "pub": "!!", "proof": "??"})- self.assertEqual(reply["error"], "refused")- self.assertFalse(self.host.active)+ first = self.host.pair_id+ self.host.begin()+ self.assertNotEqual(first, self.host.pair_id)+ self.assertEqual(len(bytes.fromhex(first)), 16)def test_seconds_left_counts_down_to_zero(self):self.host.begin()@@ -112,31 +59,13 @@ class PairingHostTests(unittest.TestCase):self.clock.advance(100)self.assertEqual(self.host.seconds_left, 0)self.assertIsNone(self.host.code)+ self.assertEqual(self.host.outcome, "expired")--class PairingClientTests(unittest.TestCase):- def test_pc_that_does_not_know_the_code_is_rejected(self):- host = PairingHost(FakeClock())- code = host.begin()- client = PairingClient(host.pair_id, code, "Test Mac")- client.request()- # A different host, holding a different code, answers in the real one's place.- impostor = PairingHost(FakeClock())- impostor.begin()- impostor.pair_id = host.pair_id- reply = impostor.handle(client.request())- self.assertFalse(reply["ok"])- with self.assertRaises(pairing.PairingError):- client.accept(reply)-- def test_tampered_reply_is_rejected(self):- host = PairingHost(FakeClock())- code = host.begin()- client, _request, reply = exchange(host, code)- other = pairing.X25519PrivateKey.generate()- reply["pub"] = pairing._b64(pairing._public_bytes(other))- with self.assertRaises(pairing.PairingError):- client.accept(reply)+ def test_cancelling_leaves_no_outcome(self):+ self.host.begin()+ self.host.cancel()+ self.assertFalse(self.host.active)+ self.assertIsNone(self.host.outcome)if __name__ == "__main__":diff --git a/win_app/tests/test_pairing_cpace.py b/win_app/tests/test_pairing_cpace.pynew file mode 100644index 0000000..078bbd6--- /dev/null+++ b/win_app/tests/test_pairing_cpace.py@@ -0,0 +1,640 @@+"""The pairing exchange itself: CPace against the published vectors, the committed vectors+replayed value by value, and the rules that hold an attacker to one guess at the code.++Pure: no sockets and no clock but the fake one, so it runs the same in both apps' suites.+"""++import json+import os+import unittest++import pairing+from pairing import PairingClient, PairingError, PairingHost, encode++_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))++with open(os.path.join(_TESTS_DIR, "pairing_vectors.json"), encoding="utf-8") as _handle:+ VECTORS = json.load(_handle)+++class FakeClock:+ def __init__(self, value=1000.0):+ self.value = value++ def __call__(self):+ return self.value++ def advance(self, seconds):+ self.value += seconds+++def scripted(*values):+ queue = list(values)+ return lambda length: queue.pop(0)+++def other_code(code):+ return str((int(code) + 1) % 10**6).zfill(6)+++def paired(host, code, name="Test Mac"):+ """One honest exchange, as (client, start, answer, confirm, done, token)."""+ client = PairingClient(host.pair_id, code, name)+ start = client.start()+ answer = host.handle(start)+ confirm = client.accept(answer)+ done = host.handle(confirm)+ return client, start, answer, confirm, done, client.finish(done)+++class PublishedVectorTests(unittest.TestCase):+ """The numbers other people published, so the core is right before Beamer adds to it."""++ def test_length_prefixes_match_the_draft(self):+ self.assertEqual(pairing._prepend_len(b"").hex(), "00")+ self.assertEqual(pairing._prepend_len(b"1234").hex(), "0431323334")+ self.assertEqual(pairing._prepend_len(bytes(128))[:2].hex(), "8001")+ self.assertEqual(pairing._prepend_len(bytes(300))[:2].hex(), "ac02")+ self.assertEqual(pairing._lv_cat(b"1234", b"5", b"", b"678").hex(), "043132333401350003363738")++ def test_the_draft_exchange_is_reproduced_step_by_step(self):+ draft = VECTORS["cpace_draft"]+ sid = bytes.fromhex(draft["sid_hex"])+ generator = pairing._generator(draft["prs_ascii"].encode(), bytes.fromhex(draft["ci_hex"]), sid)+ self.assertEqual(generator.hex(), draft["generator_hex"])+ ya_scalar = bytes.fromhex(draft["ya_scalar_hex"])+ yb_scalar = bytes.fromhex(draft["yb_scalar_hex"])+ ya = pairing._x25519(ya_scalar, generator)+ yb = pairing._x25519(yb_scalar, generator)+ self.assertEqual((ya.hex(), yb.hex()), (draft["ya_hex"], draft["yb_hex"]))+ self.assertEqual(pairing._x25519(ya_scalar, yb).hex(), draft["k_hex"])+ self.assertEqual(pairing._x25519(yb_scalar, ya).hex(), draft["k_hex"])++ def test_elligator_matches_rfc_9380(self):+ for vector in VECTORS["elligator2"]:+ with self.subTest(element=vector["field_element_hex_be"]):+ self.assertEqual(pairing._elligator2(int(vector["field_element_hex_be"], 16)), int(vector["u_hex_be"], 16))++ def test_low_order_shares_are_refused(self):+ low = VECTORS["low_order_shares"]+ scalar = bytes.fromhex(low["scalar_hex"])+ for share in low["must_refuse"]:+ with self.subTest(share=share):+ with self.assertRaises(PairingError):+ pairing._x25519(scalar, bytes.fromhex(share))+ for vector in low["must_give"]:+ with self.subTest(share=vector["share_hex"]):+ self.assertEqual(pairing._x25519(scalar, bytes.fromhex(vector["share_hex"])).hex(), vector["product_hex"])++ def test_base64_has_one_spelling(self):+ for length in range(40):+ data = bytes(range(length))+ self.assertEqual(pairing._unb64(pairing._b64(data)), data)+ for text in ("AA==", "AA=", "A", "AAB", "AB+/", " AAAA", "AAAA\n", "!!!!", "====", "AA!A", None, 7, b"AAAA"):+ with self.subTest(text=text):+ with self.assertRaises(PairingError):+ pairing._unb64(text)++ def test_hkdf_matches_rfc_5869(self):+ # Test case 1, whose first 32 bytes are the single block this HKDF produces.+ block = pairing._hkdf(bytes([0x0B]) * 22, bytes(range(13)), bytes(range(0xF0, 0xFA)))+ self.assertEqual(block.hex(), "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf")+++class PhoneVectorTests(unittest.TestCase):+ """pairing_vectors.json is what a second implementation is built against; these replay+ it through this module, so a change to the exchange cannot leave the file behind."""++ def test_constants_are_the_ones_in_the_file(self):+ constants = VECTORS["constants"]+ self.assertEqual(VECTORS["pairing_version"], pairing.PAIRING_VERSION)+ self.assertEqual(constants["channel_ascii"].encode(), pairing.CHANNEL)+ self.assertEqual(constants["role_requester_ascii"].encode(), pairing.ROLE_REQUESTER)+ self.assertEqual(constants["role_host_ascii"].encode(), pairing.ROLE_HOST)+ self.assertEqual(constants["token_info_ascii"].encode(), pairing.TOKEN_INFO)+ self.assertEqual(constants["done_label_ascii"].encode(), pairing.DONE_LABEL)+ self.assertEqual(constants["max_name_chars"], pairing.MAX_NAME_CHARS)++ def test_each_exchange_replays_to_the_same_messages_and_token(self):+ for vector in VECTORS["exchanges"]:+ with self.subTest(exchange=vector["comment"]):+ requester, host_side = vector["requester"], vector["host"]+ host = PairingHost(+ name=host_side["name"],+ identity=bytes.fromhex(host_side["id_hex"]),+ entropy=scripted(bytes.fromhex(vector["pair_id"]), bytes.fromhex(host_side["scalar_hex"])),+ )+ host.begin()+ host.code = vector["code"]+ self.assertEqual(host.pair_id, vector["pair_id"])+ client = PairingClient(+ host.pair_id,+ vector["code"],+ requester["name"],+ identity=bytes.fromhex(requester["id_hex"]),+ entropy=scripted(bytes.fromhex(requester["nonce_hex"]), bytes.fromhex(requester["scalar_hex"])),+ )+ messages = vector["messages"]+ self.assertEqual(client.start(), messages["pair_start"])+ answer = host.handle(messages["pair_start"])+ self.assertEqual(answer, messages["pair_answer"])+ confirm = client.accept(answer)+ self.assertEqual(confirm, messages["pair_confirm"])+ done = host.handle(confirm)+ self.assertEqual(done, messages["pair_done"])+ self.assertEqual(client.finish(done), vector["token"])+ self.assertEqual(host.paired, (vector["token"], requester["name"]))++ def test_each_exchange_s_intermediate_values_follow_the_specification(self):+ for vector in VECTORS["exchanges"]:+ with self.subTest(exchange=vector["comment"]):+ requester, host_side = vector["requester"], vector["host"]+ sid = pairing._session_id(vector["pair_id"], bytes.fromhex(requester["nonce_hex"]))+ self.assertEqual(sid.hex(), vector["sid_hex"])+ ada = pairing._party(pairing.ROLE_REQUESTER, bytes.fromhex(requester["id_hex"]), requester["name"])+ adb = pairing._party(pairing.ROLE_HOST, bytes.fromhex(host_side["id_hex"]), host_side["name"])+ self.assertEqual((ada.hex(), adb.hex()), (vector["ada_hex"], vector["adb_hex"]))+ self.assertEqual(pairing._generator(vector["code"].encode(), pairing.CHANNEL, sid).hex(), vector["generator_hex"])+ ya = pairing._share(vector["code"], sid, bytes.fromhex(requester["scalar_hex"]))+ yb = pairing._share(vector["code"], sid, bytes.fromhex(host_side["scalar_hex"]))+ self.assertEqual((ya.hex(), yb.hex()), (vector["ya_hex"], vector["yb_hex"]))+ for scalar, peer in ((requester["scalar_hex"], yb), (host_side["scalar_hex"], ya)):+ shared = pairing._x25519(bytes.fromhex(scalar), peer)+ token, ta, tb, td = pairing._keys(sid, shared, ya, ada, yb, adb)+ self.assertEqual(token, vector["token"])+ self.assertEqual((ta.hex(), tb.hex(), td.hex()), (vector["ta_hex"], vector["tb_hex"], vector["td_hex"]))++ def test_the_wrong_code_vector_is_refused_and_aborted(self):+ vector = VECTORS["wrong_code"]+ requester = vector["requester"]+ client = PairingClient(+ vector["pair_id"],+ vector["requester_code"],+ requester["name"],+ entropy=scripted(bytes.fromhex(requester["nonce_hex"]), bytes.fromhex(requester["scalar_hex"])),+ )+ self.assertEqual(client.start(), vector["pair_start"])+ with self.assertRaises(PairingError) as caught:+ client.accept(vector["pair_answer"])+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.assertEqual(client.abort(), vector["pair_confirm_abort"])+ self.assertEqual(vector["requester_must"], pairing.ERROR_REFUSED)++ def test_a_name_is_cut_by_code_points(self):+ vector = VECTORS["name_cut"]+ client = PairingClient("00" * 16, "482913", vector["name"])+ self.assertEqual(client.start()["name"], vector["sent"])+ self.assertEqual((len(vector["name"]), len(vector["sent"])), (vector["code_points"], pairing.MAX_NAME_CHARS))+++class ExchangeTests(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ self.host = PairingHost(self.clock, name="TEST-PC")+ self.code = self.host.begin()++ def test_right_code_agrees_one_token_without_sending_it_or_the_code(self):+ _client, start, answer, confirm, done, token = paired(self.host, self.code)+ self.assertEqual(self.host.paired, (token, "Test Mac"))+ self.assertGreaterEqual(len(token), 40)+ self.assertEqual(self.host.outcome, "paired")+ self.assertFalse(self.host.active)+ wire = b"".join(encode(message) for message in (start, answer, confirm, done))+ self.assertNotIn(token.encode(), wire)+ self.assertNotIn(self.code.encode(), wire)++ def test_the_host_stores_nothing_until_the_requester_confirms(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(client.start())+ self.assertTrue(answer["ok"])+ self.assertIsNone(self.host.paired)+ self.assertTrue(self.host.active)++ def test_two_exchanges_never_share_a_token_or_a_share(self):+ _client, first_start, _answer, _confirm, _done, first = paired(self.host, self.code)+ code = self.host.begin()+ _client, second_start, _answer, _confirm, _done, second = paired(self.host, code)+ self.assertNotEqual(first, second)+ self.assertNotEqual(first_start["share"], second_start["share"])++ def test_a_requester_with_the_wrong_code_refuses_the_answer_and_never_confirms(self):+ client = PairingClient(self.host.pair_id, other_code(self.code), "Test Mac")+ answer = self.host.handle(client.start())+ self.assertTrue(answer["ok"], "the host cannot tell a wrong code from its answer alone")+ with self.assertRaises(PairingError) as caught:+ client.accept(answer)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.assertIsNone(self.host.paired)++ def test_the_abort_ends_the_code_and_says_a_wrong_one_was_entered(self):+ client = PairingClient(self.host.pair_id, other_code(self.code), "Test Mac")+ self.host.handle(client.start())+ done = self.host.handle(client.abort())+ self.assertEqual(done, {"type": "pair_done", "pair": client.pair_id, "ok": False, "error": "refused"})+ self.assertFalse(self.host.active)+ self.assertEqual(self.host.outcome, "refused")+ self.assertIsNone(self.host.paired)++ def test_a_host_with_another_code_is_refused(self):+ impostor = PairingHost(FakeClock(), name="TEST-PC")+ impostor.begin()+ impostor.code = other_code(self.code)+ impostor.pair_id = self.host.pair_id+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ with self.assertRaises(PairingError):+ client.accept(impostor.handle(client.start()))+ with self.assertRaises(PairingError):+ client.finish({"type": "pair_done", "pair": client.pair_id, "ok": True, "tag": ""})+++class OneGuessTests(unittest.TestCase):+ """Each rule here is what stops a second guess at the code; loosening one is a hole."""++ def setUp(self):+ self.clock = FakeClock()+ self.host = PairingHost(self.clock, name="TEST-PC")+ self.code = self.host.begin()++ def test_a_code_answers_one_share_even_for_the_right_code(self):+ attacker = PairingClient(self.host.pair_id, other_code(self.code), "Attacker")+ self.assertTrue(self.host.handle(attacker.start())["ok"])+ honest = PairingClient(self.host.pair_id, self.code, "Test Mac")+ reply = self.host.handle(honest.start())+ self.assertEqual(reply, {"type": "pair_answer", "pair": honest.pair_id, "ok": False, "error": "refused"})+ second = PairingClient(self.host.pair_id, other_code(other_code(self.code)), "Attacker")+ self.assertFalse(self.host.handle(second.start())["ok"])++ def test_a_second_share_does_not_disturb_the_exchange_under_way(self):+ honest = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(honest.start())+ stranger = PairingClient(self.host.pair_id, other_code(self.code), "Attacker")+ self.assertFalse(self.host.handle(stranger.start())["ok"])+ done = self.host.handle(honest.accept(answer))+ self.assertEqual(self.host.paired[0], honest.finish(done))++ def test_a_requester_judges_one_answer_and_no_more(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ good = self.host.handle(client.start())+ forged = dict(good, tag=pairing._b64(bytes(pairing.TAG_BYTES)))+ with self.assertRaises(PairingError):+ client.accept(forged)+ with self.assertRaises(PairingError) as caught:+ client.accept(good)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)++ def test_an_error_answer_also_spends_the_attempt(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ good = self.host.handle(client.start())+ with self.assertRaises(PairingError):+ client.accept({"type": "pair_answer", "pair": client.pair_id, "ok": False, "error": "not_pairing"})+ with self.assertRaises(PairingError):+ client.accept(good)++ def test_a_wrong_confirmation_ends_the_code_and_stores_nothing(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(client.start())+ confirm = client.accept(answer)+ forged = dict(confirm, tag=pairing._b64(bytes(pairing.TAG_BYTES)))+ self.assertEqual(self.host.handle(forged)["error"], "refused")+ self.assertIsNone(self.host.paired)+ self.assertEqual(self.host.handle(confirm)["error"], "not_pairing")+ self.assertIsNone(self.host.paired)++ def test_the_host_s_own_tag_reflected_back_is_not_a_confirmation(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(client.start())+ done = self.host.handle({"type": "pair_confirm", "pair": client.pair_id, "tag": answer["tag"]})+ self.assertEqual(done["error"], "refused")+ self.assertIsNone(self.host.paired)++ def test_a_confirmation_with_no_exchange_under_way_does_nothing(self):+ done = self.host.handle({"type": "pair_confirm", "pair": self.host.pair_id, "tag": ""})+ self.assertEqual(done["error"], "not_pairing")+ self.assertTrue(self.host.active)++ def test_an_unknown_pairing_id_does_not_touch_the_code(self):+ stranger = PairingClient("deadbeef", self.code, "Test Mac")+ self.assertEqual(self.host.handle(stranger.start())["error"], "not_pairing")+ self.assertTrue(self.host.active)+ paired(self.host, self.code)++ def test_a_tampered_share_or_name_is_refused(self):+ for field, value in (("share", pairing._b64(bytes(range(1, 33)))), ("name", "EVIL-PC"), ("id", pairing._b64(b"x"))):+ with self.subTest(field=field):+ host = PairingHost(FakeClock(), name="TEST-PC")+ code = host.begin()+ client = PairingClient(host.pair_id, code, "Test Mac")+ answer = dict(host.handle(client.start()), **{field: value})+ with self.assertRaises(PairingError):+ client.accept(answer)++ def test_a_name_changed_on_the_way_to_the_host_fails_the_exchange(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(dict(client.start(), name="Someone Else"))+ with self.assertRaises(PairingError):+ client.accept(answer)++ def test_identities_are_bound_into_the_token(self):+ host = PairingHost(FakeClock(), name="TEST-PC", identity=b"h" * 16)+ code = host.begin()+ client = PairingClient(host.pair_id, code, "Test Mac", identity=b"r" * 16)+ start = client.start()+ answer = host.handle(start)+ self.assertEqual((start["id"], answer["id"]), (pairing._b64(b"r" * 16), pairing._b64(b"h" * 16)))+ self.assertEqual(client.finish(host.handle(client.accept(answer))), host.paired[0])+ host = PairingHost(FakeClock(), name="TEST-PC", identity=b"h" * 16)+ code = host.begin()+ client = PairingClient(host.pair_id, code, "Test Mac", identity=b"r" * 16)+ answer = host.handle(dict(client.start(), id=pairing._b64(b"q" * 16)))+ with self.assertRaises(PairingError):+ client.accept(answer)+++class HostStateTests(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ self.host = PairingHost(self.clock, name="TEST-PC")+ self.code = self.host.begin()++ def test_retransmitted_datagrams_get_the_same_replies(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ start = client.start()+ answer = self.host.handle(start)+ self.assertEqual(self.host.handle(start), answer)+ confirm = client.accept(answer)+ done = self.host.handle(confirm)+ self.assertEqual(self.host.handle(confirm), done)+ self.assertTrue(done["ok"])++ def test_a_refused_start_is_answered_the_same_way_again(self):+ start = dict(PairingClient(self.host.pair_id, self.code, "Test Mac").start(), share="!!")+ reply = self.host.handle(start)+ self.assertEqual(reply["error"], "refused")+ self.assertEqual(self.host.handle(start), reply)++ def test_an_expired_code_is_not_answered(self):+ pair_id = self.host.pair_id+ self.clock.advance(pairing.CODE_LIFETIME_SECONDS)+ client = PairingClient(pair_id, self.code, "Test Mac")+ self.assertEqual(self.host.handle(client.start())["error"], "not_pairing")+ self.assertEqual(self.host.outcome, "expired")++ def test_an_exchange_the_code_outlives_is_not_completed(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ confirm = client.accept(self.host.handle(client.start()))+ self.clock.advance(pairing.CODE_LIFETIME_SECONDS)+ self.assertEqual(self.host.handle(confirm)["error"], "not_pairing")+ self.assertIsNone(self.host.paired)++ def test_a_new_code_forgets_the_last_exchange(self):+ client, start, _answer, confirm, _done, _token = paired(self.host, self.code)+ self.host.paired = None+ self.host.begin()+ self.assertEqual(self.host.handle(start)["error"], "not_pairing")+ self.assertEqual(self.host.handle(confirm)["error"], "not_pairing")+ self.assertIsNone(self.host.paired)++ def test_malformed_starts_are_refused_without_an_exception(self):+ good = PairingClient(self.host.pair_id, self.code, "Test Mac").start()+ bad_fields = [+ ("nonce", "!!"), ("nonce", pairing._b64(b"short")), ("nonce", None), ("nonce", ["a"]),+ ("share", "??"), ("share", pairing._b64(bytes(31))), ("share", 7), ("share", {"a": 1}),+ ("share", pairing._b64(bytes(32))), ("share", pairing._b64(b"\x01" + bytes(31))),+ ("name", None), ("name", 12), ("name", "x" * (pairing.MAX_NAME_CHARS + 1)), ("name", "\ud800"),+ ("id", None), ("id", pairing._b64(bytes(pairing.MAX_IDENTITY_BYTES + 1))), ("id", "é"),+ ]+ for field, value in bad_fields:+ with self.subTest(field=field, value=value):+ host = PairingHost(FakeClock(), name="TEST-PC")+ host.begin()+ host.code = self.code+ host.pair_id = self.host.pair_id+ reply = host.handle(dict(good, **{field: value}))+ self.assertEqual(reply, {"type": "pair_answer", "pair": host.pair_id or good["pair"], "ok": False, "error": "refused"})+ self.assertFalse(host.active)+ self.assertIsNone(host.paired)++ def test_a_refusal_never_touches_the_code(self):+ # A refusal goes back at once, so nothing worked out from the code may come before it:+ # how long that took would be in the reply's timing.+ good = PairingClient(self.host.pair_id, self.code, "Test Mac").start()+ calls = []+ real = pairing._generator+ pairing._generator = lambda *args: calls.append(args) or real(*args)+ try:+ for field, value in (("share", pairing._b64(bytes(32))), ("share", pairing._b64(b"\x01" + bytes(31))),+ ("name", "\ud800"), ("nonce", "!!"), ("id", "=")):+ host = PairingHost(FakeClock(), name="TEST-PC")+ host.begin()+ host.code = self.code+ reply = host.handle(dict(good, pair=host.pair_id, **{field: value}))+ self.assertEqual(reply["error"], "refused")+ self.assertFalse(host.fresh_answer)+ self.assertEqual(calls, [])+ self.assertTrue(self.host.handle(good)["ok"])+ self.assertEqual(len(calls), 1)+ finally:+ pairing._generator = real++ def test_only_a_newly_made_answer_is_marked_fresh(self):+ start = PairingClient(self.host.pair_id, self.code, "Test Mac").start()+ self.assertFalse(self.host.fresh_answer)+ self.host.handle(start)+ self.assertTrue(self.host.fresh_answer)+ self.host.fresh_answer = False+ self.assertTrue(self.host.handle(start)["ok"])+ self.assertFalse(self.host.fresh_answer)++ def test_datagrams_that_are_not_for_the_host_get_no_answer(self):+ self.assertIsNone(self.host.handle({"type": "beacon", "name": "x", "port": 1}))+ self.assertIsNone(self.host.handle({"type": "pair_start", "pair": 7}))+ for pair_id in ("", "x" * 65, "\u00e9" * 8, "\ud83d"):+ self.assertIsNone(self.host.handle({"type": "pair_start", "pair": pair_id}))+ self.assertIsNone(self.host.handle({"type": "pair_request", "pair": pair_id}))+ self.assertIsNone(self.host.handle({"type": "pair_answer", "pair": self.host.pair_id}))+ self.assertTrue(self.host.active)++ def test_another_pairing_version_is_told_so(self):+ start = dict(PairingClient(self.host.pair_id, self.code, "Test Mac").start(), v=3)+ self.assertEqual(self.host.handle(start)["error"], "version")+ self.assertEqual(self.host.outcome, "version")+ self.assertFalse(self.host.active)++ def test_a_1_4_2_request_is_refused_in_the_reply_that_mac_reads(self):+ request = {"type": "pair_request", "pair": self.host.pair_id, "pub": "AAAA", "proof": "BBBB", "name": "Old Mac"}+ reply = self.host.handle(request)+ self.assertEqual(reply, {"type": "pair_reply", "pair": request["pair"], "ok": False, "error": "refused"})+ self.assertEqual(self.host.outcome, "version")+ self.assertIsNone(self.host.paired)+ self.assertEqual(self.host.handle(request)["error"], "not_pairing")++ def test_a_1_4_2_request_does_not_disturb_an_exchange_under_way(self):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ answer = self.host.handle(client.start())+ self.host.handle({"type": "pair_request", "pair": self.host.pair_id, "pub": "AAAA", "proof": "BBBB"})+ done = self.host.handle(client.accept(answer))+ self.assertEqual(self.host.paired[0], client.finish(done))+++class ClientStateTests(unittest.TestCase):+ def setUp(self):+ self.host = PairingHost(FakeClock(), name="TEST-PC")+ self.code = self.host.begin()+ self.client = PairingClient(self.host.pair_id, self.code, "Test Mac")++ def test_malformed_answers_are_refused_without_an_exception(self):+ good = self.host.handle(self.client.start())+ bad_fields = [+ ("share", None), ("share", pairing._b64(bytes(32))), ("share", pairing._b64(bytes(33))), ("share", [1]),+ ("tag", None), ("tag", "!!"), ("tag", ""), ("name", 5), ("name", "\udfff"),+ ("name", "x" * (pairing.MAX_NAME_CHARS + 1)), ("id", 1.5), ("ok", 1), ("ok", "true"),+ ]+ for field, value in bad_fields:+ with self.subTest(field=field, value=value):+ client = PairingClient(self.host.pair_id, self.code, "Test Mac")+ with self.assertRaises(PairingError):+ client.accept(dict(good, **{field: value}))++ def test_a_reply_to_another_attempt_is_not_judged(self):+ good = self.host.handle(self.client.start())+ for stray in (dict(good, pair="someone-else"), dict(good, type="pair_done"), {"type": "pair_reply", "pair": self.client.pair_id}):+ with self.assertRaises(PairingError) as caught:+ self.client.accept(stray)+ self.assertEqual(str(caught.exception), "not a reply to this attempt")+ self.client.accept(good)++ def test_the_token_is_only_handed_over_for_the_host_s_own_receipt(self):+ confirm = self.client.accept(self.host.handle(self.client.start()))+ done = self.host.handle(confirm)+ for forged in (dict(done, tag=confirm["tag"]), dict(done, tag=""), dict(done, tag=None)):+ with self.assertRaises(PairingError) as caught:+ self.client.finish(forged)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ with self.assertRaises(PairingError) as caught:+ self.client.finish({"type": "pair_done", "pair": self.client.pair_id, "ok": False, "error": "not_pairing"})+ self.assertEqual(str(caught.exception), pairing.ERROR_NOT_PAIRING)+ self.assertEqual(self.client.finish(done), self.host.paired[0])++ def test_the_host_s_name_is_known_only_once_its_tag_checks_out(self):+ answer = self.host.handle(self.client.start())+ self.assertIsNone(self.client.host_name)+ self.client.accept(answer)+ self.assertEqual((self.client.host_name, self.client.host_identity), ("TEST-PC", b""))++ def test_no_token_before_the_answer_was_accepted(self):+ with self.assertRaises(PairingError):+ self.client.finish({"type": "pair_done", "pair": self.client.pair_id, "ok": True, "tag": ""})++ def test_names_are_cut_before_they_are_sent_and_bound_as_sent(self):+ long_name = "M" * 200+ host = PairingHost(FakeClock(), name="P" * 200)+ code = host.begin()+ _client, start, answer, _confirm, _done, token = paired(host, code, name=long_name)+ self.assertEqual(start["name"], long_name[: pairing.MAX_NAME_CHARS])+ self.assertEqual(answer["name"], "P" * pairing.MAX_NAME_CHARS)+ self.assertEqual(host.paired, (token, long_name[: pairing.MAX_NAME_CHARS]))++ def test_the_largest_datagrams_fit(self):+ name = "\U0001d539" * pairing.MAX_NAME_CHARS+ host = PairingHost(FakeClock(), name=name, identity=bytes(pairing.MAX_IDENTITY_BYTES))+ code = host.begin()+ client = PairingClient(host.pair_id, code, name, identity=bytes(pairing.MAX_IDENTITY_BYTES))+ start = client.start()+ answer = host.handle(start)+ confirm = client.accept(answer)+ done = host.handle(confirm)+ for message in (start, answer, confirm, done, pairing.beacon_msg(name, 65535, host.pair_id or start["pair"])):+ self.assertLessEqual(len(encode(message)), pairing.MAX_DATAGRAM_BYTES)+ self.assertEqual(pairing.decode(encode(message))["type"], message["type"])+ self.assertEqual(client.finish(done), host.paired[0])+++class VersionTests(unittest.TestCase):+ def test_every_beacon_says_which_exchange_the_host_speaks(self):+ self.assertEqual(pairing.beacon_msg("TEST-PC", 51820)["pairing"], pairing.PAIRING_VERSION)+ self.assertEqual(pairing.beacon_msg("TEST-PC", 51820, "abcd")["pairing"], pairing.PAIRING_VERSION)++ def test_a_host_on_another_version_is_never_sent_anything(self):+ class Recorder:+ sent = []++ def sendto(self, data, address):+ self.sent.append((data, address))++ discovery = pairing.Discovery(bind_port=0)+ discovery._sock = Recorder()+ for version in (1, 3, None):+ pc = {"name": "OLD-PC", "address": "127.0.0.1", "port": 1, "reply_port": 1, "pair_id": "abcd", "pairing": version}+ with self.assertRaises(PairingError) as caught:+ discovery.pair(pc, "123456")+ self.assertEqual(str(caught.exception), pairing.ERROR_VERSION)+ self.assertEqual(Recorder.sent, [])++ def test_a_pairing_id_that_could_not_be_hashed_is_not_offered(self):+ discovery = pairing.Discovery(bind_port=0)+ for number, pair_id in enumerate(("\ud800", "é" * 8, "a" * 65, "", 7)):+ beacon = dict(pairing.beacon_msg("PC", 24820), pair=pair_id)+ discovery._note_beacon(beacon, (f"127.0.0.{number + 1}", 24821))+ self.assertEqual([pc["pair_id"] for pc in discovery.pcs()], [None] * 5)++ def test_a_beacon_whose_name_cannot_be_shown_is_dropped(self):+ discovery = pairing.Discovery(bind_port=0)+ discovery._note_beacon(pairing.beacon_msg("\ud800", 24820), ("127.0.0.1", 24821))+ self.assertEqual(discovery.pcs(), [])++ def test_only_one_attempt_runs_at_a_time(self):+ discovery = pairing.Discovery(bind_port=0)+ discovery._sock = object()+ discovery._pairing.acquire()+ pc = {"name": "PC", "address": "127.0.0.1", "port": 1, "reply_port": 1, "pair_id": "ab" * 16, "pairing": pairing.PAIRING_VERSION}+ with self.assertRaises(PairingError) as caught:+ discovery.pair(pc, "123456")+ self.assertEqual(str(caught.exception), "busy")++ def test_the_ration_is_not_wiped_by_a_burst_of_made_up_addresses(self):+ last = {}+ self.assertTrue(pairing.Announcer._due(last, "target", 100.0))+ for number in range(400):+ pairing.Announcer._due(last, f"spoofed-{number}", 100.1)+ self.assertFalse(pairing.Announcer._due(last, "target", 100.2))+ self.assertTrue(pairing.Announcer._due(last, "target", 101.0))+ self.assertLessEqual(len(last), 258)++ def test_forged_beacons_cannot_make_the_list_grow_without_end(self):+ clock = FakeClock()+ discovery = pairing.Discovery(bind_port=0, clock=clock)+ for number in range(500):+ discovery._note_beacon(pairing.beacon_msg(f"PC-{number}", 24820), (f"10.1.{number // 250}.{number % 250 + 1}", 24821))+ self.assertEqual(len(discovery._seen), pairing.MAX_SEEN_HOSTS)+ # A full list lets a newcomer in, the longest quiet making way for it.+ discovery._note_beacon(pairing.beacon_msg("REAL-PC", 24820), ("10.9.9.9", 24821))+ self.assertIn("REAL-PC", [pc["name"] for pc in discovery.pcs()])+ # A flood can still crowd it off again. The way through is the PC's address, typed:+ # that one is never the one to go.+ discovery._finding = ("10.9.9.9", 24821)+ for second in range(6):+ clock.advance(1.0)+ if second % 2 == 0:+ discovery._note_beacon(pairing.beacon_msg("REAL-PC", 24820), ("10.9.9.9", 24821))+ for number in range(200):+ discovery._note_beacon(pairing.beacon_msg("FORGED", 24820), (f"10.3.{second}.{number + 1}", 24821))+ self.assertIn("REAL-PC", [pc["name"] for pc in discovery.pcs()])+ self.assertEqual(len(discovery._seen), pairing.MAX_SEEN_HOSTS)+ discovery._finding = None+ clock.advance(pairing.BEACON_STALE_SECONDS + 1)+ discovery._note_beacon(pairing.beacon_msg("LATE-PC", 24820), ("10.2.0.1", 24821))+ self.assertEqual([pc["name"] for pc in discovery.pcs()], ["LATE-PC"])++ def test_a_datagram_of_nothing_but_brackets_is_just_ignored(self):+ self.assertIsNone(pairing.decode(b"[" * pairing.MAX_DATAGRAM_BYTES))+ self.assertIsNone(pairing.decode(b'{"a":' * 170))++ def test_a_beacon_without_a_version_is_the_old_exchange(self):+ discovery = pairing.Discovery(bind_port=0)+ discovery._note_beacon({"type": "beacon", "name": "OLD-PC", "port": 24820, "pair": "abcd"}, ("127.0.0.1", 24821))+ discovery._note_beacon(pairing.beacon_msg("NEW-PC", 24820, "abcd"), ("127.0.0.2", 24821))+ self.assertEqual({pc["name"]: pc["pairing"] for pc in discovery.pcs()}, {"OLD-PC": 1, "NEW-PC": pairing.PAIRING_VERSION})+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.pynew file mode 100644index 0000000..d11b8a0--- /dev/null+++ b/win_app/tests/test_pairing_window.py@@ -0,0 +1,59 @@+"""What the PC's window says when a code ends, in the real window built offscreen as+tools/readme_shots_win.py builds it, which starts no receiver, hooks or announcer."""++import json+import os+import tempfile+import unittest+from pathlib import Path++import pairing++try:+ from PySide6.QtWidgets import QApplication++ import kvm_bridge_win+ import theme+except ImportError: # PySide6 is only in the Windows venv+ kvm_bridge_win = None++[email protected](kvm_bridge_win is None, "needs PySide6")+class PairingOutcomeWindowTest(unittest.TestCase):+ def setUp(self):+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ self.app = QApplication.instance() or QApplication([])+ theme.init_fonts()+ config = Path(tempfile.mkdtemp()) / "config.json"+ config.write_text(json.dumps({"host": "192.0.2.20", "port": 24820}))+ self.window = kvm_bridge_win.WindowsApplication(config)+ self.host = self.window.announcer.host+ self.window.announcer.begin_pairing()+ self.window._refresh_pairing()++ def tearDown(self):+ self.window.deleteLater()++ def test_a_mac_on_the_old_exchange_is_named_as_out_of_date(self):+ self.host.handle({"type": "pair_request", "pair": self.host.pair_id, "pub": "AAAA", "proof": "BBBB"})+ self.window._refresh_pairing()+ self.assertEqual(+ self.window.pair_note.text(),+ "The Mac runs a different version of Beamer. Update Beamer on both machines, then pair again.",+ )++ def test_a_mac_that_had_the_wrong_code_ends_the_code(self):+ client = pairing.PairingClient(self.host.pair_id, "000000" if self.host.code != "000000" else "000001", "Test Mac")+ self.host.handle(client.start())+ self.assertIsNotNone(self.window.announcer.code)+ self.host.handle(client.abort())+ self.window._refresh_pairing()+ self.assertIsNone(self.window.announcer.code)+ self.assertEqual(+ self.window.pair_note.text(),+ "A wrong code was entered, so that code is cancelled. Pair again for a fresh one.",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_receiver.py b/win_app/tests/test_receiver.pyindex 40db3ec..24bca29 100644--- a/win_app/tests/test_receiver.py+++ b/win_app/tests/test_receiver.py@@ -939,12 +939,13 @@ class ReceiverHandBackTests(unittest.TestCase):so the receiver raises it: otherwise this machine keeps treating the peeras driving and its own edge and shortcut stay dead."""- def _session(self, focuses):+ def _session(self, focuses, unlock=None):server = ReceiverServer(lambda state, detail: None,clipboard=FakeClipboard(text=""),desktop=FakeDesktop([Rect(0, 0, 1920, 1080)], cursor=(500, 500)),focus_callback=focuses.append,+ unlock=unlock,)client, connection, address = connected_socket_pair()stop_event = threading.Event()@@ -992,6 +993,104 @@ class ReceiverHandBackTests(unittest.TestCase):thread.join(timeout=2.0)connection.close()+ def _next_switch(self, client, seconds):+ # Pings keep the session inside its read timeout, as the Mac's would.+ client.settimeout(0.2)+ deadline = time.monotonic() + seconds+ while time.monotonic() < deadline:+ client.send(protocol.ping_msg())+ try:+ message = client.recv()+ except socket.timeout:+ continue+ except OSError:+ return None+ if message.get("type") == protocol.MSG_SWITCH:+ return message+ return None++ def test_a_pc_that_locks_while_the_peer_drives_sends_its_input_home(self):+ # Issue #5, 30-09-2026: Windows locked while the Mac drove it, and the Mac's pointer was+ # stuck on the lock screen, where Beamer cannot inject or watch the return edge, until+ # the PC was unlocked by hand.+ class Lock:+ locked = False++ def is_locked(self):+ return self.locked++ def ensure_unlocked(self):+ return False++ lock = Lock()+ focuses = []+ server, client, connection, thread = self._session(focuses, unlock=lock)+ try:+ client.send(self._focus("windows", return_edge="left", resistance_px=100))+ wait_for_calls(focuses, minimum=1)+ self.assertIsNone(self._next_switch(client, 0.8))+ lock.locked = True+ self.assertEqual(self._next_switch(client, 3.0), protocol.switch_msg("mac"))+ finally:+ client.close()+ thread.join(timeout=2.0)+ connection.close()++ def test_switching_to_a_locked_pc_that_cannot_unlock_sends_the_input_straight_back(self):+ # The same trap from the other side: with no unlock provider, a switch to a PC already on+ # its lock screen pointed the Mac's input at nothing.+ class Locked:+ def is_locked(self):+ return True++ def ensure_unlocked(self):+ return False++ focuses = []+ server, client, connection, thread = self._session(focuses, unlock=Locked())+ try:+ client.send(self._focus("windows", return_edge="left", resistance_px=100))+ wait_for_calls(focuses, minimum=1)+ self.assertEqual(self._next_switch(client, 3.0), protocol.switch_msg("mac"))+ finally:+ client.close()+ thread.join(timeout=2.0)+ connection.close()++ def test_a_slow_arrival_on_a_locked_pc_still_gets_its_unlock(self):+ # The lock check runs on the ACK thread. When the arrival itself took a second, it saw a+ # locked PC with the peer driving and sent the input home before the unlock was asked for.+ class Unlockable:+ locked = True+ asked = 0++ def is_locked(self):+ return self.locked++ def ensure_unlocked(self):+ self.asked += 1+ self.locked = False+ return True++ class SlowOwner(list):+ def append(self, target):+ if target == "windows":+ time.sleep(1.4)+ super().append(target)++ lock = Unlockable()+ focuses = SlowOwner()+ server, client, connection, thread = self._session(focuses, unlock=lock)+ try:+ client.send(self._focus("windows", return_edge="left", resistance_px=100))+ self.assertIsNone(self._next_switch(client, 3.0))+ self.assertEqual(lock.asked, 1)+ self.assertEqual(focuses, ["windows"])+ finally:+ client.close()+ thread.join(timeout=2.0)+ connection.close()+def test_send_home_with_input_already_home_does_nothing(self):focuses = []server, client, connection, thread = self._session(focuses)diff --git a/win_app/tests/test_shared_copies.py b/win_app/tests/test_shared_copies.pyindex ec5e1ad..6e7cd04 100644--- a/win_app/tests/test_shared_copies.py+++ b/win_app/tests/test_shared_copies.py@@ -24,7 +24,10 @@ SHARED_MODULES = ("effects.py", "fx_ink.py", "fx_instrument.py", "fx_membrane.py", "fx_sparks.py", "fx_warp.py","ignored.py", "pairing.py", "protocol.py", "receiver.py", "return_edge.py", "updates.py", "wol.py",)-SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py", "test_switch_arrival.py", "test_updates.py")+SHARED_TESTS = (+ "pairing_vectors.json", "test_ignored.py", "test_pairing_cpace.py", "test_shared_copies.py", "test_switch_arrival.py",+ "test_updates.py",+)def _digest(path):diff --git a/win_app/tests/test_unlock_win.py b/win_app/tests/test_unlock_win.pyindex 9461653..3f66508 100644--- a/win_app/tests/test_unlock_win.py+++ b/win_app/tests/test_unlock_win.py@@ -18,9 +18,10 @@ class FakeKernel32:is_locked() call so a test can script the console unlocking part-waythrough the poll loop."""- def __init__(self, locked_sequence, event_opens=True):+ def __init__(self, locked_sequence, event_opens=True, lock_screen_session=1):self.locked_sequence = list(locked_sequence)self.event_opens = event_opens+ self.lock_screen_session = lock_screen_sessionself.opened_names = []self.set_events = 0self.closed = 0@@ -42,6 +43,10 @@ class FakeKernel32:def WTSGetActiveConsoleSessionId(self):return 1+ def ProcessIdToSessionId(self, pid, session):+ session._obj.value = self.lock_screen_session+ return 1+def OpenEventW(self, access, inherit, name):self.opened_names.append(name)return 99 if self.event_opens else None@@ -59,6 +64,11 @@ class IsLockedTests(unittest.TestCase):def test_logonui_running_means_locked(self):self.assertIs(unlock_win.is_locked(FakeKernel32([True])), True)+ def test_a_lock_screen_in_another_session_is_not_this_consoles(self):+ # The fix for issue #5 sends the Mac home on a lock, so a second account's lock screen or+ # an RDP logon must not read as the console's: the PC could not be driven at all.+ self.assertIs(unlock_win.is_locked(FakeKernel32([True], lock_screen_session=2)), False)+def test_no_logonui_means_unlocked(self):self.assertIs(unlock_win.is_locked(FakeKernel32([False])), False)diff --git a/win_app/unlock_win.py b/win_app/unlock_win.pyindex 49fa8bf..837b18a 100644--- a/win_app/unlock_win.py+++ b/win_app/unlock_win.py@@ -91,10 +91,12 @@ if _IS_WINDOWS:kernel32.Process32FirstW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]kernel32.Process32NextW.restype = ctypes.c_intkernel32.Process32NextW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]+ kernel32.ProcessIdToSessionId.restype = ctypes.c_int+ kernel32.ProcessIdToSessionId.argtypes = [ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong)]-def _running_process_names(mem32) -> Optional[set]:- """Every running process's image name, lowercased, or None if the+def _running_processes(mem32) -> Optional[list]:+ """Every running process as (lowercased image name, PID), or None if thesnapshot could not be taken. Enumeration only reads names and PIDs, so itneeds no privilege over the processes it lists -- LogonUI runs as SYSTEMand still shows up."""@@ -106,16 +108,26 @@ def _running_process_names(mem32) -> Optional[set]:entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)if not mem32.Process32FirstW(snapshot, ctypes.byref(entry)):return None- names = set()+ processes = []while True:- names.add(entry.szExeFile.lower())+ processes.append((entry.szExeFile.lower(), entry.th32ProcessID))if not mem32.Process32NextW(snapshot, ctypes.byref(entry)):break- return names+ return processesfinally:mem32.CloseHandle(snapshot)+def _in_console_session(mem32, pid: int, console: int) -> bool:+ """Whether `pid` runs in the console's session. A LogonUI in another session -- a second+ account's lock screen, an RDP logon -- is not this console's lock screen. A session that+ cannot be read counts as the console's, as it did before this check existed."""+ session = ctypes.c_ulong()+ if not mem32.ProcessIdToSessionId(pid, ctypes.byref(session)):+ return True+ return session.value == console++def is_locked(mem32=None) -> Optional[bool]:"""True if the console is sitting on the lock screen, False if it is not,None if that could not be determined. None is deliberately distinct from@@ -125,13 +137,17 @@ def is_locked(mem32=None) -> Optional[bool]:if mem32 is None:return Nonetry:- names = _running_process_names(mem32)+ processes = _running_processes(mem32)+ if processes is None:+ return None+ console = mem32.WTSGetActiveConsoleSessionId()+ return any(+ name == LOCK_SCREEN_PROCESS and _in_console_session(mem32, pid, console)+ for name, pid in processes+ )except Exception:LOGGER.exception("Could not enumerate processes to test for the lock screen")return None- if names is None:- return None- return LOCK_SCREEN_PROCESS in namesdef signal_unlock(mem32=None) -> bool: