ssh_browser/control/mod.rs
1//! The control API: the only path that will ever be allowed to write.
2//!
3//! No CORS headers are emitted anywhere in this module, and `OPTIONS` is refused. That
4//! combination is the security boundary, so it is worth spelling out.
5//!
6//! A page served under an alias origin is untrusted code. If it tries to reach the
7//! control API it has to send the token header; a custom header is not CORS-safelisted,
8//! so sending it forces a preflight; and a refused preflight means the request is never
9//! made. Without the header the request is a 401 instead. An extension is outside CORS
10//! by virtue of its host permissions, so none of this impedes it.
11//!
12//! The listener also only routes here for requests whose Host is the loopback address,
13//! which `guard::classify` already separates from alias requests. A proxied request
14//! cannot arrive here at all.
15
16use std::path::{Path, PathBuf};
17
18use anyhow::{Result, anyhow};
19use bytes::Bytes;
20use http_body_util::Full;
21use hyper::header::CONTENT_TYPE;
22use hyper::{Method, Response, StatusCode};
23use serde::Serialize;
24
25/// The header the token must arrive in.
26///
27/// Custom rather than `Authorization` for one reason that matters: a custom header is
28/// not CORS-safelisted, so a page attempting to send it triggers a preflight we refuse.
29pub const TOKEN_HEADER: &str = "x-ssh-browser-token";
30
31pub const PATH_PREFIX: &str = "/_control/";
32
33/// What a browser says about who started a request.
34///
35/// A forbidden header name: page script can neither set it nor remove it, so what arrives
36/// is the browser's account rather than the caller's.
37pub const FETCH_SITE_HEADER: &str = "sec-fetch-site";
38
39/// Protocol versions this daemon can speak.
40///
41/// Negotiated rather than assumed. The extension ships through a store review and the
42/// daemon ships through cargo, so on any given machine the two will not be the same age
43/// and a new daemon has to keep talking to an old extension.
44pub const PROTOCOL_MIN: u32 = 1;
45pub const PROTOCOL_MAX: u32 = 1;
46
47const TOKEN_BYTES: usize = 32;
48
49/// A bearer token for the control API.
50///
51/// Deliberately neither `Debug` nor `Display`. A token that can be formatted is a token
52/// that ends up in a log line eventually; the only way out is [`Token::as_str`], which
53/// reads as the deliberate act it is.
54pub struct Token(String);
55
56impl Token {
57 pub fn generate() -> Result<Self> {
58 let mut bytes = [0u8; TOKEN_BYTES];
59 // `getrandom::Error` does not implement `std::error::Error`, so it cannot be
60 // attached with `context`.
61 getrandom::fill(&mut bytes)
62 .map_err(|e| anyhow!("reading OS entropy for the control token failed: {e}"))?;
63 Ok(Self(hex(&bytes)))
64 }
65
66 /// Reconstruct a token generated elsewhere, such as one read back from disk.
67 pub fn from_hex(s: &str) -> Self {
68 Self(s.to_string())
69 }
70
71 pub fn as_str(&self) -> &str {
72 &self.0
73 }
74
75 /// Compare in constant time.
76 ///
77 /// A short-circuiting `==` leaks the token one byte at a time to anything that can
78 /// time the response, and on loopback that is every process on the machine. The
79 /// length is allowed to leak because it is a compile-time constant.
80 pub fn matches(&self, presented: &str) -> bool {
81 let (want, got) = (self.0.as_bytes(), presented.as_bytes());
82 if want.len() != got.len() {
83 return false;
84 }
85 let mut diff = 0u8;
86 for (a, b) in want.iter().zip(got) {
87 diff |= a ^ b;
88 }
89 diff == 0
90 }
91
92 /// Write the token where a local tool can find it, returning where it went.
93 ///
94 /// Best effort. A daemon that cannot write the file still works, because the token
95 /// is printed at startup as well, and refusing to start over this would be worse
96 /// than the inconvenience it avoids.
97 pub fn write_to_disk(&self) -> Option<PathBuf> {
98 let path = token_path()?;
99 std::fs::create_dir_all(path.parent()?).ok()?;
100 std::fs::write(&path, &self.0).ok()?;
101 restrict(&path);
102 Some(path)
103 }
104
105 /// Read a token back, if what is on disk is one.
106 ///
107 /// Length and alphabet are both checked. A file holding something else is not a token
108 /// however much one would like it to be, and accepting it would produce a daemon whose
109 /// token nothing can ever match — a locked door with no key, rather than an error.
110 fn from_disk(path: &Path) -> Option<Self> {
111 let text = std::fs::read_to_string(path).ok()?;
112 let trimmed = text.trim();
113 let looks_right = trimmed.len() == TOKEN_BYTES * 2
114 && trimmed
115 .bytes()
116 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase());
117 looks_right.then(|| Self(trimmed.to_string()))
118 }
119
120 /// The token this run will use: last run's, or a new one written down.
121 ///
122 /// Reused by default, because the alternative is what this did before and it made the
123 /// extension unusable. A fresh token every restart means pasting sixty-four characters
124 /// into a popup every time the daemon comes back — and the token was already being
125 /// written to disk, so regenerating took the risk of keeping it there and discarded the
126 /// only thing that risk buys.
127 ///
128 /// `rotate` mints a new one anyway, which is what to reach for if the old one leaked.
129 pub fn load_or_generate(rotate: bool) -> Result<(Self, Source)> {
130 if !rotate {
131 if let Some(path) = token_path() {
132 if let Some(token) = Self::from_disk(&path) {
133 return Ok((token, Source::Reused(path)));
134 }
135 }
136 }
137 let token = Self::generate()?;
138 let written = token.write_to_disk();
139 Ok((token, Source::Fresh(written)))
140 }
141}
142
143/// Where the token this run is using came from.
144///
145/// Reported rather than left to be inferred, so the startup banner can say which happened.
146/// Otherwise a reader has to compare a hex string against whatever their browser is holding
147/// in order to find out whether they need to paste it again.
148pub enum Source {
149 /// Read back from a previous run, so a browser that already has it stays connected.
150 Reused(PathBuf),
151 /// Newly minted, and written where the path says — or nowhere, if that failed.
152 Fresh(Option<PathBuf>),
153}
154
155/// Where the token file goes, resolved at runtime rather than compiled in.
156///
157/// The runtime directory is preferred on Unix because it is cleared on logout. That used to
158/// be the whole argument — a token belonging to a running process should not outlive the
159/// session — and it still holds, but it now cuts the other way as well: the token survives a
160/// daemon restart, so a browser stays connected across one, and stops being valid when the
161/// login session that owned it ends. A config directory would keep it indefinitely, which is
162/// longer than anything here needs.
163fn token_path() -> Option<PathBuf> {
164 Some(state_dir()?.join("token"))
165}
166
167/// Where this daemon keeps the small things it remembers between runs.
168///
169/// Shared with anything else that needs one rather than each picking its own: two
170/// directories chosen by two copies of this logic is how a setting gets written to one
171/// place and read from another.
172pub fn state_dir() -> Option<PathBuf> {
173 let base = std::env::var_os("XDG_RUNTIME_DIR")
174 .or_else(|| std::env::var_os("XDG_CONFIG_HOME"))
175 .or_else(|| std::env::var_os("LOCALAPPDATA"))
176 .map(PathBuf::from)
177 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
178 Some(base.join("ssh-browser"))
179}
180
181#[cfg(unix)]
182fn restrict(path: &std::path::Path) {
183 use std::os::unix::fs::PermissionsExt;
184 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
185}
186
187#[cfg(not(unix))]
188fn restrict(_path: &std::path::Path) {
189 // On Windows a file created under the user's own LOCALAPPDATA inherits an ACL that
190 // already excludes other users, and there is no mode to set.
191}
192
193fn hex(bytes: &[u8]) -> String {
194 let mut out = String::with_capacity(bytes.len() * 2);
195 for b in bytes {
196 out.push(nibble(b >> 4));
197 out.push(nibble(b & 0x0f));
198 }
199 out
200}
201
202fn nibble(n: u8) -> char {
203 match n {
204 0..=9 => (b'0' + n) as char,
205 _ => (b'a' + n - 10) as char,
206 }
207}
208
209#[derive(Serialize)]
210struct Protocol {
211 min: u32,
212 max: u32,
213}
214
215#[derive(Serialize)]
216struct Hello<'a> {
217 daemon: &'a str,
218 protocol: Protocol,
219 aliases: &'a [String],
220 /// The hostname suffix, so the extension can build an alias URL without being told it
221 /// separately.
222 ///
223 /// Reported rather than assumed: the suffix is configurable, and an extension that
224 /// hardcoded it would break the moment somebody changed it. Additive, so a protocol-1
225 /// client that does not read this field is unaffected and the range stays 1..=1.
226 suffix: &'a str,
227}
228
229/// Check the two things that must hold before any control route runs, returning the
230/// refusal if there is one.
231///
232/// Separated from routing so that a caller cannot reach a route without going through it:
233/// there is no path to the annotation handlers that does not pass this function first.
234/// Whether a request could have come from a page.
235///
236/// Measured rather than assumed. In Chromium an extension's `fetch` arrives with
237/// `Sec-Fetch-Site: none` and no `Origin` at all, while a page the daemon itself serves in
238/// the no-proxy fallback mode -- which is *same-origin* with the control API, and so the
239/// hardest case -- arrives with `same-origin`. Anything from another site is `cross-site`.
240///
241/// Absent means no browser sent it. That is a local process, which could read the token
242/// file directly, so refusing it here would protect nothing.
243pub fn from_a_page(site: Option<&str>) -> bool {
244 match site {
245 None => false,
246 Some("none") => false,
247 Some(_) => true,
248 }
249}
250
251pub fn gate(
252 method: &Method,
253 fetch_site: Option<&str>,
254 presented: Option<&str>,
255 token: &Token,
256) -> Option<Response<Full<Bytes>>> {
257 // Refusing the preflight is what keeps an alias page from ever reaching a route.
258 // Answering it, even with a restrictive allow-list, would move the decision into the
259 // browser's hands rather than ours.
260 if method == Method::OPTIONS {
261 return Some(text(
262 StatusCode::METHOD_NOT_ALLOWED,
263 "the control API does not participate in CORS",
264 ));
265 }
266
267 // Before the token, because it is a stronger statement: no page reaches this API at
268 // all, whatever it has got hold of. The token answers "is this caller authorised";
269 // this answers "is this caller a page", and a page holding a leaked token was the one
270 // case the token alone could not refuse. It matters most in the no-proxy fallback
271 // mode, where a page the daemon serves shares an origin with the control API.
272 if from_a_page(fetch_site) {
273 return Some(text(
274 StatusCode::FORBIDDEN,
275 "the control API is not reachable from a page",
276 ));
277 }
278
279 match presented {
280 Some(p) if token.matches(p) => None,
281 // The same answer either way: distinguishing "no token" from "wrong token" would
282 // tell a caller which half it got right.
283 _ => Some(text(StatusCode::UNAUTHORIZED, "control token required")),
284 }
285}
286
287/// The route name within the control namespace, e.g. `hello`.
288pub fn route_of(path: &str) -> &str {
289 path.strip_prefix(PATH_PREFIX).unwrap_or("")
290}
291
292pub fn hello(aliases: &[String], suffix: &str) -> Response<Full<Bytes>> {
293 json(&Hello {
294 daemon: env!("CARGO_PKG_VERSION"),
295 protocol: Protocol {
296 min: PROTOCOL_MIN,
297 max: PROTOCOL_MAX,
298 },
299 aliases,
300 suffix,
301 })
302}
303
304pub fn json<T: Serialize>(value: &T) -> Response<Full<Bytes>> {
305 match serde_json::to_vec(value) {
306 Ok(body) => Response::builder()
307 .status(StatusCode::OK)
308 .header(CONTENT_TYPE, "application/json")
309 .body(Full::new(Bytes::from(body)))
310 .unwrap_or_else(|_| text(StatusCode::INTERNAL_SERVER_ERROR, "malformed response")),
311 Err(e) => text(
312 StatusCode::INTERNAL_SERVER_ERROR,
313 format!("serialising the response failed: {e}"),
314 ),
315 }
316}
317
318pub fn text(status: StatusCode, detail: impl Into<String>) -> Response<Full<Bytes>> {
319 Response::builder()
320 .status(status)
321 .header(CONTENT_TYPE, "text/plain; charset=utf-8")
322 .body(Full::new(Bytes::from(detail.into())))
323 .expect("a plain-text body with static headers always builds")
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 fn token() -> Token {
331 Token::from_hex("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
332 }
333
334 #[test]
335 fn a_generated_token_is_long_and_random() {
336 let a = Token::generate().expect("OS entropy");
337 let b = Token::generate().expect("OS entropy");
338 assert_eq!(a.as_str().len(), TOKEN_BYTES * 2);
339 assert!(a.as_str().chars().all(|c| c.is_ascii_hexdigit()));
340 assert_ne!(
341 a.as_str(),
342 b.as_str(),
343 "two tokens from the same process must differ"
344 );
345 }
346
347 #[test]
348 fn the_right_token_passes_the_gate() {
349 assert!(gate(&Method::GET, None, Some(token().as_str()), &token()).is_none());
350 }
351
352 #[test]
353 fn a_missing_or_wrong_token_is_refused_identically() {
354 for presented in [None, Some(""), Some("wrong"), Some(&token().as_str()[..10])] {
355 let refusal = gate(&Method::GET, None, presented, &token()).expect("refused");
356 assert_eq!(refusal.status(), StatusCode::UNAUTHORIZED);
357 }
358 }
359
360 /// The boundary. If a preflight ever passes, an untrusted page can start negotiating
361 /// with the control API instead of being stopped before the request is even made.
362 #[test]
363 fn a_preflight_is_refused_even_with_a_valid_token() {
364 let refusal =
365 gate(&Method::OPTIONS, None, Some(token().as_str()), &token()).expect("refused");
366 assert_eq!(refusal.status(), StatusCode::METHOD_NOT_ALLOWED);
367 }
368
369 /// Nothing here may emit CORS headers: that is what stops a page reading a response
370 /// even if it somehow manages to send the request.
371 #[test]
372 fn no_response_carries_cors_headers() {
373 let mut responses = vec![hello(&["docs".to_string()], "ssh-browser")];
374 responses.extend(gate(&Method::OPTIONS, None, None, &token()));
375 responses.extend(gate(&Method::GET, None, None, &token()));
376 responses.push(text(StatusCode::NOT_FOUND, "nope"));
377
378 for res in responses {
379 for name in res.headers().keys() {
380 let lowered = name.as_str().to_ascii_lowercase();
381 assert!(
382 !lowered.starts_with("access-control-"),
383 "a control response carries {lowered}"
384 );
385 }
386 }
387 }
388
389 #[test]
390 fn hello_reports_a_protocol_range_and_the_aliases() {
391 let body = serde_json::to_string(&Hello {
392 daemon: env!("CARGO_PKG_VERSION"),
393 protocol: Protocol {
394 min: PROTOCOL_MIN,
395 max: PROTOCOL_MAX,
396 },
397 aliases: &["docs".to_string()],
398 suffix: "ssh-browser",
399 })
400 .expect("serialises");
401 assert!(body.contains("\"min\":1"));
402 assert!(body.contains("\"max\":1"));
403 assert!(body.contains("\"aliases\":[\"docs\"]"));
404 assert!(body.contains("\"daemon\":\""));
405 }
406
407 /// A temporary file, named after the test so parallel runs cannot collide.
408 fn scratch(name: &str, contents: &str) -> std::path::PathBuf {
409 let path = std::env::temp_dir().join(format!("ssh-browser-token-{name}"));
410 std::fs::write(&path, contents).expect("a temp file");
411 path
412 }
413
414 /// The whole point of keeping it: a browser that has the token stays connected across a
415 /// restart, so nobody retypes sixty-four characters to get back to where they were.
416 #[test]
417 fn a_token_survives_the_round_trip_to_disk() {
418 let path = scratch("roundtrip", token().as_str());
419 let back = Token::from_disk(&path).expect("read back");
420 assert!(back.matches(token().as_str()));
421 let _ = std::fs::remove_file(&path);
422 }
423
424 /// Anything that is not a token is not accepted as one. Taking it would produce a daemon
425 /// whose token nothing can ever match — a locked door with no key rather than an error,
426 /// and one that only shows up as a 401 on every request.
427 #[test]
428 fn a_file_that_is_not_a_token_is_refused() {
429 let cases = [
430 ("empty", ""),
431 ("short", "0123456789abcdef"),
432 ("long", &"a".repeat(65) as &str),
433 ("not-hex", &"z".repeat(64)),
434 // Uppercase would compare unequal to everything this ever generates, so it is
435 // refused rather than quietly accepted and never matched.
436 ("uppercase", &"A".repeat(64)),
437 ("a sentence", "this file used to hold a token"),
438 ];
439 for (name, contents) in cases {
440 let path = scratch(name, contents);
441 assert!(
442 Token::from_disk(&path).is_none(),
443 "{name:?} should not have read as a token"
444 );
445 let _ = std::fs::remove_file(&path);
446 }
447 }
448
449 /// Written with a trailing newline by an editor, or by anyone who opened it to look.
450 #[test]
451 fn surrounding_whitespace_does_not_spoil_it() {
452 let path = scratch("whitespace", &format!("\n {}\t\n", token().as_str()));
453 assert!(
454 Token::from_disk(&path)
455 .expect("read back")
456 .matches(token().as_str())
457 );
458 let _ = std::fs::remove_file(&path);
459 }
460
461 #[test]
462 fn routes_are_named_after_the_prefix() {
463 assert_eq!(route_of("/_control/hello"), "hello");
464 assert_eq!(route_of("/_control/annotations"), "annotations");
465 assert_eq!(route_of("/not-control"), "");
466 }
467
468 /// The measured cases. An extension's fetch arrives as `none` with no `Origin`; a page
469 /// the daemon serves in the no-proxy fallback mode arrives as `same-origin`, which is
470 /// the hardest one because it shares an origin with the control API; anything from
471 /// elsewhere is `cross-site`. Absent is not a browser at all.
472 #[test]
473 fn a_page_is_told_apart_from_an_extension() {
474 assert!(!from_a_page(None));
475 assert!(!from_a_page(Some("none")));
476 for page in ["same-origin", "same-site", "cross-site"] {
477 assert!(from_a_page(Some(page)), "{page} is a page");
478 }
479 }
480
481 /// Refused before the token is even looked at, because it is the stronger statement:
482 /// a page holding a leaked token is the one case the token alone could not refuse.
483 #[test]
484 fn a_page_cannot_reach_the_control_api_even_with_the_right_token() {
485 let refusal = gate(
486 &Method::GET,
487 Some("same-origin"),
488 Some(token().as_str()),
489 &token(),
490 )
491 .expect("refused");
492 assert_eq!(refusal.status(), StatusCode::FORBIDDEN);
493 }
494}