plexus_core/plexus/remote_child/
pairing.rs1use std::path::{Path, PathBuf};
22
23use base64::Engine;
24use sha2::{Digest, Sha256};
25
26pub const PAIRING_CONTEXT: &str = "plexus-dial-pairing/v1";
28
29pub 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 h.update((p.len() as u64).to_be_bytes());
39 h.update(p.as_bytes());
40 }
41 h.finalize().into()
42}
43
44pub fn commitment(nonce: &str) -> String {
47 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha(&[PAIRING_CONTEXT, "commit", nonce]))
48}
49
50pub fn commits_to(commit: &str, nonce: &str) -> bool {
52 commitment(nonce) == commit
53}
54
55pub 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
64pub 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
72pub 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#[derive(Debug, Clone)]
82pub struct KnownHosts {
83 path: PathBuf,
84}
85
86pub 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
137struct 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 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 pub fn new(path: impl Into<PathBuf>) -> Self {
165 Self { path: path.into() }
166 }
167
168 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 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 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 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 #[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 #[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}