From 8d8f9c798ac01b8042f65576fcad342630a9186f Mon Sep 17 00:00:00 2001 From: Humberto Prado Date: Thu, 19 Nov 2026 02:49:14 +0900 Subject: [PATCH 1/2] Harden device pairing Pair with symmetric SPAKE2 on the pairing code and use an HKDF of its key as the Noise pre-shared key, with the transcript as the Noise prologue. Discovery advertises only the id, name and protocol version. Pace failed pairing attempts per address with an overall budget and draw codes evenly from the alphabet. Protocol version 6: both computers need this version. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 + Cargo.lock | 67 +++++++ Cargo.toml | 2 + README.md | 4 +- SECURITY.md | 6 +- docs/AI_SETUP.md | 9 +- docs/ARCHITECTURE.md | 5 +- src/config.rs | 57 ++++-- src/lib.rs | 2 +- src/net.rs | 422 +++++++++++++++++++++++++++++++++++++------ src/proto.rs | 2 +- src/status.rs | 14 +- 12 files changed, 505 insertions(+), 95 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 66a72e0..97c3095 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to MagicInput are documented here. The project follows [Semantic Versioning](https://semver.org). +## [Unreleased] + +### Changed + +- **Hardened device pairing; both computers need this version.** `magicinput status` can't tell whether a nearby computer uses the same code until it connects, so its `nearby` entries drop `same_code` and gain `compatible` (same protocol version). + +### Compatibility + +- Both computers need this version: it doesn't connect to 0.6.2 or older, and says to update MagicInput on both computers. + ## [0.6.2] - 2026-10-25 ### Changed diff --git a/Cargo.lock b/Cargo.lock index 5285047..5bdb96f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -412,6 +412,12 @@ dependencies = [ "error-code", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cobs" version = "0.3.0" @@ -615,6 +621,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -626,6 +641,7 @@ dependencies = [ "curve25519-dalek-derive", "digest 0.10.7", "fiat-crypto", + "rand_core", "rustc_version", "subtle", "zeroize", @@ -710,6 +726,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid 0.10.2", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -1454,6 +1471,42 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac 0.12.1", +] + +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "html5ever" version = "0.39.0" @@ -1819,6 +1872,7 @@ dependencies = [ "embed-resource", "env_logger", "getrandom 0.4.3", + "hkdf 0.13.0", "if-addrs", "log", "mdns-sd", @@ -1831,6 +1885,7 @@ dependencies = [ "serde_json", "sha2 0.11.1", "snow", + "spake2", "tao", "toml 1.1.8+spec-1.1.0", "tray-icon", @@ -2910,6 +2965,18 @@ dependencies = [ "system-deps", ] +[[package]] +name = "spake2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5482afe85a0b6ce956c945401598dbc527593c77ba51d0a87a586938b1b893a" +dependencies = [ + "curve25519-dalek", + "hkdf 0.12.4", + "rand_core", + "sha2 0.10.9", +] + [[package]] name = "spin" version = "0.9.9" diff --git a/Cargo.toml b/Cargo.toml index e467271..018a2ac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,8 @@ toml = "1.1.8" tray-icon = "0.26.1" window-vibrancy = "0.8.1" wry = "0.57.0" +spake2 = "0.4" +hkdf = "0.13" [target."cfg(windows)".dependencies] windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_UI_HiDpi", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_UI_Shell", "Win32_System_Registry", "Win32_Storage_Packaging_Appx"] } diff --git a/README.md b/README.md index d87b9a6..dcb0f9d 100644 --- a/README.md +++ b/README.md @@ -142,8 +142,8 @@ It installs MagicInput, works out whether this is the first or second computer, Each computer runs the same small background service. When the pointer reaches the edge that leads to the other computer, the service hides and freezes the local pointer and forwards your keyboard, mouse and scroll input over the network; the other computer replays it as if it came from its own devices. Crossing back hands control home again. -- **Discovery:** computers advertise themselves on the local network (Bonjour/mDNS) and only talk to ones using the same pairing code. -- **Encryption:** every connection uses the Noise protocol (X25519, ChaCha20-Poly1305) with a key derived from the pairing code. A wrong code can't connect, and the code itself is never sent. +- **Discovery:** computers advertise themselves on the local network (Bonjour/mDNS) with a random id and their name, nothing derived from the pairing code. They only connect once pairing with the same code succeeds. +- **Encryption:** computers pair with a password-authenticated key exchange (SPAKE2) on the pairing code, then every connection uses the Noise protocol (X25519, ChaCha20-Poly1305) with the key it produced. A wrong code can't connect, the code itself is never sent, and failed attempts are slowed down. - **Local only:** connections from outside your own subnet (internet, VPNs, Tailscale) are refused. - **Keys:** keystrokes travel as layout-independent USB key codes, so each computer applies its own keyboard layout. - **Smoothness:** each pointer update is timestamped; updates that Wi-Fi delivers late are replayed as a short glide. diff --git a/SECURITY.md b/SECURITY.md index 994a6c7..ff23b0b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -18,9 +18,11 @@ Include the MagicInput, macOS and Windows versions, your network setup, reproduc ## Security boundaries - There is no MagicInput server; the two computers talk directly. -- Every connection is encrypted with the Noise protocol (`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`); the pre-shared key is derived from the pairing code, which is never transmitted. Without the code a device can't complete the handshake. +- Pairing uses a password-authenticated key exchange (symmetric SPAKE2 over Ed25519, bound to the protocol version). The pairing code is never transmitted, and recording a connection doesn't let anyone test guesses of the code offline: each connection attempt can check at most one guess. +- The key from that exchange, through HKDF-SHA256 over the exchange transcript, is the pre-shared key of the Noise protocol (`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`) that encrypts everything afterwards. Without the code a device can't complete the handshake. +- Discovery (mDNS) advertises only a random computer id, the computer's name and the protocol version; nothing derived from the pairing code. +- Failed pairing attempts are paced: a few per address, then a growing wait between attempts, plus an overall limit per minute for addresses that never paired. Failed attempts are logged without the code. - Only peers on the same local subnet are accepted or dialed; connections from the internet, VPNs and Tailscale addresses are refused. -- The pairing code is short (about 39 bits) so it's easy to type. Someone on your local network who records a MagicInput connection could recover it by offline guessing and then connect. The local-network restriction is the main boundary; on untrusted networks (cafés, shared offices), generate a new code afterwards. Moving to a password-authenticated key exchange (PAKE), which removes offline guessing, is planned. - Configuration (including the pairing code) is stored unencrypted in your user profile. - Users are responsible for the security of their operating system accounts and local network. diff --git a/docs/AI_SETUP.md b/docs/AI_SETUP.md index 5d9a320..657a664 100644 --- a/docs/AI_SETUP.md +++ b/docs/AI_SETUP.md @@ -111,7 +111,7 @@ The output looks like this: | `role` | Meaning | What to do | | --- | --- | --- | | `first` | No other computer running MagicInput was found. | Give the person this computer's `pairing_code` and tell them to install MagicInput on the other computer (they can paste the prompt from the README into an assistant there). On the other computer, pairing is `magicinput pair `. | -| `second` | Another computer runs MagicInput (`nearby`) but with a different code. | Get that computer's code and pair this one with it (below). | +| `second` | Another computer runs MagicInput (`nearby`) but isn't connected. Whether it uses the same code is only known once they connect. | Get that computer's code and pair this one with it (below). | | `paired` | Already connected (`connected_to`). | Skip to step 5. | `next_step` always says the next thing to do in plain words. `service` is `running`, `waiting_for_permission` (Mac permissions, step 2) or `not_running` (run `install` again). @@ -153,7 +153,7 @@ PowerShell: while (-not ((& $MI status --json | Out-String | ConvertFrom-Json).connected_to)) { Start-Sleep 3 }; & $MI status ``` -Usually this takes a few seconds. If it hasn't connected after about 30 seconds, see Troubleshooting. +Usually this takes a few seconds. After a few attempts with a wrong code, the computers wait up to ten seconds between tries, so give it half a minute after pairing. If it still hasn't connected, see Troubleshooting. ## 7. Tell the person how to use it @@ -173,8 +173,9 @@ If the person tells you where the other screen is, you can pin it without the pa | `service: "waiting_for_permission"` (Mac) | The person still needs to turn on MagicInput under Accessibility **and** Input Monitoring (step 2). | | `service: "not_running"` | Run `install` again. On Windows check the task: `schtasks /query /tn magicinput`. | | `nearby` is empty on **both** computers | They're on different networks, or the network blocks discovery. Find the other computer's IP address and point this one at it: `magicinput peer 192.168.1.20`. | -| `nearby` shows the other computer with `same_code: true` but `connected_to` stays empty | Usually the Windows firewall. In PowerShell run `Get-NetConnectionProfile`; if the network is `Public`, MagicInput's rule (private networks) doesn't apply. Ask the person before changing it: `Set-NetConnectionProfile -InterfaceAlias "" -NetworkCategory Private`. | -| `nearby` shows `same_code: false` | The codes differ: pair again (step 4) using the other computer's code. | +| `nearby` shows the other computer, both show the same `pairing_code`, but `connected_to` stays empty after half a minute | Usually the Windows firewall. In PowerShell run `Get-NetConnectionProfile`; if the network is `Public`, MagicInput's rule (private networks) doesn't apply. Ask the person before changing it: `Set-NetConnectionProfile -InterfaceAlias "" -NetworkCategory Private`. | +| `nearby` shows the other computer and the two `pairing_code`s differ | Pair again (step 4) using the other computer's code. | +| `nearby` shows `compatible: false` | The other computer runs a different version of MagicInput: update MagicInput on both computers. | | Connected, but the pointer doesn't cross | In Auto mode push **firmly**. With a pinned arrangement the pointer only crosses where the screens touch in Displays. | | Can't click into some Windows apps | Apps running as administrator need MagicInput to have admin rights too; the installer sets that up. Reinstall with the admin prompt accepted. | | Pointer stutters over Wi-Fi | See the Tips section of the README (5 GHz channel 149). | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 380a628..fd8159a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -48,8 +48,9 @@ Bursts of movement are merged before sending. On the receiving side, movement th ## Discovery and security -- Each computer advertises `_magicinput._tcp` over mDNS with a random id and a short tag derived from the pairing code; it only dials peers with the same tag. Of two peers, the one with the smaller id dials. -- Connections use Noise `NNpsk0_25519_ChaChaPoly_BLAKE2s` over TCP (port 24842, `TCP_NODELAY`; on macOS marked as interactive traffic for Wi-Fi). The pre-shared key is SHA-256 of the normalized pairing code. See [SECURITY.md](../SECURITY.md) for the limits of a short code. +- Each computer advertises `_magicinput._tcp` over mDNS with a random id, its name and the protocol version (`id`, `n`, `v`); nothing derived from the pairing code. It dials other MagicInput computers with the same protocol version (up to 16) and lets pairing decide whether they belong together. Of two peers, the one with the smaller id dials. +- Connections run over TCP (port 24842, `TCP_NODELAY`; on macOS marked as interactive traffic for Wi-Fi). Each side first sends `MagicInp` plus its protocol version, so a computer on another version gets a clear "update MagicInput on both computers" error. Then both run symmetric SPAKE2 (Ed25519, identity `magicinput/pake/v`) on the normalized pairing code. HKDF-SHA256 of the SPAKE2 key, salted with the transcript so far, becomes the pre-shared key for Noise `NNpsk0_25519_ChaChaPoly_BLAKE2s`, which also takes the transcript as its prologue and carries all further traffic. With different codes the Noise handshake fails. +- Pairing attempts are paced per address in both directions: three in a row, then a wait that doubles up to ten seconds (forgotten after ten quiet minutes, cleared on success or when the local code changes). Incoming attempts from addresses that never paired also share a budget of 30 per minute, and at most 8 incoming connections pair at once. - Only addresses in the subnet of one of the computer's own network interfaces are accepted or dialed; CGNAT/Tailscale ranges are excluded. ## Settings panel diff --git a/src/config.rs b/src/config.rs index 353e2d7..de4a413 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,7 +1,6 @@ use std::path::PathBuf; use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; use crate::geom::{Placement, Rect}; use crate::proto::Side; @@ -146,17 +145,6 @@ impl Config { eprintln!("Could not save {}: {e}", path.display()); } } - - /// 32-byte pre-shared key for the encrypted channel. - pub fn psk(&self) -> [u8; 32] { - Sha256::digest(format!("magicinput/v1/psk/{}", normalize_code(&self.code))).into() - } - - /// Short public tag so computers only try to talk to others paired with the same code. - pub fn group(&self) -> String { - let h = Sha256::digest(format!("magicinput/v1/group/{}", normalize_code(&self.code))); - h[..4].iter().map(|b| format!("{b:02x}")).collect() - } } pub fn new_code() -> String { @@ -177,11 +165,21 @@ pub fn normalize_code(code: &str) -> String { } fn random_string(len: usize, alphabet: &[u8]) -> String { - let mut buf = vec![0u8; len]; - getrandom::fill(&mut buf).expect("no system randomness"); - buf.iter() - .map(|b| alphabet[*b as usize % alphabet.len()] as char) - .collect() + let mut out = String::with_capacity(len); + let mut buf = [0u8; 32]; + while out.len() < len { + getrandom::fill(&mut buf).expect("no system randomness"); + out.extend(buf.iter().filter_map(|&b| pick(b, alphabet)).take(len - out.len())); + } + out +} + +/// The character for one random byte, or `None` for the few top byte values that would make +/// some characters more likely than others (they are skipped and another byte is drawn). +fn pick(b: u8, alphabet: &[u8]) -> Option { + let n = alphabet.len(); + let usable = 256 - 256 % n; + ((b as usize) < usable).then(|| alphabet[b as usize % n] as char) } fn hostname() -> String { @@ -224,8 +222,27 @@ mod tests { fn codes_normalize_the_same() { let a = Config { code: "k7qp-3mzd".into(), ..Default::default() }; let b = Config { code: "K7QP 3MZD".into(), ..Default::default() }; - assert_eq!(a.psk(), b.psk()); - assert_eq!(a.group(), b.group()); - assert_eq!(new_code().len(), 9); + assert_eq!(normalize_code(&a.code), normalize_code(&b.code)); + assert_eq!(normalize_code("o0-il1"), "00111"); + let code = new_code(); + assert_eq!(code.len(), 9); + assert_eq!(code.as_bytes()[4], b'-'); + assert!(code.bytes().filter(|&c| c != b'-').all(|c| CODE_ALPHABET.contains(&c))); + } + + #[test] + fn every_code_character_is_equally_likely() { + for alphabet in [CODE_ALPHABET, b"abcdefghijklmnopqrstuvwxyz0123456789".as_slice()] { + let mut counts = std::collections::HashMap::new(); + for b in 0..=255u8 { + if let Some(c) = pick(b, alphabet) { + *counts.entry(c).or_insert(0) += 1; + } + } + assert_eq!(counts.len(), alphabet.len()); + let per_char = 256 / alphabet.len(); + assert!(counts.values().all(|&n| n == per_char), "{counts:?}"); + } + assert_eq!(random_string(500, CODE_ALPHABET).len(), 500); } } diff --git a/src/lib.rs b/src/lib.rs index 069c8c6..bbc084c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -206,7 +206,7 @@ fn run(mut cfg: Config) { std::process::exit(0); }); - log::info!("magicinput {} running as \"{}\" (code {})", env!("CARGO_PKG_VERSION"), cfg.name, cfg.code); + log::info!("magicinput {} running as \"{}\"", env!("CARGO_PKG_VERSION"), cfg.name); log::info!("Looking for your other computer… (Ctrl+Alt+Esc / Control+Option+Esc brings the pointer back)"); if let Err(e) = platform::run_capture() { exit(&e); diff --git a/src/net.rs b/src/net.rs index 2bc9386..176a8f0 100644 --- a/src/net.rs +++ b/src/net.rs @@ -1,28 +1,39 @@ -//! Encrypted peer connection (Noise NNpsk0 over TCP) plus LAN discovery (mDNS). +//! Encrypted peer connection (SPAKE2 pairing, then Noise NNpsk0 over TCP) plus LAN discovery (mDNS). -use std::collections::HashMap; +use std::collections::{HashMap, HashSet, VecDeque}; use std::error::Error; use std::fs::File; use std::io::{Read, Write}; use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream, ToSocketAddrs}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; use crossbeam_channel::{Receiver, RecvTimeoutError}; use log::{debug, info, warn}; use mdns_sd::{ServiceDaemon, ServiceEvent, ServiceInfo}; +use sha2::Sha256; use snow::TransportState; +use spake2::{Ed25519Group, Identity, Password, Spake2}; -use crate::config::Config; +use crate::config::{Config, normalize_code}; use crate::core::{Core, Peer}; use crate::proto::{Msg, Os, PROTOCOL_VERSION}; type Res = Result>; const NOISE: &str = "Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s"; +/// Starts the first frame each side sends, followed by its `PROTOCOL_VERSION` (big-endian u32). +const MAGIC: &[u8; 8] = b"MagicInp"; +/// Labels binding the pairing exchange and the key it yields to this protocol. +const PAKE_ID: &str = "magicinput/pake"; +const PSK_INFO: &[u8] = b"magicinput/noise-psk"; +/// At most this many incoming connections may be pairing at once. +const MAX_PENDING: usize = 8; +/// At most this many discovered computers are remembered (and dialed). +const MAX_FOUND: usize = 16; const SERVICE: &str = "_magicinput._tcp.local."; const MAX_FRAME: usize = 65535; const TIMEOUT: Duration = Duration::from_secs(5); @@ -45,14 +56,11 @@ struct Active { struct Found { host: String, port: u16, - /// Pairing group tag they advertise; only peers with ours are dialed. - group: String, addrs: Vec, } pub struct Net { cfg: RwLock, - psk: Mutex<[u8; 32]>, core: &'static Core, active: Mutex>, next_gen: AtomicU64, @@ -61,6 +69,11 @@ pub struct Net { mdns: Mutex>, /// Full name of our current mDNS registration. registered: Mutex>, + /// Paces pairing attempts from other computers, and to them. + inbound: Mutex, + outbound: Mutex, + /// Incoming connections still pairing. + pending: AtomicUsize, } pub fn start(cfg: Config, core: &'static Core, out: Receiver) -> Res> { @@ -78,7 +91,6 @@ pub fn start(cfg: Config, core: &'static Core, out: Receiver) -> Res) -> Res) -> Res= MAX_PENDING { + debug!("Ignoring connection from {addr}: too many computers pairing at once"); + continue; + } + if !n.inbound.lock().unwrap().try_begin(addr.ip(), Instant::now()) { + debug!("Ignoring connection from {addr}: waiting after failed pairing attempts"); + continue; + } + n.pending.fetch_add(1, Ordering::SeqCst); let n = n.clone(); thread::spawn(move || { - if let Err(e) = n.establish(stream, false) { - warn!("Incoming connection from {addr:?} failed: {e} (different pairing code?)"); + if let Err(e) = n.clone().establish(stream, false) { + let wait = n.inbound.lock().unwrap().waiting(addr.ip()); + warn!("Incoming connection from {addr} failed: {e}{}", pause(wait)); } }); } @@ -123,7 +148,9 @@ impl Net { pub fn reload(&self, new: Config) { let old = std::mem::replace(&mut *self.cfg.write().unwrap(), new.clone()); if old.code != new.code || old.name != new.name { - *self.psk.lock().unwrap() = new.psk(); + // Attempts that failed with the previous code don't count against anyone. + self.inbound.lock().unwrap().clear(); + self.outbound.lock().unwrap().clear(); if let Err(e) = self.register() { warn!("Could not re-advertise: {e}"); } @@ -142,10 +169,9 @@ impl Net { if let Some(old) = self.registered.lock().unwrap().take() { let _ = mdns.unregister(&old); } - let group = cfg.group(); let instance = format!("{}-{}", cfg.name, cfg.id); let host = format!("magicinput-{}.local.", cfg.id); - let props = [("id", cfg.id.as_str()), ("g", group.as_str()), ("n", cfg.name.as_str())]; + let props = txt_properties(&cfg); let info = ServiceInfo::new(SERVICE, &instance, &host, "", cfg.port, &props[..])?.enable_addr_auto(); *self.registered.lock().unwrap() = Some(info.get_fullname().to_string()); mdns.register(info)?; @@ -156,19 +182,19 @@ impl Net { loop { if self.active.lock().unwrap().is_none() { let cfg = self.cfg.read().unwrap().clone(); - let group = cfg.group(); let mut targets: Vec = Vec::new(); if let Some(addr) = &cfg.peer_addr { let with_port = if addr.contains(':') { addr.clone() } else { format!("{addr}:{}", cfg.port) }; targets.extend(with_port.to_socket_addrs().into_iter().flatten().filter(|a| same_lan(a.ip()))); } - // For discovered peers only the smaller id dials, so we don't race each other. + // For discovered peers only the smaller id dials, so we don't race each other. Any + // MagicInput computer is dialed: pairing decides whether it's ours. let peers: Vec<(Vec, String, u16)> = self .found .lock() .unwrap() .iter() - .filter(|(id, f)| cfg.id < **id && f.group == group) + .filter(|(id, _)| cfg.id < **id) .map(|(_, f)| (f.addrs.clone(), f.host.clone(), f.port)) .collect(); for (addrs, host, port) in peers { @@ -181,12 +207,23 @@ impl Net { targets.extend(addrs.into_iter().filter(|a| a.is_ipv4() && same_lan(a.ip()))); } for addr in targets { + if !self.outbound.lock().unwrap().try_begin(addr.ip(), Instant::now()) { + debug!("{addr}: waiting after failed pairing attempts"); + continue; + } match TcpStream::connect_timeout(&addr, Duration::from_secs(2)) { Ok(s) => match self.clone().establish(s, true) { Ok(()) => break, - Err(e) => warn!("Connecting to {addr} failed: {e}"), + Err(e) => { + let wait = self.outbound.lock().unwrap().waiting(addr.ip()); + warn!("Connecting to {addr} failed: {e}{}", pause(wait)); + } }, - Err(e) => debug!("{addr}: {e}"), + Err(e) => { + // Nobody answered, so no pairing was attempted. + self.outbound.lock().unwrap().not_attempted(addr.ip()); + debug!("{addr}: {e}"); + } } } } @@ -200,18 +237,24 @@ impl Net { *self.mdns.lock().unwrap() = Some(mdns); self.register()?; thread::spawn(move || { + let mut other_versions = HashSet::new(); while let Ok(ev) = rx.recv() { if let ServiceEvent::ServiceRemoved(_, fullname) = &ev { // Forget addresses of computers that went away, so we stop dialing them. self.found.lock().unwrap().retain(|id, _| !fullname.contains(id.as_str())); } if let ServiceEvent::ServiceResolved(s) = ev { - let (Some(id), Some(g)) = (s.get_property_val_str("id"), s.get_property_val_str("g")) else { - continue; - }; + let Some(id) = s.get_property_val_str("id") else { continue }; if id == self.cfg.read().unwrap().id { continue; } + // Older versions can't pair with this one; their computers don't advertise `v`. + if s.get_property_val_str("v") != Some(PROTOCOL_VERSION.to_string().as_str()) { + if other_versions.insert(id.to_string()) { + warn!("{} runs a different version of MagicInput: update MagicInput on both computers", s.host); + } + continue; + } let addrs: Vec = s .get_addresses_v4() .into_iter() @@ -219,10 +262,13 @@ impl Net { .collect(); debug!("Discovered {id} ({}) at {addrs:?}", s.host); let mut found = self.found.lock().unwrap(); + if !found.contains_key(id) && found.len() >= MAX_FOUND { + debug!("Ignoring {id}: too many computers nearby"); + continue; + } let entry = found .entry(id.to_string()) - .or_insert(Found { host: s.host.clone(), port: s.get_port(), group: String::new(), addrs: Vec::new() }); - entry.group = g.to_string(); + .or_insert(Found { host: s.host.clone(), port: s.get_port(), addrs: Vec::new() }); entry.host = s.host.clone(); entry.port = s.get_port(); if !addrs.is_empty() { @@ -236,12 +282,17 @@ impl Net { /// Handshake, exchange hellos, then run the reader until the connection drops. fn establish(self: Arc, mut stream: TcpStream, dialer: bool) -> Res<()> { - stream.set_nodelay(true)?; - prioritize(&stream); - stream.set_read_timeout(Some(TIMEOUT))?; - stream.set_write_timeout(Some(TIMEOUT))?; - let psk = *self.psk.lock().unwrap(); - let mut noise = handshake(&mut stream, &psk, dialer)?; + let paired = (|| { + stream.set_nodelay(true)?; + prioritize(&stream); + stream.set_read_timeout(Some(TIMEOUT))?; + stream.set_write_timeout(Some(TIMEOUT))?; + self.pair(&mut stream, dialer) + })(); + if !dialer { + self.pending.fetch_sub(1, Ordering::SeqCst); + } + let mut noise = paired?; let cfg = self.cfg.read().unwrap().clone(); let hello = Msg::Hello { @@ -264,7 +315,7 @@ impl Net { return Err("expected hello".into()); }; if version != PROTOCOL_VERSION { - return Err(format!("{name} runs protocol v{version}, we run v{PROTOCOL_VERSION}; update both").into()); + return Err(format!("{name} runs protocol v{version}, this computer v{PROTOCOL_VERSION}: update MagicInput on both computers").into()); } if id == cfg.id { return Err("connected to myself".into()); @@ -316,6 +367,17 @@ impl Net { Ok(()) } + /// Pair over a fresh connection with the current code; success clears earlier failed attempts + /// from (or to) that address. + fn pair(&self, stream: &mut TcpStream, initiator: bool) -> Res { + let code = self.cfg.read().unwrap().code.clone(); + let noise = secure(stream, &code, initiator)?; + let ip = stream.peer_addr()?.ip(); + let throttle = if initiator { &self.outbound } else { &self.inbound }; + throttle.lock().unwrap().succeeded(ip); + Ok(noise) + } + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] /// Offer a file to the other computer over a connection of its own. `force`: our user is /// working on the other computer. Returns whether it took the file and saved all of it. @@ -330,13 +392,12 @@ impl Net { stream.set_nodelay(true)?; stream.set_read_timeout(Some(FILE_TIMEOUT))?; stream.set_write_timeout(Some(FILE_TIMEOUT))?; - let psk = *self.psk.lock().unwrap(); - let mut noise = handshake(&mut stream, &psk, true)?; + let mut noise = self.pair(&mut stream, true)?; let Msg::Hello { version, .. } = read_msg(&mut stream, &mut noise)? else { return Err("expected hello".into()); }; if version != PROTOCOL_VERSION { - return Err(format!("the other computer runs protocol v{version}, we run v{PROTOCOL_VERSION}").into()); + return Err(format!("the other computer runs protocol v{version}, this one v{PROTOCOL_VERSION}: update MagicInput on both computers").into()); } offer_file(&mut stream, &mut noise, path, force, crate::platform::idle_ms()) } @@ -388,15 +449,20 @@ impl Net { pub struct Nearby { pub name: String, pub address: Option, - /// Uses the same pairing code as this computer. - pub same_code: bool, + /// Runs a version of MagicInput that can pair with this one. Whether it uses the same code + /// is only known once it connects. + pub compatible: bool, +} + +/// What we advertise over mDNS. Nothing here depends on the pairing code. +fn txt_properties(cfg: &Config) -> Vec<(&'static str, String)> { + vec![("id", cfg.id.clone()), ("n", cfg.name.clone()), ("v", PROTOCOL_VERSION.to_string())] } /// Look for other computers running MagicInput on the local network (for `magicinput status`). pub fn discover(cfg: &Config, wait: Duration) -> Vec { let Ok(mdns) = ServiceDaemon::new() else { return Vec::new() }; let Ok(rx) = mdns.browse(SERVICE) else { return Vec::new() }; - let group = cfg.group(); let deadline = std::time::Instant::now() + wait; let mut found: HashMap = HashMap::new(); while let Some(left) = deadline.checked_duration_since(std::time::Instant::now()) { @@ -412,8 +478,8 @@ pub fn discover(cfg: &Config, wait: Duration) -> Vec { instance.strip_suffix(&format!("-{id}")).unwrap_or(instance).to_string() }); let address = s.get_addresses_v4().into_iter().next().map(|ip| ip.to_string()); - let same_code = s.get_property_val_str("g") == Some(group.as_str()); - found.insert(id.to_string(), Nearby { name, address, same_code }); + let compatible = s.get_property_val_str("v") == Some(PROTOCOL_VERSION.to_string().as_str()); + found.insert(id.to_string(), Nearby { name, address, compatible }); } Ok(_) => {} Err(_) => break, @@ -469,22 +535,151 @@ fn same_lan(ip: IpAddr) -> bool { }) } -fn handshake(stream: &mut TcpStream, psk: &[u8; 32], initiator: bool) -> Res { - let builder = snow::Builder::new(NOISE.parse()?).psk(0, psk)?; +/// Pair with the computer on the other end of `stream` and open the encrypted channel. +/// +/// Each side first sends `MAGIC` and its protocol version, then a symmetric SPAKE2 message +/// for the normalized pairing code. HKDF of the SPAKE2 key (salted with everything sent so +/// far) is the Noise pre-shared key, and the same transcript is the Noise prologue. Only a +/// computer with the same code and protocol version completes the Noise handshake; the code +/// itself is never sent. +fn secure(stream: &mut TcpStream, code: &str, initiator: bool) -> Res { + let mut intro = MAGIC.to_vec(); + intro.extend_from_slice(&PROTOCOL_VERSION.to_be_bytes()); + write_frame(stream, &intro)?; + let theirs = read_frame(stream).map_err(|e| { + format!("the other computer closed the connection before pairing ({e}); it may run an older MagicInput (update MagicInput on both computers), or be waiting after failed attempts") + })?; + if theirs.len() != intro.len() || theirs[..MAGIC.len()] != MAGIC[..] { + return Err("the other computer runs an older MagicInput: update MagicInput on both computers".into()); + } + let version = u32::from_be_bytes(theirs[MAGIC.len()..].try_into()?); + if version != PROTOCOL_VERSION { + return Err(format!("the other computer runs protocol v{version}, this one v{PROTOCOL_VERSION}: update MagicInput on both computers").into()); + } + + let id = format!("{PAKE_ID}/v{PROTOCOL_VERSION}"); + let (pake, ours) = Spake2::::start_symmetric(&Password::new(normalize_code(code).as_bytes()), &Identity::new(id.as_bytes())); + write_frame(stream, &ours)?; + let peer = read_frame(stream).map_err(|e| format!("the other computer stopped pairing ({e}); check both use the same code"))?; + let key = pake.finish(&peer).map_err(|e| format!("invalid pairing message: {e:?}"))?; + + let (first, second) = if initiator { (&ours, &peer) } else { (&peer, &ours) }; + let mut transcript = intro; + transcript.extend_from_slice(first); + transcript.extend_from_slice(second); + let mut psk = [0u8; 32]; + hkdf::Hkdf::::new(Some(&transcript), &key) + .expand(PSK_INFO, &mut psk) + .map_err(|_| "key derivation failed")?; + + let builder = snow::Builder::new(NOISE.parse()?).psk(0, &psk)?.prologue(&transcript)?; let mut buf = vec![0u8; MAX_FRAME]; + let mismatch = "the pairing codes don't match"; let mut hs = if initiator { builder.build_initiator()? } else { builder.build_responder()? }; if initiator { let n = hs.write_message(&[], &mut buf)?; write_frame(stream, &buf[..n])?; - hs.read_message(&read_frame(stream)?, &mut buf)?; + let reply = read_frame(stream).map_err(|_| mismatch)?; + hs.read_message(&reply, &mut buf).map_err(|_| mismatch)?; } else { - hs.read_message(&read_frame(stream)?, &mut buf)?; + hs.read_message(&read_frame(stream)?, &mut buf).map_err(|_| mismatch)?; let n = hs.write_message(&[], &mut buf)?; write_frame(stream, &buf[..n])?; } Ok(hs.into_transport_mode()?) } +/// Log text for how long an address waits before its next pairing attempt. +fn pause(wait: Duration) -> String { + if wait.is_zero() { String::new() } else { format!(" (next pairing attempt allowed in {} s)", wait.as_secs()) } +} + +/// Paces pairing attempts per address so codes can't be tried quickly. Each address gets a +/// few attempts in a row, then waits longer before each next one (up to ten seconds); waiting +/// is forgotten after ten quiet minutes. An attempt counts as failed from the moment it +/// starts until it succeeds, so parallel attempts are paced too. Inbound, addresses that +/// never paired also share an overall budget per minute. +struct Throttle { + peers: HashMap, + /// Whether the overall budget applies. + overall: bool, + /// Starts of recent attempts from addresses that never paired. + recent: VecDeque, + /// Addresses that paired since MagicInput started. + paired: HashSet, +} + +#[derive(Clone, Copy)] +struct Strikes { + count: u32, + last: Instant, +} + +impl Throttle { + /// Attempts in a row before waiting starts. + const FREE: u32 = 3; + const MAX_WAIT: Duration = Duration::from_secs(10); + const FORGET: Duration = Duration::from_secs(600); + const MINUTE: Duration = Duration::from_secs(60); + /// Attempts per minute from addresses that never paired, all together. + const OVERALL: usize = 30; + + fn new(overall: bool) -> Throttle { + Throttle { peers: HashMap::new(), overall, recent: VecDeque::new(), paired: HashSet::new() } + } + + /// How long to wait after `count` attempts that didn't succeed. + fn wait(count: u32) -> Duration { + match count.checked_sub(Self::FREE + 1) { + None => Duration::ZERO, + Some(n) => Duration::from_secs(1 << n.min(6)).min(Self::MAX_WAIT), + } + } + + /// How long `ip` has to wait before its next attempt. + fn waiting(&self, ip: IpAddr) -> Duration { + self.peers.get(&ip).map_or(Duration::ZERO, |s| Self::wait(s.count)) + } + + /// Whether an attempt with `ip` may start now; if so it's counted. + fn try_begin(&mut self, ip: IpAddr, now: Instant) -> bool { + self.peers.retain(|_, s| now.duration_since(s.last) < Self::FORGET); + if self.peers.get(&ip).is_some_and(|s| now < s.last + Self::wait(s.count)) { + return false; + } + if self.overall && !self.paired.contains(&ip) { + while self.recent.front().is_some_and(|t| now.duration_since(*t) >= Self::MINUTE) { + self.recent.pop_front(); + } + if self.recent.len() >= Self::OVERALL { + return false; + } + self.recent.push_back(now); + } + let s = self.peers.entry(ip).or_insert(Strikes { count: 0, last: now }); + s.count += 1; + s.last = now; + true + } + + fn succeeded(&mut self, ip: IpAddr) { + self.peers.remove(&ip); + self.paired.insert(ip); + } + + /// The attempt never reached the other computer. + fn not_attempted(&mut self, ip: IpAddr) { + if let Some(s) = self.peers.get_mut(&ip) { + s.count = s.count.saturating_sub(1); + } + } + + fn clear(&mut self) { + self.peers.clear(); + self.recent.clear(); + } +} + /// The other computer offers a file: take it into Downloads if its user is working here (or /// this computer was used more recently), and show it. fn receive_offer(stream: &mut TcpStream, noise: &mut TransportState, name: &str, size: u64, force: bool, idle_ms: u64) -> Res<()> { @@ -630,25 +825,35 @@ fn read_frame(stream: &mut TcpStream) -> Res> { mod tests { use super::*; - fn pair(psk_a: [u8; 32], psk_b: [u8; 32]) -> (Res, Res, TcpStream, TcpStream) { + /// Pair a dialer using `code_a` with a listener using `code_b`. + fn pair(code_a: &'static str, code_b: &str) -> (Res, Res, TcpStream, TcpStream) { + let (mut b, t) = dial(move |s| secure(s, code_a, true)); + let rb = secure(&mut b, code_b, false); + if rb.is_err() { + // As `establish` does: a failed connection is dropped. + let _ = b.shutdown(std::net::Shutdown::Both); + } + let (ra, a) = t.join().unwrap(); + (ra, rb, a, b) + } + + /// Run `f` on a connection to a local listener; returns the listener's end. + fn dial(f: impl FnOnce(&mut TcpStream) -> T + Send + 'static) -> (TcpStream, thread::JoinHandle<(T, TcpStream)>) { let l = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = l.local_addr().unwrap(); let t = thread::spawn(move || { let mut s = TcpStream::connect(addr).unwrap(); s.set_read_timeout(Some(TIMEOUT)).unwrap(); - let r = handshake(&mut s, &psk_a, true); - (r, s) + (f(&mut s), s) }); - let (mut b, _) = l.accept().unwrap(); + let (b, _) = l.accept().unwrap(); b.set_read_timeout(Some(TIMEOUT)).unwrap(); - let rb = handshake(&mut b, &psk_b, false); - let (ra, a) = t.join().unwrap(); - (ra, rb, a, b) + (b, t) } #[test] fn encrypted_roundtrip() { - let (ra, rb, mut a, mut b) = pair([7; 32], [7; 32]); + let (ra, rb, mut a, mut b) = pair("K7QP-3MZD", "k7qp 3mzd"); let (mut na, mut nb) = (ra.unwrap(), rb.unwrap()); let m = Msg::Key { hid: 0x04, down: true }; write_msg(&mut a, &mut na, &m).unwrap(); @@ -675,7 +880,7 @@ mod tests { std::fs::write(&src, &data).unwrap(); std::fs::write(dir.join("out/photo.heic"), b"already here").unwrap(); - let (ra, rb, mut a, mut b) = pair([3; 32], [3; 32]); + let (ra, rb, mut a, mut b) = pair("AAAA-BBBB", "AAAA-BBBB"); let (mut na, mut nb) = (ra.unwrap(), rb.unwrap()); let sender = thread::spawn(move || offer_file(&mut a, &mut na, &src, true, 0).unwrap()); let Msg::Offer { name, size, force, .. } = read_msg(&mut b, &mut nb).unwrap() else { panic!("expected an offer") }; @@ -694,7 +899,7 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); let src = dir.join("a.txt"); std::fs::write(&src, b"hi").unwrap(); - let (ra, rb, mut a, mut b) = pair([4; 32], [4; 32]); + let (ra, rb, mut a, mut b) = pair("AAAA-BBBB", "AAAA-BBBB"); let (mut na, mut nb) = (ra.unwrap(), rb.unwrap()); let sender = thread::spawn(move || offer_file(&mut a, &mut na, &src, false, 0).unwrap()); let Msg::Offer { name, size, .. } = read_msg(&mut b, &mut nb).unwrap() else { panic!("expected an offer") }; @@ -714,7 +919,114 @@ mod tests { #[test] fn wrong_code_is_rejected() { - let (_ra, rb, _a, _b) = pair([1; 32], [2; 32]); - assert!(rb.is_err()); + let (ra, rb, _a, _b) = pair("K7QP-3MZD", "K7QP-3MZE"); + assert!(rb.unwrap_err().to_string().contains("codes don't match")); + assert!(ra.is_err()); + } + + #[test] + fn older_versions_are_told_to_update() { + // MagicInput 0.6.2 and older open with a bare Noise message. + let (mut b, t) = dial(|s| { + let psk = [9; 32]; + let mut hs = snow::Builder::new(NOISE.parse().unwrap()).psk(0, &psk).unwrap().build_initiator().unwrap(); + let mut buf = vec![0u8; MAX_FRAME]; + let n = hs.write_message(&[], &mut buf).unwrap(); + write_frame(s, &buf[..n]).unwrap(); + }); + let e = secure(&mut b, "K7QP-3MZD", false).unwrap_err().to_string(); + assert!(e.contains("update MagicInput on both computers"), "{e}"); + t.join().unwrap(); + + // A future version with the same opening. + let (mut b, t) = dial(|s| { + let mut intro = MAGIC.to_vec(); + intro.extend_from_slice(&(PROTOCOL_VERSION + 1).to_be_bytes()); + write_frame(s, &intro).unwrap(); + }); + let e = secure(&mut b, "K7QP-3MZD", false).unwrap_err().to_string(); + assert!(e.contains("update MagicInput on both computers"), "{e}"); + t.join().unwrap(); + } + + #[test] + fn advertisement_has_nothing_from_the_pairing_code() { + let a = Config { code: "K7QP-3MZD".into(), ..Default::default() }; + let b = Config { code: "ABCD-EFGH".into(), ..a.clone() }; + assert_eq!(txt_properties(&a), txt_properties(&b)); + let keys: Vec<&str> = txt_properties(&a).iter().map(|(k, _)| *k).collect(); + assert_eq!(keys, ["id", "n", "v"]); + for (_, v) in txt_properties(&a) { + assert!(!v.contains("K7QP") && !v.contains("3MZD")); + } + } + + #[test] + fn failed_attempts_are_paced() { + let ip: IpAddr = "192.168.1.20".parse().unwrap(); + let other: IpAddr = "192.168.1.21".parse().unwrap(); + let t0 = Instant::now(); + let mut th = Throttle::new(true); + for _ in 0..=Throttle::FREE { + assert!(th.try_begin(ip, t0)); + } + // Waiting starts, and grows with each further attempt. + assert!(!th.try_begin(ip, t0)); + assert!(th.try_begin(other, t0), "other addresses aren't held up"); + assert!(th.try_begin(ip, t0 + Duration::from_secs(1))); + assert!(!th.try_begin(ip, t0 + Duration::from_secs(2))); + assert!(th.try_begin(ip, t0 + Duration::from_secs(3))); + let mut t = t0 + Duration::from_secs(3); + for _ in 0..20 { + t += Throttle::MAX_WAIT; + assert!(th.try_begin(ip, t), "the wait stops growing"); + } + assert!(!th.try_begin(ip, t + Throttle::MAX_WAIT - Duration::from_secs(1))); + assert!(th.try_begin(ip, t + Throttle::FORGET + Throttle::MAX_WAIT), "forgotten after a quiet while"); + + // Pairing clears the count. + th.succeeded(ip); + for _ in 0..=Throttle::FREE { + assert!(th.try_begin(ip, t0)); + } + // Outgoing attempts that reached nobody don't count. + let mut out = Throttle::new(false); + for _ in 0..10 { + assert!(out.try_begin(ip, t0)); + out.not_attempted(ip); + } + } + + #[test] + fn computers_that_never_paired_share_a_budget() { + let t0 = Instant::now(); + let mut th = Throttle::new(true); + let known: IpAddr = "10.0.0.1".parse().unwrap(); + assert!(th.try_begin(known, t0)); + th.succeeded(known); + // The known computer's first attempt used up part of the budget. + for i in 1..Throttle::OVERALL { + assert!(th.try_begin(IpAddr::V4(Ipv4Addr::new(10, 0, 1, i as u8)), t0)); + } + assert!(!th.try_begin("10.0.2.1".parse().unwrap(), t0)); + assert!(th.try_begin(known, t0), "a computer that paired before still gets in"); + assert!(th.try_begin("10.0.2.1".parse().unwrap(), t0 + Throttle::MINUTE)); + } + + #[test] + fn right_code_pairs_after_failed_attempts() { + let net_ip: IpAddr = "127.0.0.1".parse().unwrap(); + let mut th = Throttle::new(true); + let t0 = Instant::now(); + for _ in 0..Throttle::FREE { + assert!(th.try_begin(net_ip, t0)); + let (_, rb, _, _) = pair("WRNG-C0DE", "K7QP-3MZD"); + assert!(rb.is_err()); + } + assert!(th.try_begin(net_ip, t0)); + let (ra, rb, _, _) = pair("K7QP-3MZD", "K7QP-3MZD"); + assert!(ra.is_ok() && rb.is_ok()); + th.succeeded(net_ip); + assert!(th.try_begin(net_ip, t0)); } } diff --git a/src/proto.rs b/src/proto.rs index 774c13b..4756600 100644 --- a/src/proto.rs +++ b/src/proto.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::config::Layout; use crate::geom::Rect; -pub const PROTOCOL_VERSION: u32 = 5; +pub const PROTOCOL_VERSION: u32 = 6; /// Which edge of *this* computer's screens the other computer sits on. #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] diff --git a/src/status.rs b/src/status.rs index 57c13fe..42e600b 100644 --- a/src/status.rs +++ b/src/status.rs @@ -115,14 +115,11 @@ pub fn report(cfg: &mut Config, json: bool) { format!("Start it again: {cmd} install") } else if let Some(peer) = &connected { format!("All set: connected to {peer}. Move the pointer off the edge of the screen toward it (in Auto mode, push firmly past the left or right edge).") - } else if let Some(n) = nearby.iter().find(|n| n.same_code) { - format!( - "{} uses the same pairing code but isn't connected yet. Check both computers are on the same network and the firewall allows MagicInput, then wait a few seconds.", - n.name - ) + } else if let Some(n) = nearby.iter().find(|n| !n.compatible) { + format!("{} runs a different version of MagicInput, so they can't pair: update MagicInput on both computers.", n.name) } else if let Some(n) = nearby.first() { format!( - "This is the second computer: {} is already running MagicInput. Get its code (on that computer run `magicinput status`, or open MagicInput and click the link icon), then run here: {cmd} pair ", + "{} is running MagicInput but isn't connected. If this is the second computer, get its code (on that computer run `magicinput status`, or open MagicInput and click the link icon), then run here: {cmd} pair . If both already show the same code, check both computers are on the same network and the firewall allows MagicInput, then wait half a minute.", n.name ) } else { @@ -143,7 +140,7 @@ pub fn report(cfg: &mut Config, json: bool) { "business_license": crate::license::verify(&cfg.license).map(|l| l.plan), "connected_to": connected, "role": role, - "nearby": nearby.iter().map(|n| serde_json::json!({ "name": n.name, "address": n.address, "same_code": n.same_code })).collect::>(), + "nearby": nearby.iter().map(|n| serde_json::json!({ "name": n.name, "address": n.address, "compatible": n.compatible })).collect::>(), "next_step": next, }); println!("{}", serde_json::to_string_pretty(&v).unwrap()); @@ -161,7 +158,8 @@ pub fn report(cfg: &mut Config, json: bool) { } for n in &nearby { let addr = n.address.as_deref().map(|a| format!(" ({a})")).unwrap_or_default(); - println!(" Nearby: {}{addr}, {}", n.name, if n.same_code { "same code" } else { "different code" }); + let version = if n.compatible { "" } else { ", different version: update MagicInput on both computers" }; + println!(" Nearby: {}{addr}{version}", n.name); } println!("\nNext: {next}"); } From 357788f25969a5f519ee800db4725a51efc33fe7 Mon Sep 17 00:00:00 2001 From: Humberto Prado Date: Thu, 19 Nov 2026 03:21:45 +0900 Subject: [PATCH 2/2] Docs: correct the number of pairing attempts before waiting Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fd8159a..e42c333 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -50,7 +50,7 @@ Bursts of movement are merged before sending. On the receiving side, movement th - Each computer advertises `_magicinput._tcp` over mDNS with a random id, its name and the protocol version (`id`, `n`, `v`); nothing derived from the pairing code. It dials other MagicInput computers with the same protocol version (up to 16) and lets pairing decide whether they belong together. Of two peers, the one with the smaller id dials. - Connections run over TCP (port 24842, `TCP_NODELAY`; on macOS marked as interactive traffic for Wi-Fi). Each side first sends `MagicInp` plus its protocol version, so a computer on another version gets a clear "update MagicInput on both computers" error. Then both run symmetric SPAKE2 (Ed25519, identity `magicinput/pake/v`) on the normalized pairing code. HKDF-SHA256 of the SPAKE2 key, salted with the transcript so far, becomes the pre-shared key for Noise `NNpsk0_25519_ChaChaPoly_BLAKE2s`, which also takes the transcript as its prologue and carries all further traffic. With different codes the Noise handshake fails. -- Pairing attempts are paced per address in both directions: three in a row, then a wait that doubles up to ten seconds (forgotten after ten quiet minutes, cleared on success or when the local code changes). Incoming attempts from addresses that never paired also share a budget of 30 per minute, and at most 8 incoming connections pair at once. +- Pairing attempts are paced per address in both directions: four in a row, then a wait that doubles up to ten seconds (forgotten after ten quiet minutes, cleared on success or when the local code changes). Incoming attempts from addresses that never paired also share a budget of 30 per minute, and at most 8 incoming connections pair at once. - Only addresses in the subnet of one of the computer's own network interfaces are accepted or dialed; CGNAT/Tailscale ranges are excluded. ## Settings panel