Skip to main content

plexus_core/plexus/remote_child/
pairing.rs

1//! NEST-25 · first contact, the way ssh does it: the node learns the host's
2//! key once and pins it (its known-hosts file), and both ends show one short
3//! **pairing code** a person compares instead of 64 hex characters.
4//!
5//! The code (plexus-wire spec/14's first contact): the node sends
6//! `_info {nonce, commit}` — `commit` the [`commitment`] to a nonce of its
7//! own it keeps back — the host answers with a fresh `host_nonce` beside its
8//! key proof, and the node reveals its nonce in the offer (`pairing_nonce`),
9//! which the host checks against the commitment. Both ends then hold the same
10//! two keys and the same two nonces, and [`pairing_code`] is the first 8
11//! RFC 4648 base32 characters of their domain-separated SHA-256, `MMG4-2KLG`
12//! (menger's pairing-code form, TETHER-12).
13//!
14//! What it protects against: a man in the middle at first contact who
15//! answers each end with a key of its own. The two codes then differ, and
16//! because the node committed to its nonce before it saw the host's, the
17//! middle cannot search for keys whose codes agree: one try in 2⁴⁰ matches,
18//! and every try is an offer an operator sees. What it does not: an operator
19//! who accepts without comparing the code.
20
21use std::path::{Path, PathBuf};
22
23use base64::Engine;
24use sha2::{Digest, Sha256};
25
26/// The domain the pairing code's hash is taken in.
27pub const PAIRING_CONTEXT: &str = "plexus-dial-pairing/v1";
28
29/// How many base32 characters a pairing code has (40 bits).
30pub const CODE_CHARS: usize = 8;
31
32const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
33
34fn sha(parts: &[&str]) -> [u8; 32] {
35    let mut h = Sha256::new();
36    for p in parts {
37        // Each part length-prefixed: no two lists of parts hash alike.
38        h.update((p.len() as u64).to_be_bytes());
39        h.update(p.as_bytes());
40    }
41    h.finalize().into()
42}
43
44/// The node's commitment to `nonce` (sent at `_info`, before it sees the
45/// host's nonce): base64url of its domain-separated SHA-256.
46pub fn commitment(nonce: &str) -> String {
47    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha(&[PAIRING_CONTEXT, "commit", nonce]))
48}
49
50/// Whether `nonce` is the one `commit` committed to.
51pub fn commits_to(commit: &str, nonce: &str) -> bool {
52    commitment(nonce) == commit
53}
54
55/// The pairing code of one connection: both keys (`key:<hex>`) and both
56/// nonces, `XXXX-XXXX`.
57pub fn pairing_code(host_key: &str, node_key: &str, node_nonce: &str, host_nonce: &str) -> String {
58    let d = sha(&[PAIRING_CONTEXT, "code", host_key, node_key, node_nonce, host_nonce]);
59    let bits = d[..5].iter().fold(0u64, |acc, b| (acc << 8) | u64::from(*b));
60    let chars: String = (0..CODE_CHARS).map(|i| ALPHABET[((bits >> (35 - 5 * i)) & 31) as usize] as char).collect();
61    format!("{}-{}", &chars[..4], &chars[4..])
62}
63
64/// A code as typed — any case, dashes and spaces optional — as
65/// [`pairing_code`] writes it, or `None` when it is not one.
66pub fn normalize_code(typed: &str) -> Option<String> {
67    let chars: String = typed.chars().filter(|c| !c.is_whitespace() && *c != '-').map(|c| c.to_ascii_uppercase()).collect();
68    let ok = chars.len() == CODE_CHARS && chars.bytes().all(|b| ALPHABET.contains(&b));
69    ok.then(|| format!("{}-{}", &chars[..4], &chars[4..]))
70}
71
72/// A key's fingerprint as ssh shows one: `SHA256:<base64>` of its 32 bytes.
73pub fn key_fingerprint(principal: &str) -> Option<String> {
74    let key = crate::plexus::peer_token::key_of(principal)?;
75    Some(format!("SHA256:{}", base64::engine::general_purpose::STANDARD_NO_PAD.encode(Sha256::digest(key.as_bytes()))))
76}
77
78/// The node's known hosts: each host it said yes to, by URL, and the key
79/// pinned for it — a line `<url> key:<hex>`. Read as a key file is (not
80/// through a link, the user's own, 0600); written whole, 0600.
81#[derive(Debug, Clone)]
82pub struct KnownHosts {
83    path: PathBuf,
84}
85
86/// Review L2: a URL as the known-hosts file keys it — the scheme and host
87/// lower-cased, the host's trailing dot dropped, the scheme's default port
88/// (80 for `ws`, 443 for `wss`) dropped, trailing `/`s dropped, the path kept.
89/// One host, however it is spelled, is one entry.
90pub fn canonical_url(url: &str) -> String {
91    let url = url.trim();
92    let (scheme, rest) = match url.split_once("://") {
93        Some((s, r)) => (s.to_ascii_lowercase(), r),
94        None => return url.trim_end_matches('/').to_string(),
95    };
96    let cut = rest.find(['/', '?', '#']).unwrap_or(rest.len());
97    let (authority, path) = rest.split_at(cut);
98    let (userinfo, hostport) = match authority.rsplit_once('@') {
99        Some((u, h)) => (Some(u), h),
100        None => (None, authority),
101    };
102    let (host, port) = if let Some(end) = hostport.strip_prefix('[').and_then(|h| h.find(']')) {
103        let host = &hostport[..end + 2];
104        (host.to_string(), hostport[end + 2..].strip_prefix(':').map(str::to_string))
105    } else {
106        match hostport.rsplit_once(':') {
107            Some((h, p)) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => (h.to_string(), Some(p.to_string())),
108            _ => (hostport.to_string(), None),
109        }
110    };
111    let host = host.to_ascii_lowercase();
112    let host = host.trim_end_matches('.');
113    let default = match scheme.as_str() {
114        "ws" | "http" => Some("80"),
115        "wss" | "https" => Some("443"),
116        _ => None,
117    };
118    let port = port.map(|p| p.trim_start_matches('0').to_string()).filter(|p| Some(p.as_str()) != default && !p.is_empty());
119    let mut out = format!("{scheme}://");
120    if let Some(u) = userinfo {
121        out.push_str(u);
122        out.push('@');
123    }
124    out.push_str(host);
125    if let Some(p) = port {
126        out.push(':');
127        out.push_str(&p);
128    }
129    out.push_str(path.trim_end_matches('/'));
130    out
131}
132
133fn host_of(url: &str) -> String {
134    canonical_url(url)
135}
136
137/// Review L2: the file's lock, held while it is read, changed and written
138/// (`<file>.lock`, 0600, never through a link): two pins at once both kept.
139struct Locked(#[allow(dead_code)] std::fs::File);
140
141fn lock(path: &Path) -> Result<Locked, String> {
142    let lock_path = path.with_extension("lock");
143    let mut o = std::fs::OpenOptions::new();
144    o.read(true).write(true).create(true);
145    #[cfg(unix)]
146    {
147        use std::os::unix::fs::OpenOptionsExt;
148        o.mode(0o600).custom_flags(libc::O_NOFOLLOW);
149    }
150    let f = o.open(&lock_path).map_err(|e| format!("{}: {e}", lock_path.display()))?;
151    #[cfg(unix)]
152    {
153        use std::os::unix::io::AsRawFd;
154        // SAFETY: a valid descriptor this function owns; flock has no other preconditions.
155        if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX) } != 0 {
156            return Err(format!("{}: {}", lock_path.display(), std::io::Error::last_os_error()));
157        }
158    }
159    Ok(Locked(f))
160}
161
162impl KnownHosts {
163    /// The file at `path`.
164    pub fn new(path: impl Into<PathBuf>) -> Self {
165        Self { path: path.into() }
166    }
167
168    /// `$XDG_CONFIG_HOME/plexus/known_hosts`, else `~/.config/plexus/known_hosts`.
169    pub fn default_path() -> Option<PathBuf> {
170        let from = |k: &str| std::env::var_os(k).map(PathBuf::from).filter(|p| p.is_absolute());
171        from("XDG_CONFIG_HOME").or_else(|| from("HOME").map(|h| h.join(".config"))).map(|c| c.join("plexus").join("known_hosts"))
172    }
173
174    /// Where it is kept.
175    pub fn path(&self) -> &Path {
176        &self.path
177    }
178
179    fn entries(&self) -> Result<Vec<(String, String)>, String> {
180        let Some(bytes) = crate::plexus::peer_token::read_private_if_any(&self.path)? else { return Ok(Vec::new()) };
181        let text = String::from_utf8(bytes).map_err(|_| format!("{} is not text", self.path.display()))?;
182        let mut out = Vec::new();
183        for (n, line) in text.lines().enumerate() {
184            let line = line.trim();
185            if line.is_empty() || line.starts_with('#') {
186                continue;
187            }
188            match line.split_whitespace().collect::<Vec<_>>().as_slice() {
189                [url, key] if crate::plexus::peer_token::key_of(key).is_some() => out.push((host_of(url), key.to_string())),
190                _ => return Err(format!("{}:{}: not `<url> key:<64 hex>`", self.path.display(), n + 1)),
191            }
192        }
193        Ok(out)
194    }
195
196    /// The key pinned for `url`, if one is.
197    pub fn get(&self, url: &str) -> Result<Option<String>, String> {
198        let want = host_of(url);
199        Ok(self.entries()?.into_iter().find(|(u, _)| *u == want).map(|(_, k)| k))
200    }
201
202    /// Pin `key` for `url`. Refused when another key is pinned for it: a
203    /// host whose key changed is never re-pinned here, only by a person
204    /// editing the file.
205    pub fn add(&self, url: &str, key: &str) -> Result<(), String> {
206        if crate::plexus::peer_token::key_of(key).is_none() {
207            return Err(format!("`{key}` is not a key (`key:<64 hex>`)"));
208        }
209        if let Some(dir) = self.path.parent() {
210            if !dir.exists() {
211                std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
212                #[cfg(unix)]
213                {
214                    use std::os::unix::fs::PermissionsExt;
215                    let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
216                }
217            }
218        }
219        let _held = lock(&self.path)?;
220        let mut entries = self.entries()?;
221        match entries.iter().find(|(u, _)| *u == host_of(url)) {
222            Some((_, k)) if k == key => return Ok(()),
223            Some((_, k)) => return Err(format!("{} pins another key for {url} ({k}): remove that line by hand to trust a new one", self.path.display())),
224            None => entries.push((host_of(url), key.to_string())),
225        }
226        let text: String = entries.iter().map(|(u, k)| format!("{u} {k}\n")).collect();
227        let tmp = self.path.with_extension("tmp");
228        let _ = std::fs::remove_file(&tmp);
229        crate::plexus::peer_token::write_private(&tmp, text.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?;
230        std::fs::rename(&tmp, &self.path).map_err(|e| format!("{}: {e}", self.path.display()))
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    const A: &str = "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
239    const B: &str = "key:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
240
241    #[test]
242    fn the_code_is_eight_base32_characters_and_moves_with_every_input() {
243        let c = pairing_code(A, B, "n1", "n2");
244        assert_eq!(c.len(), 9);
245        assert_eq!(normalize_code(&c.to_lowercase().replace('-', " ")), Some(c.clone()));
246        for other in [pairing_code(B, A, "n1", "n2"), pairing_code(A, B, "n2", "n1"), pairing_code(A, B, "n1", "n3")] {
247            assert_ne!(c, other);
248        }
249    }
250
251    #[test]
252    fn a_commitment_binds_its_nonce() {
253        assert!(commits_to(&commitment("x"), "x"));
254        assert!(!commits_to(&commitment("x"), "y"));
255    }
256
257    /// Review L2: a pinned host respelled is the same entry — scheme and host
258    /// in any case, its default port said or not, a trailing dot or slash.
259    #[test]
260    fn a_respelled_url_of_a_pinned_host_is_the_same_entry() {
261        let dir = tempfile::tempdir().unwrap();
262        let k = KnownHosts::new(dir.path().join("known_hosts"));
263        k.add("ws://Host.Example./ws/", A).unwrap();
264        for same in ["ws://host.example/ws", "WS://HOST.EXAMPLE:80/ws", "ws://host.example.:80/ws//"] {
265            assert_eq!(k.get(same).unwrap().as_deref(), Some(A), "{same}");
266            assert!(k.add(same, B).unwrap_err().contains("another key"), "{same}: re-pinned under another spelling");
267        }
268        for other in ["ws://host.example/other", "ws://host.example:8080/ws", "wss://host.example/ws"] {
269            assert_eq!(k.get(other).unwrap(), None, "{other}");
270        }
271        k.add("wss://h.example:443", B).unwrap();
272        assert_eq!(k.get("wss://H.EXAMPLE/").unwrap().as_deref(), Some(B));
273    }
274
275    /// Review L2: pins written at once by many are all kept.
276    #[test]
277    fn pins_written_at_once_are_all_kept() {
278        let dir = tempfile::tempdir().unwrap();
279        let path = dir.path().join("known_hosts");
280        let threads: Vec<_> = (0..8)
281            .map(|t| {
282                let path = path.clone();
283                std::thread::spawn(move || {
284                    let k = KnownHosts::new(path);
285                    for i in 0..8 {
286                        k.add(&format!("ws://h{t}-{i}.example/ws"), A).unwrap();
287                    }
288                })
289            })
290            .collect();
291        for t in threads {
292            t.join().unwrap();
293        }
294        let k = KnownHosts::new(path);
295        for t in 0..8 {
296            for i in 0..8 {
297                assert_eq!(k.get(&format!("ws://h{t}-{i}.example/ws")).unwrap().as_deref(), Some(A), "h{t}-{i} lost");
298            }
299        }
300    }
301
302    #[test]
303    fn known_hosts_pins_once_and_never_repins() {
304        let dir = tempfile::tempdir().unwrap();
305        let k = KnownHosts::new(dir.path().join("plexus/known_hosts"));
306        assert_eq!(k.get("ws://h/ws").unwrap(), None);
307        k.add("ws://h/ws/", A).unwrap();
308        assert_eq!(k.get("ws://h/ws").unwrap().as_deref(), Some(A));
309        assert!(k.add("ws://h/ws", B).unwrap_err().contains("another key"));
310        #[cfg(unix)]
311        {
312            use std::os::unix::fs::PermissionsExt;
313            assert_eq!(std::fs::metadata(k.path()).unwrap().permissions().mode() & 0o777, 0o600);
314        }
315    }
316}