collab-net: serve pinned TLS for app sessions hosted on the network (#1131)

An app hosting a live session for other machines sent the session token
in the clear over plain ws://. Such a host now serves TLS with an
ephemeral self-signed Ed25519 certificate (DER written by hand with ring,
no new crates), and its invite links pin the certificate's SHA-256
(`cert=`, URL-safe base64): figcraft://join?server=wss://…&cert=… and
wss://…/?cert=…

- tls: the shared session is a rustls::Connection (client or server),
  keeping the split reader/writer locking; `accept` answers a server
  handshake by the hello deadline; `handshake_pinned` uses a verifier
  that compares the end-entity certificate's SHA-256 in constant time
  and still checks the TLS 1.2/1.3 handshake signature, refusing any
  other certificate before the Hello with a clear reason.
- invite: Endpoint::cert (None for Endpoint::plain), Endpoint::pinned;
  a malformed pin, one on ws://, or two that disagree is an error that
  never echoes the link. The pin stays out of the WebSocket request URL.
  An automation allowlist entry allows only its own pin.
- host/hub: HostConfig::tls, Host::cert_sha256, Host::endpoint; the hub
  carries the server config to each connection. Hosting::serve (the
  server) is unchanged.
- link: NetLink::host serves TLS for non-loopback binds without a join
  code. Join-code (short) shares stay plain ws://: a 20-symbol code has
  no room for the pin, and its joiners share the token with the link.
- web: the browser refuses a pinned link with a clear reason.

Tests: pinned join and edit sync both ways, a plain client against a
TLS host, a host presenting another certificate (refused, not admitted),
the request carrying neither token nor pin, link round trips and
malformed cert= values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bryton CooperandClaude Opus 5.5 committed 2026-11-28 11:43:29 -07:00
1 parent d95c6a91d4
commit 37ff872305
20 files changed
+655 -57

No files matched your search

Generated
+1
View File
@@ -2704,6 +2704,7 @@ dependencies = [
"js-sys",
"log",
"proptest",
"ring",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
+4 -1
View File
@@ -15,6 +15,8 @@ figcraft-doc = { workspace = true }
log = { workspace = true }
# `std::time::Instant` natively, the browser's clock in the web build.
web-time = "1"
# Invite links write a session certificate's SHA-256 (`cert=`) in URL-safe base64.
base64 = { workspace = true }
# Native transport: blocking tungstenite with a reader and a writer thread per connection.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
@@ -27,7 +29,8 @@ rustls-pki-types = { version = "1", features = ["std"] }
webpki-roots = "1"
rustls-native-certs = "0.8"
getrandom = "0.4"
base64 = { workspace = true }
# A hosting app's own Ed25519 certificate (`cert.rs`): the provider rustls already uses.
ring = "0.17"
# The browser client: the page's WebSocket API.
[target.'cfg(target_arch = "wasm32")'.dependencies]
+127
View File
@@ -0,0 +1,127 @@
//! A session's own certificate (native): a fresh Ed25519 key and a self-signed X.509 v3
//! certificate for it, made when an app starts hosting on the network and gone when it stops.
//! Nobody vouches for it; the invite link carries its SHA-256 instead (`cert=`), and a guest
//! connects only to a host presenting exactly that certificate ([`crate::tls::handshake_pinned`]).
//!
//! The certificate is written out as DER by hand (a few fixed structures), so hosting needs no
//! certificate library: its validity runs from 2000 to 9999-12-31 (RFC 5280's "no expiry"), as
//! the pin, not a date, is what's checked.
use std::sync::Arc;
use ring::rand::{SecureRandom, SystemRandom};
use ring::signature::{Ed25519KeyPair, KeyPair};
use rustls::ServerConfig;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
/// The SHA-256 of a certificate's DER: what an invite pins.
pub type Fingerprint = [u8; 32];
/// A session's certificate, its private key and its fingerprint.
pub struct SessionCert {
pub cert: CertificateDer<'static>,
pub key: PrivateKeyDer<'static>,
pub sha256: Fingerprint,
}
/// The SHA-256 of `der`.
pub fn fingerprint(der: &[u8]) -> Fingerprint {
let mut out = [0u8; 32];
out.copy_from_slice(ring::digest::digest(&ring::digest::SHA256, der).as_ref());
out
}
/// `id-Ed25519` (1.3.101.112), as an AlgorithmIdentifier: no parameters (RFC 8410).
const ED25519: &[u8] = &[0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70];
/// A DER element: `tag`, its length, `body`.
fn der(tag: u8, body: &[u8]) -> Vec<u8> {
let mut out = vec![tag];
match u8::try_from(body.len()) {
Ok(n) if n < 0x80 => out.push(n),
_ => {
// Long form: the length's bytes without leading zeros, after their count.
let bytes = body.len().to_be_bytes();
let len: Vec<u8> = bytes.iter().copied().skip_while(|b| *b == 0).collect();
out.push(0x80 | u8::try_from(len.len()).unwrap_or(0));
out.extend_from_slice(&len);
}
}
out.extend_from_slice(body);
out
}
fn seq(parts: &[&[u8]]) -> Vec<u8> {
der(0x30, &parts.concat())
}
/// A BIT STRING of whole bytes.
fn bits(b: &[u8]) -> Vec<u8> {
der(0x03, &[&[0u8][..], b].concat())
}
/// `CN=<name>`.
fn name(cn: &str) -> Vec<u8> {
let attr = seq(&[&der(0x06, &[0x55, 0x04, 0x03]), &der(0x0C, cn.as_bytes())]);
seq(&[&der(0x31, &attr)])
}
/// The to-be-signed part of a certificate for `public` (32 bytes) with `serial`.
fn tbs(serial: &[u8; 16], public: &[u8]) -> Vec<u8> {
let version = der(0xA0, &der(0x02, &[2]));
let subject = name("FigCraft live session");
let validity = seq(&[&der(0x17, b"000101000000Z"), &der(0x18, b"99991231235959Z")]);
let spki = seq(&[ED25519, &bits(public)]);
// basicConstraints (2.5.29.19), critical: not an authority.
let basic = seq(&[&der(0x06, &[0x55, 0x1D, 0x13]), &der(0x01, &[0xFF]), &der(0x04, &seq(&[]))]);
let extensions = der(0xA3, &seq(&[&basic]));
seq(&[&version, &der(0x02, serial), ED25519, &subject, &validity, &subject, &spki, &extensions])
}
/// A fresh key and a self-signed certificate for it.
pub fn generate() -> Result<SessionCert, String> {
let rng = SystemRandom::new();
let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).map_err(|_| "can't make a key for the session's certificate")?;
let pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).map_err(|_| "can't read the session's new key")?;
let mut serial = [0u8; 16];
rng.fill(&mut serial).map_err(|_| "no randomness for the session's certificate")?;
// A positive INTEGER with no leading zero byte.
serial[0] = (serial[0] & 0x7F) | 0x01;
let tbs = tbs(&serial, pair.public_key().as_ref());
let signature = pair.sign(&tbs);
let cert = seq(&[&tbs, ED25519, &bits(signature.as_ref())]);
let sha256 = fingerprint(&cert);
Ok(SessionCert { cert: CertificateDer::from(cert), key: PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(pkcs8.as_ref().to_vec())), sha256 })
}
/// The server settings presenting `cert`.
pub fn server_config(cert: &SessionCert) -> Result<Arc<ServerConfig>, String> {
let cfg = ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.with_no_client_auth()
.with_single_cert(vec![cert.cert.clone()], cert.key.clone_key())
.map_err(|e| format!("the session's certificate isn't usable: {e}"))?;
Ok(Arc::new(cfg))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn long_lengths_use_the_fewest_bytes() {
assert_eq!(der(0x04, &[0; 0x7F])[..2], [0x04, 0x7F]);
assert_eq!(der(0x04, &[0; 0x80])[..3], [0x04, 0x81, 0x80]);
assert_eq!(der(0x04, &[0; 0x1234])[..4], [0x04, 0x82, 0x12, 0x34]);
}
#[test]
fn each_certificate_is_new_and_its_fingerprint_is_its_hash() {
let (a, b) = (generate().unwrap(), generate().unwrap());
assert_ne!(a.sha256, b.sha256);
assert_eq!(a.sha256, fingerprint(a.cert.as_ref()));
// rustls (webpki) parses it and accepts the key as its own.
server_config(&a).unwrap();
}
}
+26
View File
@@ -223,6 +223,32 @@ fn a_share_on_every_interface_names_an_address_others_reach() {
assert_eq!(host.execute("collab.stop", &json!({})).unwrap()["ended"], true);
}
/// A session hosted for other machines (here on every interface, without a join code) serves TLS
/// with a certificate of its own: its links are `wss://` and pin it, a guest joining with them
/// edits along both ways, and the same session as a plain `ws://` link gets nowhere.
#[test]
fn a_network_host_serves_tls_its_links_pin_and_edits_sync() {
let (mut host, mut guest, mut plain) = (session("Hana"), session("Ada"), session("Bo"));
let hosted = host.execute("collab.host", &json!({"bind": "0.0.0.0"})).unwrap();
let (link, url) = (hosted["link"].as_str().unwrap().to_string(), hosted["url"].as_str().unwrap().to_string());
let invite = Invite::parse(&link).unwrap();
assert!(invite.server.secure && invite.server.cert.is_some(), "{link}");
assert_eq!(Invite::parse(&url).unwrap(), invite, "the link and the URL name the same pin");
guest.execute("collab.join", &json!({"link": link})).unwrap();
pump(&mut [&mut host, &mut guest], "the join", |s| live(s[1]) && s[0].live().peers.len() == 1);
let before = layers(&host);
host.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
pump(&mut [&mut host, &mut guest], "the host's edit", |s| layers(s[1]) == before + 1);
guest.execute("shape.ellipse", &json!({"x": 80, "y": 10, "width": 40, "height": 30})).unwrap();
pump(&mut [&mut host, &mut guest], "the guest's edit", |s| layers(s[0]) == before + 2);
// Without TLS the host doesn't answer.
let unpinned = Invite::new(invite.server.host.clone(), invite.file.clone(), invite.token.clone());
plain.execute("collab.join", &json!({"link": unpinned.link()})).unwrap();
pump(&mut [&mut host, &mut guest, &mut plain], "the plain join's failure", |s| matches!(s[2].live().status, Status::Failed { .. }));
assert_eq!(host.live().peers.len(), 1);
assert_eq!(host.execute("collab.stop", &json!({})).unwrap()["ended"], true);
}
/// A listener on one address is reached at it; one on every interface at an address of its own
/// family, on its port.
#[test]
+1
View File
@@ -636,6 +636,7 @@ fn joins_a_real_host_and_edits_with_it() {
name: "Hana".into(),
limits: fast_limits(),
core: Limits::default(),
tls: false,
},
host_probe.clone(),
)
+30 -2
View File
@@ -15,6 +15,7 @@ use figcraft_engine::live::{Event, PEOPLE};
pub use crate::hub::REMOVED;
use crate::hub::{Admission, Backend, Closing, Hosting, Local, clean_name, to_local};
use crate::inbox::Inbox;
use crate::invite::Endpoint;
pub use crate::join::ENDED;
use crate::net::NetLimits;
@@ -36,12 +37,17 @@ pub struct HostConfig {
pub name: String,
pub limits: NetLimits,
pub core: figcraft_collab::Limits,
/// Serve TLS with a certificate made for this session ([`crate::cert`]): every guest must
/// connect over it, to exactly that certificate ([`Host::cert_sha256`] for their links). For
/// a host others reach over a network, where the token would otherwise travel in the clear.
pub tls: bool,
}
/// A running session host. Dropping it stops it.
pub struct Host {
hosting: Hosting,
me: Peer,
cert_sha256: Option<[u8; 32]>,
}
/// The app's one file and its tokens: whoever has the edit token edits, whoever has the view
@@ -94,6 +100,14 @@ impl Host {
"this file can't be shared: its design review settings hold {list}; trim them with design.configure (or reset the settings), then share again"
)));
}
// A new certificate each session: an old invite's pin never matches a later session.
let (tls, cert_sha256) = match cfg.tls {
true => {
let cert = crate::cert::generate().map_err(io::Error::other)?;
(Some(crate::cert::server_config(&cert).map_err(io::Error::other)?), Some(cert.sha256))
}
false => (None, None),
};
let listener = match TcpListener::bind(cfg.addr) {
Ok(l) => l,
Err(e) if e.kind() == io::ErrorKind::AddrInUse && cfg.any_port_if_taken => TcpListener::bind(SocketAddr::new(cfg.addr.ip(), 0))?,
@@ -127,8 +141,8 @@ impl Host {
let me = server.peers().find(|p| p.client_id == me).cloned().ok_or_else(|| io::Error::other("the host didn't join its own session"))?;
let backend = OneFile { file: cfg.file.clone(), token: cfg.token, view: cfg.view_token };
let local = Local { file: cfg.file, server, id: me.client_id, inbox };
let hosting = Hosting::start(listener, backend, cfg.limits, Some(local))?;
Ok(Host { hosting, me })
let hosting = Hosting::start(listener, backend, cfg.limits, Some(local), tls)?;
Ok(Host { hosting, me, cert_sha256 })
}
/// Where it listens.
@@ -136,6 +150,20 @@ impl Host {
self.hosting.addr()
}
/// The SHA-256 of the certificate it serves TLS with (`None`: plain `ws://`).
pub fn cert_sha256(&self) -> Option<[u8; 32]> {
self.cert_sha256
}
/// Where others connect to, at `host` (`host:port`): `wss://` to its certificate when it has
/// one, else plain `ws://`.
pub fn endpoint(&self, host: impl Into<String>) -> Endpoint {
match self.cert_sha256 {
Some(c) => Endpoint::pinned(host, c),
None => Endpoint::plain(host),
}
}
/// The host as the others see them.
pub fn me(&self) -> &Peer {
&self.me
+17 -4
View File
@@ -90,6 +90,8 @@ pub(super) struct Shared {
/// Bytes being read into messages, all connections together, and who is reading them.
pub(super) reading: Arc<AtomicUsize>,
pub(super) readers: Readers,
/// The TLS every connection must speak (an app hosting on the network), if any.
pub(super) tls: Option<Arc<rustls::ServerConfig>>,
}
pub(super) fn accept(listener: &TcpListener, hub: &Sender<HubIn>, stop: &AtomicBool, open: &Arc<AtomicUsize>, limits: NetLimits, shared: Shared) {
@@ -209,12 +211,23 @@ fn serve(mut stream: TcpStream, conn: u64, hub: &Sender<HubIn>, limits: NetLimit
if stream.set_read_timeout(Some(limits.hello_timeout)).is_err() || stream.set_write_timeout(Some(limits.write_timeout)).is_err() {
return;
}
if health_check(&mut stream, Instant::now() + limits.hello_timeout) {
return;
}
// Over TLS everything is inside it (an uptime check too, which then isn't answered in the
// clear): the handshake comes first, by the hello's deadline.
let tls = match &shared.tls {
Some(cfg) => match crate::tls::accept(&stream, cfg.clone(), hello_deadline) {
Ok(t) => Some(t),
Err(e) => {
log::debug!("live session: TLS handshake failed: {e}");
shutdown(&stream);
return;
}
},
None if health_check(&mut stream, Instant::now() + limits.hello_timeout) => return,
None => None,
};
let Ok(peer) = stream.peer_addr().map(|a| a.ip().to_canonical()) else { return };
let proxied = limits.trusted_proxy.is_some_and(|p| p.to_canonical() == peer);
let Ok((mut rd, wr, sock)) = Duplex::split(stream, None) else { return };
let Ok((mut rd, wr, sock)) = Duplex::split(stream, tls) else { return };
// The handshake and the hello must be in by the deadline, however slowly they trickle in.
rd.read_until(Some(hello_deadline));
let cfg = config(limits.max_client_message);
+15 -3
View File
@@ -1,3 +1,5 @@
use rustls::ServerConfig;
use super::backend::Backend;
use super::conn::{Shared, accept};
use super::limits::PerAddress;
@@ -43,10 +45,18 @@ pub struct Hosting {
impl Hosting {
/// Serve `backend`'s files on `listener`.
pub fn serve<B: Backend>(listener: TcpListener, backend: B, limits: NetLimits) -> io::Result<Hosting> {
Self::start(listener, backend, limits, None)
Self::start(listener, backend, limits, None, None)
}
pub(crate) fn start<B: Backend>(listener: TcpListener, backend: B, limits: NetLimits, local: Option<Local>) -> io::Result<Hosting> {
/// Serve on `listener`, with the hosting person in it (`local`), over TLS with `tls` when
/// given (every connection must speak it).
pub(crate) fn start<B: Backend>(
listener: TcpListener,
backend: B,
limits: NetLimits,
local: Option<Local>,
tls: Option<Arc<ServerConfig>>,
) -> io::Result<Hosting> {
let addr = listener.local_addr()?;
listener.set_nonblocking(true)?;
let in_flight = InFlight(Arc::default());
@@ -76,7 +86,9 @@ impl Hosting {
blocks: Blocks::default(),
reading: Arc::default(),
readers: Readers::default(),
tls,
};
let shared_tls = shared.tls.is_some();
let queued = shared.queued.clone();
let blocks = shared.blocks.clone();
let reading = shared.reading.clone();
@@ -92,7 +104,7 @@ impl Hosting {
return Err(e);
}
};
log::info!("live session: listening on {addr}");
log::info!("live session: listening on {addr}{}", if shared_tls { " (TLS)" } else { "" });
Ok(Hosting {
addr,
hub: hub_tx,
+76 -11
View File
@@ -1,5 +1,10 @@
//! Invite links and server addresses.
//!
//! An app hosting on its local network serves TLS with a certificate of its own (nobody vouches
//! for it), so its links name it: `cert=<SHA-256, URL-safe base64>` beside a `wss://` server
//! (`figcraft://join?server=wss://…&cert=…&file=…&token=…`, `wss://…/?cert=…&file=…&token=…`). A
//! guest then connects only to a host presenting exactly that certificate.
//!
//! An invite (or share) link names a session's endpoint, its file and a token:
//! `figcraft://join?host=<host:port>&file=<id>&token=<secret>` for a plain `ws://` endpoint at `/`
//! (what the desktop app hosts), `figcraft://join?server=<ws(s)://host[:port][/path]>&file=…&token=…`
@@ -20,6 +25,8 @@
//! out the file's team link to whoever asks, while the file is shared. Such a link carries no
//! secret: whoever can reach the server may join with it.
use base64::Engine as _;
/// Where a session or a server listens: `ws://host:port/path` or `wss://…` (TLS).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Endpoint {
@@ -27,8 +34,11 @@ pub struct Endpoint {
pub host: String,
/// The path it answers on: `/`, or a reverse proxy's prefix (`/figcraft/`).
pub path: String,
/// `wss://`: TLS (a reverse proxy in front of the server).
/// `wss://`: TLS (a reverse proxy in front of the server, or an app's own certificate).
pub secure: bool,
/// The SHA-256 of the one certificate to accept (`cert=`; `wss://` only), in place of
/// checking it with the authorities this computer trusts.
pub cert: Option<[u8; 32]>,
}
/// What an invite link names.
@@ -53,12 +63,46 @@ pub enum Lookup {
/// Longest link accepted (anything longer isn't one of ours).
const MAX_LINK: usize = 2048;
/// The query key of a certificate pin.
const CERT: &str = "cert";
const NOT: &str = "that's not a live session invite: expected figcraft://join?host=…&file=…&token=… or ws://host:port/?file=…&token=…";
impl Endpoint {
/// A plain `ws://host/` endpoint.
pub fn plain(host: impl Into<String>) -> Self {
Self { host: host.into(), path: "/".into(), secure: false }
Self { host: host.into(), path: "/".into(), secure: false, cert: None }
}
/// A `wss://host/` endpoint presenting the certificate `cert` is the SHA-256 of.
pub fn pinned(host: impl Into<String>, cert: [u8; 32]) -> Self {
Self { host: host.into(), path: "/".into(), secure: true, cert: Some(cert) }
}
/// `cert=…&` for a pinned endpoint (empty otherwise): a link's query starts with it.
fn cert_pair(&self) -> String {
self.cert.map(|c| format!("{CERT}={}&", B64.encode(c))).unwrap_or_default()
}
/// Take a `cert=` pin out of `query` into this endpoint: a malformed one, one on a `ws://`
/// address, or one that contradicts a pin already there is an error (never ignored, which
/// would join without it).
fn take_cert(&mut self, query: &mut Vec<(String, String)>) -> Result<(), String> {
let mut found = None;
for (_, v) in query.extract_if(.., |(k, _)| k == CERT) {
let pin = read_cert(&v)?;
if found.is_some_and(|f| f != pin) || self.cert.is_some_and(|c| c != pin) {
return Err("the link names two different certificates".into());
}
found = Some(pin);
}
if let Some(pin) = found {
if !self.secure {
return Err("the link names a certificate for a ws:// address: a certificate needs wss://".into());
}
self.cert = Some(pin);
}
Ok(())
}
/// `ws://` at `/`: an invite can name it as `host=…`.
@@ -66,7 +110,7 @@ impl Endpoint {
!self.secure && self.path == "/"
}
/// The WebSocket URL to connect to (no secrets in it).
/// The WebSocket URL to connect to (no secrets in it, nor the pin).
pub fn url(&self) -> String {
format!("{}://{}{}", if self.secure { "wss" } else { "ws" }, self.host, self.path)
}
@@ -87,6 +131,8 @@ impl Endpoint {
/// Whether this endpoint is within an explicitly allowed server origin and path prefix.
pub fn is_within(&self, allowed: &Endpoint) -> bool {
self.secure == allowed.secure
// A pin trusts a certificate no authority checked: only the one allowed.
&& self.cert == allowed.cert
&& self.host.eq_ignore_ascii_case(&allowed.host)
&& safe_path(&self.path)
&& safe_path(&allowed.path)
@@ -125,7 +171,10 @@ impl Endpoint {
if !path.ends_with('/') {
path.push('/');
}
Ok((Endpoint { host, path, secure }, pairs(query)?))
let mut query = pairs(query)?;
let mut endpoint = Endpoint { host, path, secure, cert: None };
endpoint.take_cert(&mut query)?;
Ok((endpoint, query))
}
}
@@ -140,7 +189,7 @@ impl Invite {
if self.server.is_plain() {
format!("figcraft://join?host={}&file={}&token={}", self.server.host, self.file, self.token)
} else {
format!("figcraft://join?server={}&file={}&token={}", self.server.url(), self.file, self.token)
format!("figcraft://join?server={}&{}file={}&token={}", self.server.url(), self.server.cert_pair(), self.file, self.token)
}
}
@@ -150,13 +199,13 @@ impl Invite {
if self.server.is_plain() {
format!("figcraft://join?host={}&file={}&team=1", self.server.host, self.file)
} else {
format!("figcraft://join?server={}&file={}&team=1", self.server.url(), self.file)
format!("figcraft://join?server={}&{}file={}&team=1", self.server.url(), self.server.cert_pair(), self.file)
}
}
/// The same session as a WebSocket URL.
pub fn url(&self) -> String {
format!("{}?file={}&token={}", self.server.url(), self.file, self.token)
format!("{}?{}file={}&token={}", self.server.url(), self.server.cert_pair(), self.file, self.token)
}
/// What the client connects to (no secrets in it).
@@ -192,16 +241,19 @@ impl Invite {
if !path.trim_end_matches('/').eq_ignore_ascii_case("join") {
return Err(NOT.into());
}
let query = pairs(query).map_err(|_| NOT)?;
let mut query = pairs(query).map_err(|_| NOT)?;
let get = |k: &str| query.iter().find(|(key, _)| key == k).map(|(_, v)| v.clone());
let server = match (get("server"), get("host")) {
(Some(url), _) => Endpoint::parse(&url).map(|(e, _)| e).map_err(|_| "the invite link's server isn't a ws:// or wss:// address")?,
let mut server = match (get("server"), get("host")) {
(Some(url), _) => Endpoint::parse(&url)
.map(|(e, _)| e)
.map_err(|e| if e.contains("certificate") { e } else { "the invite link's server isn't a ws:// or wss:// address".into() })?,
(None, Some(host)) if valid_host(&host) => Endpoint::plain(host),
_ => return Err("the invite link's host isn't an address with a port (like 192.168.1.20:47900)".into()),
};
server.take_cert(&mut query)?;
(server, query)
} else if scheme.eq_ignore_ascii_case("ws") || scheme.eq_ignore_ascii_case("wss") {
Endpoint::parse(link).map_err(|e| if e.contains("host") { e } else { NOT.into() })?
Endpoint::parse(link).map_err(|e| if e.contains("host") || e.contains("certificate") { e } else { NOT.into() })?
} else {
return Err(NOT.into());
};
@@ -220,6 +272,19 @@ impl Invite {
}
}
/// URL-safe base64 without padding: how a link writes a certificate's SHA-256.
const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE_NO_PAD;
/// A `cert=` value: a SHA-256 in [`B64`] (43 characters). Errors don't echo it.
fn read_cert(v: &str) -> Result<[u8; 32], String> {
const BAD: &str = "the link's certificate (cert=) isn't a SHA-256 in URL-safe base64";
if v.len() != 43 {
return Err(BAD.into());
}
let bytes = B64.decode(v).map_err(|_| BAD)?;
<[u8; 32]>::try_from(bytes).map_err(|_| BAD.into())
}
/// Without surrounding spaces, quotes or angle brackets.
fn clean(s: &str) -> &str {
s.trim().trim_matches(|c| matches!(c, '<' | '>' | '"' | '\''))
+65 -3
View File
@@ -41,7 +41,7 @@ fn hosts_can_be_v6_or_names() {
#[test]
fn server_links_carry_tls_and_a_path() {
// A server behind a TLS reverse proxy, under a path: the server= form.
let i = Invite { server: Endpoint { host: "figcraft.example.com:443".into(), path: "/live/".into(), secure: true }, ..invite() };
let i = Invite { server: Endpoint { host: "figcraft.example.com:443".into(), path: "/live/".into(), secure: true, cert: None }, ..invite() };
assert_eq!(i.link(), format!("figcraft://join?server=wss://figcraft.example.com:443/live/&file=0123456789abcdef&token={TOKEN}"));
assert_eq!(i.url(), format!("wss://figcraft.example.com:443/live/?file=0123456789abcdef&token={TOKEN}"));
assert_eq!(i.endpoint(), "wss://figcraft.example.com:443/live/");
@@ -88,7 +88,7 @@ fn server_addresses_with_a_key() {
assert_eq!(e, Endpoint::plain("127.0.0.1:47900"));
assert_eq!(q, vec![("key".to_string(), "KeyKeyKeyKeyKeyKeyKey0".to_string())]);
let (e, q) = Endpoint::parse(" wss://example.org ").unwrap();
assert_eq!(e, Endpoint { host: "example.org:443".into(), path: "/".into(), secure: true });
assert_eq!(e, Endpoint { host: "example.org:443".into(), path: "/".into(), secure: true, cert: None });
assert!(q.is_empty());
let secret = "SuperSecretToken123456";
for bad in [
@@ -142,10 +142,18 @@ proptest! {
#[test]
fn valid_invites_round_trip(a in 1u8..255, port in 1u16.., file in "[a-f0-9]{1,64}", token in "[A-Za-z0-9_-]{16,128}", path in "(/[a-z0-9]{1,8}){0,3}", secure: bool) {
let i = Invite { server: Endpoint { host: format!("10.0.0.{a}:{port}"), path: format!("{path}/"), secure }, file, token };
let i = Invite { server: Endpoint { host: format!("10.0.0.{a}:{port}"), path: format!("{path}/"), secure, cert: None }, file, token };
prop_assert_eq!(Invite::parse(&i.link()), Ok(i.clone()));
prop_assert_eq!(Invite::parse(&i.url()), Ok(i));
}
#[test]
fn pinned_invites_round_trip(a in 1u8..255, port in 1u16.., pin: [u8; 32], file in "[a-f0-9]{1,64}", token in "[A-Za-z0-9_-]{16,128}") {
let i = Invite { server: Endpoint::pinned(format!("10.0.0.{a}:{port}"), pin), file, token };
prop_assert_eq!(Invite::parse(&i.link()), Ok(i.clone()));
prop_assert_eq!(Invite::parse(&i.url()), Ok(i.clone()));
prop_assert_eq!(Invite::parse(&i.team_link().replace("&team=1", &format!("&token={}", i.token))), Ok(i));
}
}
#[test]
@@ -163,3 +171,57 @@ fn port_must_be_all_digits() {
assert!(Endpoint::parse(bad).is_err(), "accepted {bad}");
}
}
/// The SHA-256 of an app's own certificate, as a link writes it.
const PIN: [u8; 32] = [7; 32];
const PIN_B64: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
#[test]
fn a_pinned_invite_names_its_certificate_in_both_forms_and_never_in_the_request() {
let i = Invite { server: Endpoint::pinned("192.168.1.20:47900", PIN), ..invite() };
assert_eq!(i.link(), format!("figcraft://join?server=wss://192.168.1.20:47900/&cert={PIN_B64}&file=0123456789abcdef&token={TOKEN}"));
assert_eq!(i.url(), format!("wss://192.168.1.20:47900/?cert={PIN_B64}&file=0123456789abcdef&token={TOKEN}"));
for way in [i.link(), i.url()] {
let back = Invite::parse(&way).unwrap();
assert_eq!((back.server.cert, back.server.secure), (Some(PIN), true), "{way}");
}
// What the client connects to carries neither the token nor the pin.
assert_eq!(i.endpoint(), "wss://192.168.1.20:47900/");
// A server address can carry one too (the query's other pairs stay).
let (e, query) = Endpoint::parse(&format!("wss://192.168.1.20:47900/?cert={PIN_B64}&key=k")).unwrap();
assert_eq!((e.cert, query), (Some(PIN), vec![("key".to_string(), "k".to_string())]));
}
#[test]
fn malformed_or_misplaced_certificates_are_refused_without_echoing_the_link() {
let other = "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg";
let rest = format!("file=0123456789abcdef&token={TOKEN}");
for bad in [
// Not 32 bytes, not URL-safe base64, padded, or with stray bits.
format!("wss://10.0.0.1:47900/?cert=BwcH&{rest}"),
format!("wss://10.0.0.1:47900/?cert={PIN_B64}A&{rest}"),
format!("wss://10.0.0.1:47900/?cert={PIN_B64}=&{rest}"),
format!("wss://10.0.0.1:47900/?cert=+wcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc&{rest}"),
format!("wss://10.0.0.1:47900/?cert=BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwd&{rest}"),
format!("wss://10.0.0.1:47900/?cert=&{rest}"),
format!("figcraft://join?server=wss://10.0.0.1:47900/&cert=%ZZ&{rest}"),
// On a plain address: never dropped (that would join without it).
format!("ws://10.0.0.1:47900/?cert={PIN_B64}&{rest}"),
format!("figcraft://join?host=10.0.0.1:47900&cert={PIN_B64}&{rest}"),
// Two that disagree.
format!("wss://10.0.0.1:47900/?cert={PIN_B64}&cert={other}&{rest}"),
format!("figcraft://join?server=wss://10.0.0.1:47900/%3Fcert%3D{PIN_B64}&cert={other}&{rest}"),
] {
let e = Invite::parse(&bad).expect_err(&bad);
assert!(!e.contains(TOKEN) && !e.contains("10.0.0.1") && !e.contains("BwcH"), "{bad}: {e}");
}
}
#[test]
fn an_allowed_server_allows_only_its_own_certificate() {
let allowed = Endpoint::pinned("10.0.0.1:47900", PIN);
assert!(Endpoint::pinned("10.0.0.1:47900", PIN).is_within(&allowed));
assert!(!Endpoint::pinned("10.0.0.1:47900", [8; 32]).is_within(&allowed));
let by_authority = Endpoint { cert: None, ..allowed.clone() };
assert!(!allowed.is_within(&by_authority), "a pin bypasses the authorities the allowed server is checked with");
}
+2
View File
@@ -26,6 +26,8 @@ mod requests;
mod sessions;
pub mod throttle;
#[cfg(not(target_arch = "wasm32"))]
pub mod cert;
#[cfg(not(target_arch = "wasm32"))]
pub mod guest;
#[cfg(not(target_arch = "wasm32"))]
+9 -2
View File
@@ -188,12 +188,19 @@ impl LiveLink for NetLink {
name: o.name,
limits: self.limits,
core: figcraft_collab::Limits::default(),
// Reachable from other machines: the token mustn't cross the network in the clear, so
// the session serves TLS to its own certificate, which its links pin. A session with a
// join code stays plain: a code has no room for the pin, and the code's joiners would
// fail against TLS (and share the token with the link's).
tls: !ip.is_loopback() && !o.short,
};
let host = Host::start(cfg, inbox.clone()).map_err(|e| format!("can't listen on {ip}: {e}"))?;
// Listening on every interface (`0.0.0.0`, `::`), the links name an address others reach.
let at = reachable(host.addr()).to_string();
let view = view_token.map(|v| Invite::new(at.clone(), file.clone(), v)).map(|v| WayIn { link: v.link(), url: v.url() });
let invite = Invite::new(at.clone(), file, token);
let server = host.endpoint(at.clone());
let view =
view_token.map(|v| Invite { server: server.clone(), file: file.clone(), token: v }).map(|v| WayIn { link: v.link(), url: v.url() });
let invite = Invite { server, file, token };
let info = SessionInfo {
role: Role::Host,
me: host.me().client_id,
+12 -2
View File
@@ -61,7 +61,7 @@ impl Probe {
})
}
fn joined(&self) -> Vec<u32> {
pub(crate) fn joined(&self) -> Vec<u32> {
self.events.iter().filter_map(|e| if let Event::PeerJoined(p) = e { Some(p.client_id) } else { None }).collect()
}
@@ -80,6 +80,12 @@ pub(crate) fn fast_limits() -> NetLimits {
/// A host on a free loopback port with these limits, a probe of what it is told, and its invite.
fn start_with(limits: NetLimits, core: Limits) -> (Host, Probe, Invite) {
host_on_loopback(limits, core, false)
}
/// A host on a free loopback port, serving TLS with its own certificate when `tls` (its invite
/// then pins it), a probe of what it is told, and its invite.
pub(crate) fn host_on_loopback(limits: NetLimits, core: Limits, tls: bool) -> (Host, Probe, Invite) {
let probe = Probe::new();
let mut doc = Document::new("Shared file");
doc.repair();
@@ -93,9 +99,10 @@ fn start_with(limits: NetLimits, core: Limits) -> (Host, Probe, Invite) {
name: "Hana".into(),
limits,
core,
tls,
};
let host = Host::start(cfg, probe.inbox.clone()).unwrap();
let invite = Invite::new(host.addr().to_string(), FILE, TOKEN);
let invite = Invite { server: host.endpoint(host.addr().to_string()), file: FILE.into(), token: TOKEN.into() };
(host, probe, invite)
}
@@ -278,6 +285,7 @@ fn a_view_token_lets_people_look_and_not_edit() {
name: "Hana".into(),
limits: fast_limits(),
core: Limits::default(),
tls: false,
}
};
let same = Host::start(cfg(TOKEN), probe.inbox.clone()).err().expect("a view token equal to the edit token is refused");
@@ -318,6 +326,7 @@ fn a_file_with_review_settings_past_the_limits_is_not_shared() {
name: "Hana".into(),
limits: fast_limits(),
core: Limits::default(),
tls: false,
};
let e = Host::start(cfg, probe.inbox.clone()).err().expect("settings past the limits are refused");
let text = e.to_string();
@@ -793,6 +802,7 @@ fn a_welcome_over_the_size_limit_says_the_file_is_too_large() {
name: "Hana".into(),
limits: fast_limits(),
core: Limits::default(),
tls: false,
};
let mut host = Host::start(cfg, probe.inbox.clone()).unwrap();
let invite = Invite::new(host.addr().to_string(), FILE, TOKEN);
+2 -2
View File
@@ -250,7 +250,7 @@ mod tests {
}
});
let limits = NetLimits { idle_timeout: idle, ..NetLimits::default() };
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false };
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false, cert: None };
let ws = connect(&server, &limits, Duration::from_secs(2)).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
@@ -274,7 +274,7 @@ mod tests {
}
});
let limits = NetLimits { request_reply_timeout: Duration::from_millis(400), ..NetLimits::default() };
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false };
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false, cert: None };
let mut ws = connect(&server, &limits, Duration::from_secs(2)).unwrap();
let started = std::time::Instant::now();
assert!(reply::<()>(&mut ws, &limits, |_| None).is_err());
+6 -2
View File
@@ -239,13 +239,17 @@ pub fn shutdown(s: &TcpStream) {
let _ = s.shutdown(Shutdown::Both);
}
/// Connect to `server` (through TLS for `wss://`): the reader's and the writer's handles, and the
/// Connect to `server` (through TLS for `wss://`, to exactly its pinned certificate when it has one): the reader's and the writer's handles, and the
/// socket to shut it down with.
pub fn open(server: &Endpoint, timeout: Duration, limits: &NetLimits) -> Result<(Duplex, Duplex, TcpStream), String> {
// A plain `ws://localhost` is trusted as this machine (a key may go over it), so only loopback
// addresses are connected to: a resolver mapping the name elsewhere must not carry it off-machine.
let stream = dial(&server.host, !server.secure && server.loopback(), timeout, limits)?;
let tls = if server.secure { Some(tls::handshake(&stream, &server.host)?) } else { None };
let tls = match (server.secure, &server.cert) {
(true, Some(pin)) => Some(tls::handshake_pinned(&stream, &server.host, pin)?),
(true, None) => Some(tls::handshake(&stream, &server.host)?),
(false, _) => None,
};
Duplex::split(stream, tls).map_err(|e| e.to_string())
}
+137 -15
View File
@@ -8,15 +8,27 @@
//! sender takes the socket's write lock first (so records go out in the order they were made),
//! encrypts under the session's lock, then writes with only the socket's. Neither waits on the
//! network while holding the session, so a send stuck behind a full socket never stops the reader
//! from draining what arrives.
//! from draining what arrives. The session is a client's or, for an app hosting on the network
//! with its own certificate ([`crate::cert`]), a server's ([`accept`]).
//!
//! A `wss://` address with a `cert=` pin ([`handshake_pinned`]) trusts no authority: the server
//! must present exactly the certificate whose SHA-256 the invite names, and prove it holds its key.
use std::io::{self, Read, Write};
use std::net::TcpStream;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::time::Instant;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, ServerName};
use rustls::{CertificateError, ClientConfig, ClientConnection, RootCertStore};
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{
CertificateError, ClientConfig, ClientConnection, Connection, DigitallySignedStruct, RootCertStore, ServerConfig, ServerConnection,
SignatureScheme,
};
use crate::cert::{Fingerprint, fingerprint};
/// The variable naming a PEM file of extra certificate authorities to trust.
pub const CA_FILE: &str = "FIGCRAFT_CA_FILE";
@@ -24,24 +36,65 @@ pub const CA_FILE: &str = "FIGCRAFT_CA_FILE";
/// The variable that, set, leaves the operating system's certificate store out.
pub const NO_SYSTEM_ROOTS: &str = "FIGCRAFT_NO_SYSTEM_ROOTS";
/// One connection's TLS session, shared by its reader and writer.
pub type Tls = Arc<Mutex<ClientConnection>>;
/// One connection's TLS session (a client's or a server's), shared by its reader and writer.
pub type Tls = Arc<Mutex<Connection>>;
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
/// The certificate name in `host` (`name:port`, `[v6]:port`).
fn server_name(host: &str) -> Result<ServerName<'static>, String> {
let name = host.rsplit_once(':').map_or(host, |(n, _)| n).trim_start_matches('[').trim_end_matches(']');
ServerName::try_from(name.to_string()).map_err(|_| format!("{name} isn't a name a certificate can be for"))
}
/// Set up TLS on `stream`, connected to `host` (`name:port`), verifying its certificate.
pub fn handshake(stream: &TcpStream, host: &str) -> Result<Tls, String> {
let name = host.rsplit_once(':').map_or(host, |(n, _)| n).trim_start_matches('[').trim_end_matches(']');
let name = ServerName::try_from(name.to_string()).map_err(|_| format!("{name} isn't a name a certificate can be for"))?;
let mut conn = ClientConnection::new(config()?, name).map_err(|e| e.to_string())?;
let conn = ClientConnection::new(config()?, server_name(host)?).map_err(|e| e.to_string())?;
client_handshake(stream, conn).map_err(|e| explain(host, &e))
}
/// Set up TLS on `stream`, connected to `host`, accepting only the certificate whose SHA-256 is
/// `expected` (an invite's `cert=`): no authority is asked, and any other certificate (someone in
/// between) is refused before anything is sent.
pub fn handshake_pinned(stream: &TcpStream, host: &str, expected: &Fingerprint) -> Result<Tls, String> {
let conn = ClientConnection::new(pinned_config(expected)?, server_name(host)?).map_err(|e| e.to_string())?;
client_handshake(stream, conn).map_err(|e| match rustls_error(&e) {
Some(rustls::Error::InvalidCertificate(CertificateError::ApplicationVerificationFailure)) => format!(
"the certificate of {host} isn't the one the invite names: someone may be in between, or the session restarted (ask for a new invite link)"
),
_ => explain(host, &e),
})
}
fn client_handshake(stream: &TcpStream, mut conn: ClientConnection) -> io::Result<Tls> {
// Writes are flushed to the socket at once, so the queue never grows.
conn.set_buffer_limit(None);
while conn.is_handshaking() {
conn.complete_io(&mut &*stream).map_err(|e| explain(host, &e))?;
conn.complete_io(&mut &*stream)?;
}
Ok(Arc::new(Mutex::new(conn)))
Ok(Arc::new(Mutex::new(Connection::Client(conn))))
}
/// Answer a client's TLS handshake on `stream` with `config`, by `deadline` however slowly its
/// bytes come.
pub fn accept(stream: &TcpStream, config: Arc<ServerConfig>, deadline: Instant) -> io::Result<Tls> {
let mut conn = ServerConnection::new(config).map_err(io::Error::other)?;
conn.set_buffer_limit(None);
while conn.is_handshaking() {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err(io::ErrorKind::TimedOut.into());
}
stream.set_read_timeout(Some(left))?;
conn.complete_io(&mut &*stream)?;
}
Ok(Arc::new(Mutex::new(Connection::Server(conn))))
}
fn rustls_error(e: &io::Error) -> Option<&rustls::Error> {
e.get_ref().and_then(|i| i.downcast_ref::<rustls::Error>())
}
/// Why the TLS handshake with `host` failed, in words.
@@ -56,7 +109,7 @@ fn explain(host: &str, e: &io::Error) -> String {
CertificateError::Revoked => "has been revoked".into(),
other => format!("isn't valid ({other:?})"),
};
match e.get_ref().and_then(|i| i.downcast_ref::<rustls::Error>()) {
match rustls_error(e) {
Some(rustls::Error::InvalidCertificate(c)) => format!("the certificate of {host} {}", why(c)),
Some(other) => format!("no secure connection to {host} ({other}); is a TLS server answering there?"),
None => format!("no secure connection to {host} ({e})"),
@@ -91,7 +144,7 @@ fn make_config() -> Result<Arc<ClientConfig>, String> {
}
#[cfg(test)]
roots.add(CertificateDer::from(&include_bytes!("testdata/test-ca.der")[..])).map_err(|e| e.to_string())?;
let config = ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
let config = ClientConfig::builder_with_provider(provider())
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.with_root_certificates(roots)
@@ -99,10 +152,79 @@ fn make_config() -> Result<Arc<ClientConfig>, String> {
Ok(Arc::new(config))
}
/// The ring provider every connection uses.
fn provider() -> Arc<CryptoProvider> {
Arc::new(rustls::crypto::ring::default_provider())
}
/// Client settings trusting only the certificate `expected` is the SHA-256 of.
fn pinned_config(expected: &Fingerprint) -> Result<Arc<ClientConfig>, String> {
let provider = provider();
let verifier = Pinned { expected: *expected, algorithms: provider.signature_verification_algorithms };
let config = ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.dangerous()
.with_custom_certificate_verifier(Arc::new(verifier))
.with_no_client_auth();
Ok(Arc::new(config))
}
/// Accepts the one certificate an invite pins, and only a handshake signed with its key.
#[derive(Debug)]
struct Pinned {
expected: Fingerprint,
algorithms: WebPkiSupportedAlgorithms,
}
/// `a == b`, in a time that doesn't depend on where they differ.
fn same(a: &Fingerprint, b: &Fingerprint) -> bool {
a.iter().zip(b).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0
}
impl ServerCertVerifier for Pinned {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
if same(&fingerprint(end_entity.as_ref()), &self.expected) {
Ok(ServerCertVerified::assertion())
} else {
Err(rustls::Error::InvalidCertificate(CertificateError::ApplicationVerificationFailure))
}
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(message, cert, dss, &self.algorithms)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(message, cert, dss, &self.algorithms)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algorithms.supported_schemes()
}
}
/// Read plaintext into `buf`: what the session has, else wait for bytes on `sock` (outside the
/// session's lock), take them in and try again. Anything the session must answer (alerts, key
/// updates) goes out through `out`.
pub fn read(tls: &Mutex<ClientConnection>, sock: &mut TcpStream, out: &Mutex<TcpStream>, buf: &mut [u8]) -> io::Result<usize> {
pub fn read(tls: &Mutex<Connection>, sock: &mut TcpStream, out: &Mutex<TcpStream>, buf: &mut [u8]) -> io::Result<usize> {
loop {
match lock(tls).reader().read(buf) {
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {}
@@ -126,14 +248,14 @@ pub fn read(tls: &Mutex<ClientConnection>, sock: &mut TcpStream, out: &Mutex<Tcp
}
/// Encrypt and send all of `buf`.
pub fn write(tls: &Mutex<ClientConnection>, out: &Mutex<TcpStream>, buf: &[u8]) -> io::Result<usize> {
pub fn write(tls: &Mutex<Connection>, out: &Mutex<TcpStream>, buf: &[u8]) -> io::Result<usize> {
send(tls, out, buf)?;
Ok(buf.len())
}
/// Encrypt `plain` and send it after whatever the session has waiting (see the module's docs for
/// the locking).
fn send(tls: &Mutex<ClientConnection>, out: &Mutex<TcpStream>, plain: &[u8]) -> io::Result<()> {
fn send(tls: &Mutex<Connection>, out: &Mutex<TcpStream>, plain: &[u8]) -> io::Result<()> {
let mut w = lock(out);
let mut records = Vec::new();
{
+101 -5
View File
@@ -1,19 +1,22 @@
//! Joining over `wss://`: a guest and a managing connection reach a host through a TLS terminator
//! (like the reverse proxy in front of a server) whose certificate comes from a test authority
//! only test builds trust; a certificate for another name is refused with a clear reason.
//! only test builds trust; a certificate for another name is refused with a clear reason. An app
//! hosting with its own certificate is joined through the pin in its invite, and only through it:
//! a plain client, or a host presenting another certificate (someone in between), gets nothing.
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, Instant};
use figcraft_collab::Limits;
use figcraft_engine::live::{Event, Status};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
use rustls::{ServerConfig, ServerConnection, StreamOwned};
use crate::guest::{Guest, GuestConfig};
use crate::invite::{Endpoint, Invite};
use crate::loopback_tests::{Probe, fast_limits, quick, start};
use crate::loopback_tests::{Probe, fast_limits, host_on_loopback, quick, start};
use crate::manage;
/// Serve `localhost`'s test certificate on a port of `localhost` and relay each connection to
@@ -67,7 +70,7 @@ fn relay(s: TcpStream, upstream: SocketAddr, cfg: Arc<ServerConfig>) {
}
fn secure(host: String, invite: &Invite) -> Invite {
Invite { server: Endpoint { host, path: "/".into(), secure: true }, ..invite.clone() }
Invite { server: Endpoint { host, path: "/".into(), secure: true, cert: None }, ..invite.clone() }
}
#[test]
@@ -111,7 +114,7 @@ fn reader_and_writer_share_one_session_without_blocking_each_other() {
let _ = io::copy(&mut s.try_clone().unwrap(), &mut s);
});
let front = terminator(upstream);
let server = Endpoint { host: format!("localhost:{}", front.port()), path: "/".into(), secure: true };
let server = Endpoint { host: format!("localhost:{}", front.port()), path: "/".into(), secure: true, cert: None };
let (mut rd, mut wr, _sock) = crate::net::open(&server, Duration::from_secs(5), &fast_limits()).unwrap();
rd.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
let sent: Vec<u8> = (0..8 << 20).map(|i: u32| (i % 251) as u8).collect();
@@ -122,3 +125,96 @@ fn reader_and_writer_share_one_session_without_blocking_each_other() {
writer.join().unwrap();
assert!(got == expect);
}
/// The loopback hosts' token.
const TOKEN_OF_TESTS: &str = "AbCdEfGhIjKlMnOpQrStUv";
fn tls_host() -> (crate::host::Host, Probe, Invite) {
host_on_loopback(fast_limits(), Limits::default(), true)
}
fn failed(e: &[Event]) -> Option<&str> {
e.iter().find_map(|e| match e {
Event::Status(Status::Failed { reason }) => Some(reason.as_str()),
_ => None,
})
}
#[test]
fn a_host_with_its_own_certificate_is_joined_through_the_pin() {
let (mut host, mut hp, invite) = tls_host();
let pin = host.cert_sha256().unwrap();
assert_eq!((invite.server.secure, invite.server.cert), (true, Some(pin)));
assert!(invite.link().contains("cert=") && invite.url().starts_with("wss://"), "{}", invite.link());
// Joined from the link, as someone pasting it would; the document comes over TLS.
let mut probe = Probe::new();
let mut g = Guest::start(quick(GuestConfig::new(Invite::parse(&invite.link()).unwrap(), "Ada".into())), probe.inbox.clone()).unwrap();
probe.wait("the welcome over pinned TLS", |e| e.iter().any(|e| matches!(e, Event::Welcome { .. })));
hp.wait("the guest in the host's session", |e| e.iter().any(|e| matches!(e, Event::PeerJoined(_))));
g.leave();
host.stop();
}
/// Someone in between (here: another host with the same file and token, and a certificate of its
/// own) is refused before the guest says anything: the token never reaches it.
#[test]
fn a_host_presenting_another_certificate_is_refused_before_the_hello() {
let (mut real, _rp, invite) = tls_host();
let (mut mitm, mut mp, posing) = tls_host();
assert_ne!(real.cert_sha256(), mitm.cert_sha256());
let pinned_to_real = Invite { server: Endpoint { host: posing.server.host.clone(), ..invite.server.clone() }, ..invite };
let mut probe = Probe::new();
let _g = Guest::start(quick(GuestConfig::new(pinned_to_real, "Ada".into())), probe.inbox.clone()).unwrap();
probe.wait("the refusal", |e| failed(e).is_some());
let reason = failed(&probe.events).unwrap();
assert!(reason.contains("isn't the one the invite names"), "{reason}");
assert!(!reason.contains(TOKEN_OF_TESTS) && !reason.contains("cert="), "{reason}");
std::thread::sleep(Duration::from_millis(200));
mp.events.extend(mp.inbox.drain());
assert!(mp.joined().is_empty(), "the impostor admitted the guest: {:#?}", mp.events);
assert!(!probe.events.iter().any(|e| matches!(e, Event::Welcome { .. })));
mitm.stop();
real.stop();
}
/// A plain `ws://` client gets no session from a TLS host, and soon knows it.
#[test]
fn a_plain_client_cant_join_a_tls_host() {
let (mut host, mut hp, invite) = tls_host();
let plain = Invite::new(invite.server.host.clone(), invite.file.clone(), invite.token.clone());
let mut probe = Probe::new();
let started = Instant::now();
let _g = Guest::start(quick(GuestConfig::new(plain, "Ada".into())), probe.inbox.clone()).unwrap();
probe.wait("the failure", |e| failed(e).is_some());
assert!(started.elapsed() < fast_limits().hello_timeout, "{:?}", started.elapsed());
hp.events.extend(hp.inbox.drain());
assert!(hp.joined().is_empty());
host.stop();
}
/// The WebSocket request to a pinned host names neither the token nor the pin.
#[test]
fn the_request_to_a_pinned_host_carries_no_secret() {
let cert = crate::cert::generate().unwrap();
let cfg = crate::cert::server_config(&cert).unwrap();
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let (s, _) = listener.accept().unwrap();
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut tls = StreamOwned::new(ServerConnection::new(cfg).unwrap(), s);
let mut req = Vec::new();
let mut b = [0u8; 1];
while !req.ends_with(b"\r\n\r\n") && tls.read_exact(&mut b).is_ok() {
req.push(b[0]);
}
let _ = tx.send(String::from_utf8_lossy(&req).into_owned());
});
let invite = Invite { server: Endpoint::pinned(addr.to_string(), cert.sha256), file: "0123456789abcdef".into(), token: TOKEN_OF_TESTS.into() };
let _g = Guest::start(quick(GuestConfig::new(invite, "Ada".into())), Probe::new().inbox.clone()).unwrap();
let req = rx.recv_timeout(Duration::from_secs(10)).unwrap();
let line = req.lines().next().unwrap_or_default();
assert!(line.starts_with("GET / "), "{req}");
assert!(!req.contains(TOKEN_OF_TESTS) && !req.contains("cert"), "{req}");
}
+5
View File
@@ -142,6 +142,11 @@ fn js_error(e: &wasm_bindgen::JsValue) -> String {
/// Whether this page may reach `server`: an `https://` page can't open an unencrypted `ws://`
/// connection, except to this machine.
fn reachable(server: &Endpoint) -> Result<(), String> {
// A browser checks certificates against its authorities only: it can't hold a connection to
// the one certificate an app's invite pins.
if server.cert.is_some() {
return Err("that session is hosted by an app on its local network with its own certificate, which a browser can't check: join it from the desktop app".into());
}
let secure_page = web_sys::window().and_then(|w| w.location().protocol().ok()).is_some_and(|p| p == "https:");
if secure_page && !server.secure && !server.loopback() {
return Err("this page was loaded over https, and browsers block unencrypted ws:// connections; use a wss:// address (a server behind TLS), open FigCraft from an http:// address (like http://localhost:8767), or use the desktop app".into());
+16 -4
View File
@@ -551,6 +551,15 @@ resuming with its offline edits, and leaving the session going back to snapshot
`ws://<ip:port>/` and sends the token only inside its `Hello`. Links are pasted into the Join
dialog (its field has the keyboard when it opens; Escape closes it), or opened from anywhere:
see *Opening invite links* below.
- TLS off this machine: a host others reach (any address but loopback) without a join code
serves TLS with an Ed25519 certificate made for the session (gone when it stops), and its links
pin it: `figcraft://join?server=wss://<ip:port>/&cert=<sha256>&file=…&token=…` or
`wss://<ip:port>/?cert=<sha256>&file=…&token=…` (`<sha256>`: the certificate's SHA-256 in
URL-safe base64 without padding). A guest trusts no authority for it: it accepts only exactly
that certificate, with the handshake signed by its key, and refuses any other before its
`Hello` (someone in between gets nothing). A plain `ws://` client gets no session from such a
host. A local network share with a join code stays plain `ws://`: a 20-symbol code has no room
for the pin.
- Reconnect: a connection that drops after it was live reconnects until you leave, with growing
pauses (0.5 s, doubling up to 10 s, 12 attempts), then a minute's pause and as many again. A
server turning a live session away is taken as passing (busy, a limit, a file it couldn't read
@@ -769,7 +778,8 @@ resuming with its offline edits, and leaving the session going back to snapshot
engine's link (which must be `Send`) holds only the session's number and its inbox.
- Hosting stays desktop-only (a page can't listen on a socket); the Share popover in the browser
says so and offers only joining, and `collab.peers` reports `canHost: false`.
- **Mixed content.** A desktop-hosted session is plain `ws://`. Browsers block `ws://` from a page
- **Mixed content.** A desktop-hosted session is plain `ws://`, or pinned `wss://`, which a browser
can't check (it refuses such a link and says to join from the desktop app). Browsers block `ws://` from a page
loaded over `https://`, except to this machine (`127.0.0.1`, `[::1]`, `localhost`), so an https
page refuses other hosts up front with a message instead of failing obscurely. To join from
other machines, serve the web build over `http://` on a trusted network (locally:
@@ -1028,9 +1038,11 @@ chooses to share on the network; the default is the invite link with a random to
constant time (the hub's backend). It is in the invite link by design, so whoever holds the link
can join until the session stops: share it like a password. It never travels in the WebSocket
request (the path is `/`), so proxies don't log it; FigCraft never logs it (logs name addresses
and ports only), and errors about links never echo the link. Traffic is not encrypted (`ws://`):
on a shared network, others on the path could read presence and the token. Use a trusted LAN
or a VPN; TLS (`wss://`) comes from a reverse proxy in front of a `figcraft-server`.
and ports only), and errors about links never echo the link. A host reachable from other
machines serves pinned TLS (above). A share with a join code, and a host on this machine only,
are not encrypted (`ws://`): on a shared network, others on the path could read a code share's
presence and token, so use a trusted LAN or a VPN for those; TLS for a `figcraft-server` comes
from a reverse proxy in front of it.
- **Limits.** At most 64 open sockets (joined or not) and the core's 256 people; a connection must
finish the WebSocket handshake and say hello within 10 s, and one silent for 45 s is dropped
(clients ping every 15 s); client messages are at most 16 MiB (what the host sends keeps the
+3 -1
View File
@@ -1715,7 +1715,9 @@ only: a host stops hosting it, a guest leaves it.
or any free one when it's taken, as it is for a second hosted document (`port` picks one, 0
any). Returns the session as
`collab.peers` does, with `link` (`figcraft://join?host=…&file=…&token=…`) and `url`
(`ws://…/?file=…&token=…`): both carry the session's secret, so share them only with people you
(`ws://…/?file=…&token=…`); bound to any address but this machine's, the session serves TLS
with its own certificate and they pin it (`figcraft://join?server=wss://…&cert=…&file=…&token=…`,
`wss://…/?cert=…&file=…&token=…`; see `docs/collab-protocol.md`): both carry the session's secret, so share them only with people you
invite. `collab.stop {}` ends the active document's session.
- `collab.join {code}` or `collab.join {link}` (a join code of either kind: spaces, dashes and
case don't matter, `O` reads as `0` and `I` or `L` as `1`; or a link in any form: an app's