Merge branch 't3/p15-b2-relay-service': the relay service (P15 B2)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 09:53:38 -07:00
commit 06daffea76
26 files changed
+10460 -6

No files matched your search

Generated
+225 -4
View File
@@ -352,6 +352,45 @@ dependencies = [
"libloading",
]
[[package]]
name = "asn1-rs"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
dependencies = [
"asn1-rs-derive",
"asn1-rs-impl",
"displaydoc",
"nom",
"num-traits",
"rusticata-macros",
"thiserror 2.0.21",
"time",
]
[[package]]
name = "asn1-rs-derive"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"synstructure 0.13.2",
]
[[package]]
name = "asn1-rs-impl"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -692,6 +731,9 @@ name = "bit-vec"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
dependencies = [
"serde",
]
[[package]]
name = "bit-vec"
@@ -1407,6 +1449,12 @@ dependencies = [
"itertools 0.13.0",
]
[[package]]
name = "critical-section"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
[[package]]
name = "crossbeam-deque"
version = "0.8.8"
@@ -1584,6 +1632,20 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "der-parser"
version = "10.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
dependencies = [
"asn1-rs",
"displaydoc",
"nom",
"num-bigint",
"num-traits",
"rusticata-macros",
]
[[package]]
name = "deranged"
version = "0.5.8"
@@ -3021,6 +3083,25 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hickory-proto"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d"
dependencies = [
"data-encoding",
"idna",
"ipnet",
"jni",
"once_cell",
"rand 0.10.3",
"ring",
"thiserror 2.0.21",
"tinyvec",
"tracing",
"url",
]
[[package]]
name = "hmac"
version = "0.12.1"
@@ -4325,6 +4406,12 @@ dependencies = [
"unicase",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "minisign"
version = "0.10.0"
@@ -4492,6 +4579,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "notify"
version = "8.2.0"
@@ -4945,11 +5042,24 @@ dependencies = [
"memchr",
]
[[package]]
name = "oid-registry"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
dependencies = [
"asn1-rs",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
dependencies = [
"critical-section",
"portable-atomic",
]
[[package]]
name = "oorandom"
@@ -5140,6 +5250,16 @@ dependencies = [
"ryu",
]
[[package]]
name = "pem"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"
dependencies = [
"base64 0.23.1",
"serde_core",
]
[[package]]
name = "peniko"
version = "0.6.1"
@@ -5817,6 +5937,20 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "rcgen"
version = "0.14.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
dependencies = [
"pem",
"ring",
"rustls-pki-types",
"time",
"x509-parser",
"yasna",
]
[[package]]
name = "read-fonts"
version = "0.39.2"
@@ -5952,6 +6086,28 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "relay"
version = "0.1.0"
dependencies = [
"futures",
"hickory-proto",
"proptest",
"rcgen",
"ring",
"rusqlite",
"rustls",
"serde",
"serde_json",
"tempfile",
"thiserror 2.0.21",
"tokio",
"tokio-rustls",
"tokio-util",
"toml 1.1.8+spec-1.1.0",
"yamux",
]
[[package]]
name = "renderdoc-sys"
version = "1.1.0"
@@ -6226,6 +6382,15 @@ dependencies = [
"semver",
]
[[package]]
name = "rusticata-macros"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
dependencies = [
"nom",
]
[[package]]
name = "rustix"
version = "0.38.44"
@@ -6271,6 +6436,7 @@ checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"aws-lc-rs",
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
@@ -7021,6 +7187,17 @@ dependencies = [
"futures-core",
]
[[package]]
name = "synstructure"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "synstructure"
version = "0.14.0"
@@ -7081,7 +7258,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.61.2",
@@ -7296,6 +7473,7 @@ checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b"
dependencies = [
"bytes",
"futures-core",
"futures-io",
"futures-sink",
"futures-util",
"libc",
@@ -9198,6 +9376,24 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
[[package]]
name = "x509-parser"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
dependencies = [
"asn1-rs",
"data-encoding",
"der-parser",
"lazy_static",
"nom",
"oid-registry",
"ring",
"rusticata-macros",
"thiserror 2.0.21",
"time",
]
[[package]]
name = "xcursor"
version = "0.3.11"
@@ -9250,6 +9446,31 @@ dependencies = [
"linked-hash-map",
]
[[package]]
name = "yamux"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f4e661d6ba6f09a768e31c6f3d88f9fac596ad5d376515d598a37b62d220b34"
dependencies = [
"futures",
"log",
"nohash-hasher",
"parking_lot",
"pin-project",
"static_assertions",
"web-time",
]
[[package]]
name = "yasna"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
dependencies = [
"bit-vec 0.9.1",
"time",
]
[[package]]
name = "yoke"
version = "0.8.3"
@@ -9270,7 +9491,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.7",
"synstructure",
"synstructure 0.14.0",
]
[[package]]
@@ -9417,7 +9638,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.7",
"synstructure",
"synstructure 0.14.0",
]
[[package]]
@@ -9502,7 +9723,7 @@ dependencies = [
"sha1",
"time",
"typed-path",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
"zeroize",
"zopfli",
"zstd",
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["crates/ledger-core", "crates/ledger-store", "crates/ledger-config", "crates/ledger-mcp", "crates/ledger-import", "crates/ledger-reader", "crates/ledger-cli", "crates/ledger-gui", "crates/ledger-vault", "crates/ledger-host", "crates/ledger-package"]
members = ["crates/ledger-core", "crates/ledger-store", "crates/ledger-config", "crates/ledger-mcp", "crates/ledger-import", "crates/ledger-reader", "crates/ledger-cli", "crates/ledger-gui", "crates/ledger-vault", "crates/ledger-host", "crates/ledger-package", "crates/relay"]
[workspace.package]
edition = "2024"
+40
View File
@@ -0,0 +1,40 @@
[package]
name = "relay"
version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "The relay for wanderbooks.link: routes an assistant's TLS connection, by server name, down the line an app holds open, and is the domain's DNS server. It forwards encrypted bytes and holds no certificate for any app."
[lib]
name = "relay"
path = "src/lib.rs"
[[bin]]
name = "relay"
path = "src/main.rs"
[dependencies]
futures = "0.3"
hickory-proto = { version = "0.26", default-features = false, features = ["std"] }
ring = "0.17"
rusqlite = { version = "0.41", features = ["bundled"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "sync", "net", "signal", "time"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
tokio-util = { version = "0.7", features = ["compat"] }
toml = "1"
yamux = "0.14"
[dev-dependencies]
tokio = { version = "1", features = ["test-util"] }
proptest = "1"
rcgen = { version = "0.14", default-features = false, features = ["ring", "pem"] }
tempfile = "3"
[lints]
workspace = true
+443
View File
@@ -0,0 +1,443 @@
//! The certificate authorities: a list the relay serves, not code.
//!
//! Every authority an app may use speaks the same protocol (ACME,
//! RFC 8555). The app's certificate code knows the protocol and nothing
//! about any one authority; at each issuance it asks the relay for the
//! list to try, in order. Swapping Let's Encrypt for Google Trust Services
//! or ZeroSSL, or adding one, is an edit to the list the relay reads, with
//! no release of the app.
//!
//! The list names each authority's directory address and the domain it
//! uses in a CAA record (its "issuer domain name", which its own
//! documentation gives). The relay's DNS answers CAA for the zone from the
//! same list, naming each listed authority and the DNS-01 method only, so
//! swapping an authority is an edit to this one file.
//!
//! ```toml
//! [[authority]]
//! id = "letsencrypt"
//! directory = "https://acme-v02.api.letsencrypt.org/directory"
//! caa_domain = "letsencrypt.org"
//!
//! [[authority]]
//! id = "zerossl"
//! directory = "https://acme.zerossl.com/v2/DV90"
//! caa_domain = "sectigo.com"
//! needs_binding = true
//! ```
//!
//! The file never holds a binding credential: an account-binding secret
//! (RFC 8555 section 7.3.4) is one an authority issues for one account,
//! and serving a shared one to every app would hand every holder of a name
//! the operator's account. A file with `binding_kid` or `binding_hmac_key`
//! is refused. A binding comes from a [`BindingSource`], per app; with none
//! installed an authority that needs one is still listed, marked not
//! usable, and served without one.
//!
//! ```text
//! GOAL: the authority an app asks is chosen by the relay's list at the
//! moment of the request, in the list's order, so an operator can
//! change authorities without a release of the app.
//! SOURCE: WB-relay-5 (the list of authorities), D-87, RFC 8555 section
//! 7.3.4 (external account binding).
//! INVARIANTS:
//! 1. The list is served in the order written, with each authority's
//! directory address and whether it needs a binding.
//! 2. No binding secret is ever served from the file: a file that
//! carries one is refused (a new file leaves the old list in force),
//! and a binding is served only when a per-app [`BindingSource`]
//! gives one; an authority that needs one and has none is served
//! without a binding and marked not usable.
//! 3. A bad file never replaces a good list.
//! 4. The list is bounded: at most 16 authorities.
//! 5. The CAA issuer set is the list's `caa_domain`s, in order, and
//! follows the file.
//! SCENARIOS:
//! 1. Two authorities, the first plain and the second needing a binding,
//! are served in that order; the second has a binding only from a
//! source, and is marked not usable without one.
//! 2. The file is edited to put the second first: the next read serves
//! that order.
//! 3. The file is edited to garbage: the old list is still served.
//! 4. A file with a binding secret in it is refused in words.
//! ```
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::time::SystemTime;
use serde::Deserialize;
use crate::names::Name;
use crate::proto::{Authority, Binding};
const MAX_AUTHORITIES: usize = 16;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct File {
#[serde(default)]
authority: Vec<Entry>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct Entry {
id: String,
directory: String,
caa_domain: String,
#[serde(default)]
needs_binding: bool,
// Never accepted: read only to be refused in words.
binding_kid: Option<String>,
binding_hmac_key: Option<String>,
}
/// Why a list was refused.
#[derive(Debug, thiserror::Error)]
pub enum ListError {
/// The file is not valid TOML of this shape.
#[error("authority list: {0}")]
Toml(#[from] toml::de::Error),
/// The file could not be read.
#[error("authority list: {0}")]
Io(#[from] std::io::Error),
/// The list is empty, too long, or an entry is wrong.
#[error("authority list: {0}")]
Invalid(String),
}
/// Where an app's binding credential comes from: one per app, obtained
/// from the authority's own API by a deployment that implements this. The
/// list file never carries one.
pub trait BindingSource: Send + Sync {
/// The credential for this app at this authority, if one is needed.
fn binding_for(&self, authority_id: &str, name: &Name) -> Option<Binding>;
}
#[derive(Debug, Clone)]
struct Listed {
id: String,
directory: String,
needs_binding: bool,
caa_domain: String,
}
/// The list the relay serves.
pub struct AuthorityList {
current: RwLock<Arc<Vec<Listed>>>,
source: Option<PathBuf>,
seen: std::sync::Mutex<Option<SystemTime>>,
bindings: Option<Arc<dyn BindingSource>>,
}
fn is_loopback_http(url: &str) -> bool {
["http://127.0.0.1", "http://localhost", "http://[::1]"]
.iter()
.any(|p| url.starts_with(p))
}
/// A domain name fit for a CAA `issue` value: lower-case letters, digits
/// and hyphens in labels of 1 to 63, at least two labels, 253 at most. No
/// `;` or space, so no parameter can be smuggled into the record.
fn is_caa_domain(d: &str) -> bool {
d.len() <= 253
&& d.split('.').count() >= 2
&& d.split('.').all(|l| {
(1..=63).contains(&l.len())
&& !l.starts_with('-')
&& !l.ends_with('-')
&& l.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
})
}
fn parse(text: &str) -> Result<Vec<Listed>, ListError> {
let file: File = toml::from_str(text)?;
if file.authority.is_empty() || file.authority.len() > MAX_AUTHORITIES {
return Err(ListError::Invalid(format!(
"1 to {MAX_AUTHORITIES} authorities, not {}",
file.authority.len()
)));
}
let mut out: Vec<Listed> = Vec::new();
for e in file.authority {
if e.id.is_empty() || e.id.len() > 64 || out.iter().any(|o| o.id == e.id) {
return Err(ListError::Invalid(format!("authority id {:?}", e.id)));
}
if e.directory.len() > 512
|| !(e.directory.starts_with("https://") || is_loopback_http(&e.directory))
{
return Err(ListError::Invalid(format!(
"{}: the directory must be https",
e.id
)));
}
if e.binding_kid.is_some() || e.binding_hmac_key.is_some() {
return Err(ListError::Invalid(format!(
"{}: the list must not carry a binding secret (binding_kid, \
binding_hmac_key): a shared credential would be served to every app. \
Mark the authority needs_binding = true and give the relay a per-app \
binding source instead",
e.id
)));
}
if !is_caa_domain(&e.caa_domain) {
return Err(ListError::Invalid(format!(
"{}: caa_domain must be the authority's issuer domain name, \
such as letsencrypt.org",
e.id
)));
}
out.push(Listed {
id: e.id,
directory: e.directory,
needs_binding: e.needs_binding,
caa_domain: e.caa_domain,
});
}
Ok(out)
}
impl AuthorityList {
/// A list from TOML text.
pub fn from_toml(text: &str) -> Result<Self, ListError> {
Ok(AuthorityList {
current: RwLock::new(Arc::new(parse(text)?)),
source: None,
seen: std::sync::Mutex::new(None),
bindings: None,
})
}
/// A list read from a file, and read again by [`AuthorityList::reload`].
pub fn from_file(path: PathBuf) -> Result<Self, ListError> {
let text = std::fs::read_to_string(&path)?;
let list = parse(&text)?;
let seen = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
Ok(AuthorityList {
current: RwLock::new(Arc::new(list)),
source: Some(path),
seen: std::sync::Mutex::new(seen),
bindings: None,
})
}
/// An empty list: no authority is offered until one is configured.
pub fn empty() -> Self {
AuthorityList {
current: RwLock::new(Arc::new(Vec::new())),
source: None,
seen: std::sync::Mutex::new(None),
bindings: None,
}
}
/// Take bindings from `source`, per app. Without one no authority that
/// needs a binding is usable.
pub fn with_binding_source(mut self, source: Arc<dyn BindingSource>) -> Self {
self.bindings = Some(source);
self
}
/// Read the file again if it changed. A bad file changes nothing.
/// Returns whether the list was replaced.
pub fn reload(&self) -> Result<bool, ListError> {
let Some(path) = &self.source else {
return Ok(false);
};
let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok();
{
let mut seen = self.seen.lock().unwrap_or_else(|p| p.into_inner());
if *seen == modified && modified.is_some() {
return Ok(false);
}
*seen = modified;
}
let list = parse(&std::fs::read_to_string(path)?)?;
*self.current.write().unwrap_or_else(|p| p.into_inner()) = Arc::new(list);
Ok(true)
}
/// The list for this app, in order.
pub fn for_app(&self, name: &Name) -> Vec<Authority> {
let list = Arc::clone(&self.current.read().unwrap_or_else(|p| p.into_inner()));
list.iter()
.map(|a| {
let binding = if a.needs_binding {
self.bindings
.as_ref()
.and_then(|b| b.binding_for(&a.id, name))
} else {
None
};
Authority {
id: a.id.clone(),
directory: a.directory.clone(),
needs_binding: a.needs_binding,
usable: !a.needs_binding || binding.is_some(),
binding,
}
})
.collect()
}
/// The CAA issuer domains of the listed authorities, in order, each
/// once: what the zone's CAA record permits to issue.
pub fn caa_issuers(&self) -> Vec<String> {
let list = Arc::clone(&self.current.read().unwrap_or_else(|p| p.into_inner()));
let mut out: Vec<String> = Vec::new();
for a in list.iter() {
if !out.contains(&a.caa_domain) {
out.push(a.caa_domain.clone());
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
const TWO: &str = r#"
[[authority]]
id = "letsencrypt"
directory = "https://acme-v02.api.letsencrypt.org/directory"
caa_domain = "letsencrypt.org"
[[authority]]
id = "zerossl"
directory = "https://acme.zerossl.com/v2/DV90"
caa_domain = "sectigo.com"
needs_binding = true
"#;
fn name() -> Name {
Name::parse("ledger-accrual-tally-mint").unwrap()
}
struct PerApp;
impl BindingSource for PerApp {
fn binding_for(&self, id: &str, name: &Name) -> Option<Binding> {
Some(Binding {
kid: format!("{id}-{name}"),
hmac_key: "x".into(),
})
}
}
#[test]
fn the_list_is_served_in_order_and_a_binding_comes_only_from_a_source() {
let l = AuthorityList::from_toml(TWO).unwrap();
let got = l.for_app(&name());
assert_eq!(got.len(), 2);
assert_eq!(got[0].id, "letsencrypt");
assert!(!got[0].needs_binding && got[0].binding.is_none() && got[0].usable);
assert_eq!(got[1].id, "zerossl");
// No source: listed, needs one, served without, and not usable yet.
assert!(got[1].needs_binding && got[1].binding.is_none() && !got[1].usable);
let l = l.with_binding_source(Arc::new(PerApp));
let got = l.for_app(&name());
assert!(got[1].usable);
assert_eq!(
got[1].binding,
Some(Binding {
kid: "zerossl-ledger-accrual-tally-mint".into(),
hmac_key: "x".into()
})
);
assert!(got[0].binding.is_none());
}
#[test]
fn a_list_file_that_carries_a_binding_secret_is_refused_in_words() {
for secret in [
"binding_kid = 'k'\nbinding_hmac_key = 'a2V5'\n",
"binding_kid = 'k'\n",
"binding_hmac_key = 'a2V5'\n",
] {
let text = format!(
"[[authority]]\nid='z'\ndirectory='https://x/d'\ncaa_domain='x.example'\nneeds_binding=true\n{secret}"
);
let err = AuthorityList::from_toml(&text).err().expect("refused");
let said = err.to_string();
assert!(
said.contains("binding secret") && said.contains("per-app binding source"),
"{said}"
);
}
}
#[test]
fn a_bad_list_is_refused() {
for bad in [
"",
"[[authority]]\nid='a'\ndirectory='http://example.com/dir'\ncaa_domain='x.example'\n",
// no caa_domain, and a caa_domain that is not a plain domain name
"[[authority]]\nid='a'\ndirectory='https://x/d'\n",
"[[authority]]\nid='a'\ndirectory='https://x/d'\ncaa_domain='x.example; accounturi=y'\n",
"[[authority]]\nid='a'\ndirectory='https://x/d'\ncaa_domain='Example.COM'\n",
"[[authority]]\nid='a'\ndirectory='https://x/d'\ncaa_domain='localhost'\n",
"[[authority]]\nid='a'\ndirectory='https://x/d'\ncaa_domain='x.example'\n[[authority]]\nid='a'\ndirectory='https://y/d'\ncaa_domain='y.example'\n",
"[[authority]]\nid='a'\ndirectory='https://x/d'\ncaa_domain='x.example'\nsurprise=1\n",
] {
assert!(AuthorityList::from_toml(bad).is_err(), "{bad:?}");
}
let many: String = (0..17)
.map(|i| {
format!(
"[[authority]]\nid='a{i}'\ndirectory='https://x/d'\ncaa_domain='x.example'\n"
)
})
.collect();
assert!(AuthorityList::from_toml(&many).is_err());
}
#[test]
fn an_edit_changes_what_is_served_and_a_bad_edit_does_not() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorities.toml");
std::fs::write(&path, TWO).unwrap();
let l = AuthorityList::from_file(path.clone()).unwrap();
assert_eq!(l.for_app(&name())[0].id, "letsencrypt");
assert_eq!(l.caa_issuers(), ["letsencrypt.org", "sectigo.com"]);
let flipped = "[[authority]]\nid='zerossl'\ndirectory='https://acme.zerossl.com/v2/DV90'\ncaa_domain='sectigo.com'\nneeds_binding=true\n[[authority]]\nid='letsencrypt'\ndirectory='https://acme-v02.api.letsencrypt.org/directory'\ncaa_domain='letsencrypt.org'\n";
std::fs::write(&path, flipped).unwrap();
// Same-second edits may not move the mtime: force it to look new.
*l.seen.lock().unwrap() = None;
assert!(l.reload().unwrap());
assert_eq!(l.for_app(&name())[0].id, "zerossl");
assert_eq!(l.caa_issuers(), ["sectigo.com", "letsencrypt.org"]);
std::fs::write(&path, "not toml {{{").unwrap();
*l.seen.lock().unwrap() = None;
assert!(l.reload().is_err());
assert_eq!(l.for_app(&name())[0].id, "zerossl", "the good list stands");
// A file that gains a binding secret is a bad file too.
let secret = format!("{flipped}binding_kid='k'\nbinding_hmac_key='a2V5'\n");
std::fs::write(&path, secret).unwrap();
*l.seen.lock().unwrap() = None;
assert!(l.reload().is_err());
assert_eq!(l.for_app(&name())[0].id, "zerossl", "the good list stands");
}
#[test]
fn a_binding_source_is_asked_only_for_authorities_that_need_one() {
let l = AuthorityList::from_toml(TWO)
.unwrap()
.with_binding_source(Arc::new(PerApp));
let got = l.for_app(&name());
assert!(got[0].binding.is_none(), "letsencrypt needs none");
assert!(got[1].binding.is_some());
}
#[test]
fn two_authorities_with_one_issuer_name_it_once() {
let text = "[[authority]]\nid='a'\ndirectory='https://x/d'\ncaa_domain='x.example'\n[[authority]]\nid='b'\ndirectory='https://y/d'\ncaa_domain='x.example'\n";
assert_eq!(
AuthorityList::from_toml(text).unwrap().caa_issuers(),
["x.example"]
);
assert!(AuthorityList::empty().caa_issuers().is_empty());
}
}
+290
View File
@@ -0,0 +1,290 @@
//! The app's side of the line: dial out, prove the name, hold the line.
//!
//! This is the client the tests use, and the part of the protocol the
//! desktop app (unit B3) builds on. It does not do the app's policy:
//! when to dial, when to renew, what to do with a caller.
//!
//! ```text
//! GOAL: connect to the relay, prove the key for a name for this session
//! only, and hand the app each caller with the caller's address.
//! SOURCE: WB-relay-2 (the line and its proof), WB-relay-6 (the caller's
//! address).
//! INVARIANTS:
//! 1. The proof signs this session's TLS exporter and the relay's fresh
//! nonce: it cannot be reused in another session.
//! 2. A caller stream is handed on only after its address header
//! parsed; a stream with a bad header is dropped.
//! 3. Pending headers are bounded in number and in time.
//! SCENARIOS:
//! 1. `connect` with a new name and `claim = true` gives a line with
//! `verdict.claimed`; a second connect with `claim = false` and the
//! same key gives a line, and with another key is refused.
//! ```
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use rustls::ClientConfig;
use rustls::pki_types::ServerName;
use tokio::net::TcpStream;
use tokio::sync::{Semaphore, mpsc};
use tokio::task::JoinHandle;
use tokio::time::timeout;
use tokio_rustls::TlsConnector;
use tokio_util::compat::TokioAsyncReadCompatExt;
use crate::mux::{self, Mux, MuxLimits, Stream};
use crate::names::Name;
use crate::proto::{
self, AppKey, Authority, Caller, Challenge, EXPORTER_LABEL, Hello, Refusal, Request, Response,
VERSION, Verdict, read_frame, write_frame,
};
/// Why a line could not be made, or a request failed.
#[derive(Debug, thiserror::Error)]
pub enum ClientError {
/// The network or TLS failed.
#[error("i/o: {0}")]
Io(#[from] io::Error),
/// A message was malformed or too long.
#[error("protocol: {0}")]
Frame(#[from] proto::FrameError),
/// The relay said no.
#[error("the relay refused the line: {0:?}")]
Refused(Refusal),
/// The relay did not answer in time.
#[error("timed out")]
Timeout,
/// The line is closed.
#[error("the line is closed")]
Closed,
}
/// A caller handed to the app.
pub struct Incoming {
/// Who the caller is, as the relay saw them.
pub caller: Caller,
/// The caller's bytes: their TLS ClientHello first.
pub stream: Stream,
}
/// Options for a line.
#[derive(Debug, Clone, Copy)]
pub struct LineOptions {
/// Streams at once on the line. At least the relay's `streams_per_app`
/// plus `control_streams_per_app` plus 4, or the relay's opens are
/// refused.
pub max_streams: usize,
/// How long a caller stream may take to send its address header.
pub header_timeout: Duration,
/// How long a request waits for its answer.
pub request_timeout: Duration,
}
impl Default for LineOptions {
fn default() -> Self {
LineOptions {
max_streams: 64,
header_timeout: Duration::from_secs(5),
request_timeout: Duration::from_secs(10),
}
}
}
/// An app's open line.
pub struct Line {
/// The relay's verdict: claimed or not, and the stream limit.
pub verdict: Verdict,
handle: LineHandle,
incoming: mpsc::Receiver<Incoming>,
task: JoinHandle<()>,
}
/// TLS to the relay, as `server_name` (the relay's host).
pub async fn tls_connect(
addr: SocketAddr,
tls: Arc<ClientConfig>,
server_name: &str,
) -> io::Result<tokio_rustls::client::TlsStream<TcpStream>> {
let tcp = TcpStream::connect(addr).await?;
tcp.set_nodelay(true)?;
let name = ServerName::try_from(server_name.to_owned())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
TlsConnector::from(tls).connect(name, tcp).await
}
/// This TLS session's exporter value, the thing a proof is bound to.
pub fn session_exporter(tls: &tokio_rustls::client::TlsStream<TcpStream>) -> io::Result<[u8; 32]> {
let mut out = [0u8; 32];
tls.get_ref()
.1
.export_keying_material(&mut out[..], EXPORTER_LABEL, None)
.map_err(|e| io::Error::other(e.to_string()))?;
Ok(out)
}
/// The hello for a session: the name, the key, and the signature.
pub fn make_hello(
key: &AppKey,
name: &Name,
claim: bool,
exporter: &[u8; 32],
nonce: &[u8; 32],
) -> Hello {
Hello {
v: VERSION,
name: name.to_string(),
public_key: proto::hex(&key.public_key()),
claim,
signature: proto::hex(&key.sign(&proto::proof_message(exporter, nonce, name, claim))),
}
}
/// Dial the relay and bring up the line for `name`. `claim` is true only
/// the first time, to take the name.
pub async fn connect(
addr: SocketAddr,
tls: Arc<ClientConfig>,
server_name: &str,
name: Name,
key: &AppKey,
claim: bool,
opts: LineOptions,
) -> Result<Line, ClientError> {
let mut stream = timeout(opts.request_timeout, tls_connect(addr, tls, server_name))
.await
.map_err(|_| ClientError::Timeout)??;
let exporter = session_exporter(&stream)?;
let challenge: Challenge = timeout(opts.request_timeout, read_frame(&mut stream))
.await
.map_err(|_| ClientError::Timeout)??;
let nonce = proto::unhex::<32>(&challenge.nonce)
.ok_or_else(|| ClientError::Io(io::Error::new(io::ErrorKind::InvalidData, "bad nonce")))?;
let hello = make_hello(key, &name, claim, &exporter, &nonce);
write_frame(&mut stream, &hello).await?;
let verdict: Verdict = timeout(opts.request_timeout, read_frame(&mut stream))
.await
.map_err(|_| ClientError::Timeout)??;
if !verdict.ok {
return Err(ClientError::Refused(
verdict.refusal.unwrap_or(Refusal::BadRequest),
));
}
Ok(Line::up(stream, verdict, opts))
}
impl Line {
/// Start the multiplexer over a TLS stream that has passed the
/// handshake.
pub fn up(
stream: tokio_rustls::client::TlsStream<TcpStream>,
verdict: Verdict,
opts: LineOptions,
) -> Line {
let (tx, incoming) = mpsc::channel::<Incoming>(16);
let pending = Arc::new(Semaphore::new(64));
let header_timeout = opts.header_timeout;
let (mux, task) = mux::spawn(
stream.compat(),
yamux::Mode::Client,
MuxLimits {
max_streams: opts.max_streams,
idle: Duration::from_secs(3600 * 24 * 365),
},
None,
move |mut stream| {
let Ok(permit) = Arc::clone(&pending).try_acquire_owned() else {
return; // too many callers waiting to be read: drop
};
let tx = tx.clone();
tokio::spawn(async move {
let header = timeout(header_timeout, Caller::read(&mut stream)).await;
drop(permit);
if let Ok(Ok(caller)) = header {
let _ = tx.try_send(Incoming { caller, stream });
}
});
},
);
Line {
verdict,
handle: LineHandle { mux, opts },
incoming,
task,
}
}
/// The next caller, or `None` when the line has ended.
pub async fn accept(&mut self) -> Option<Incoming> {
self.incoming.recv().await
}
/// A clonable handle for requests and closing, for use beside
/// [`Line::accept`].
pub fn handle(&self) -> LineHandle {
self.handle.clone()
}
/// Close the line and wait for it.
pub async fn close(self) {
self.handle.mux.close();
let _ = self.task.await;
}
}
/// What can be done with a line besides taking callers: requests, and
/// closing. Clones share the line.
#[derive(Clone)]
pub struct LineHandle {
mux: Mux,
opts: LineOptions,
}
impl LineHandle {
/// One request on a stream of its own.
pub async fn request(&self, request: Request) -> Result<Response, ClientError> {
let wait = self.opts.request_timeout;
let mut stream = self.mux.open(wait).await.map_err(|_| ClientError::Closed)?;
timeout(wait, async {
write_frame(&mut stream, &request).await?;
let r: Response = read_frame(&mut stream).await?;
Ok::<_, ClientError>(r)
})
.await
.map_err(|_| ClientError::Timeout)?
}
/// Ask the relay to publish an ACME DNS-01 proof value for this
/// app's name.
pub async fn publish_txt(&self, value: &str) -> Result<Response, ClientError> {
self.request(Request::PublishTxt {
value: value.to_owned(),
})
.await
}
/// The certificate authorities to try, in order.
pub async fn authorities(&self) -> Result<Vec<Authority>, ClientError> {
let r = self.request(Request::Authorities).await?;
Ok(r.authorities.unwrap_or_default())
}
/// True once the line has ended.
pub fn is_closed(&self) -> bool {
self.mux.is_closed()
}
/// Ask the line to close.
pub fn close(&self) {
self.mux.close();
}
}
impl std::ops::Deref for Line {
type Target = LineHandle;
fn deref(&self) -> &LineHandle {
&self.handle
}
}
+299
View File
@@ -0,0 +1,299 @@
//! The relay's settings, and every limit it enforces.
//!
//! Every limit is a number here with a default and a reason; nothing in
//! the relay is unbounded. The defaults are sized for hundreds of
//! thousands of idle apps on one modest host.
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use std::path::PathBuf;
use std::time::Duration;
use serde::Deserialize;
/// A name server of the domain, and where it is.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NameServer {
/// Its host name (`ns1.wanderbooks.link`).
pub name: String,
/// Its IPv4 addresses.
#[serde(default)]
pub v4: Vec<Ipv4Addr>,
/// Its IPv6 addresses.
#[serde(default)]
pub v6: Vec<Ipv6Addr>,
}
/// Every limit and timeout. Times are in milliseconds.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Limits {
/// Apps connected at once. Admission stops here.
pub max_lines: usize,
/// Connections open at once, all kinds (hello stage, line handshake,
/// callers being spliced, apps' lines).
pub max_connections: usize,
/// Connections that have not yet sent a whole ClientHello.
pub max_pending_hellos: usize,
/// Of those, from one address (an IPv4 address, an IPv6 /64). Strict:
/// this is the slow-loris limit.
pub max_pending_per_ip: u32,
/// Of those, from one network (an IPv4 /24, an IPv6 /48).
pub max_pending_per_net: u32,
/// Hello places kept back for addresses that held a proven line
/// lately, used only when `max_pending_hellos` is full. The server
/// name is not known before the hello is read, so the reserve is for
/// who is calling, not for what is asked.
pub hello_reserve: usize,
/// Bits in each generation of the filter of addresses that held a
/// proven line (a power of two).
pub known_bits: usize,
/// An address that held a proven line counts as known for one to two
/// of these.
pub known_period_ms: u64,
/// Connections from one address, all stages. Generous: the AI vendors'
/// callers share a few addresses between all their users.
pub max_connections_per_ip: u32,
/// How long a peer has to send a whole ClientHello, from connecting.
pub hello_timeout_ms: u64,
/// Line handshakes (TLS and proof) in progress at once.
pub max_handshakes: usize,
/// Of those, from one address (an IPv4 address, an IPv6 /64), held
/// until the verdict.
pub max_handshakes_per_ip: u32,
/// Of those, from one network (an IPv4 /24, an IPv6 /48).
pub max_handshakes_per_net: u32,
/// How long a line's TLS handshake and proof may take in all.
pub handshake_timeout_ms: u64,
/// How long to wait for the app to open a stream for a caller.
pub open_stream_timeout_ms: u64,
/// Caller streams open on one app's line at once.
pub streams_per_app: u32,
/// Control streams (requests from the app) in progress at once, per line.
pub control_streams_per_app: u32,
/// The copy buffer, per direction, per spliced connection, in bytes.
pub copy_buffer: usize,
/// A spliced connection with no byte either way this long is closed.
pub stream_idle_ms: u64,
/// The slowest a spliced connection may take bytes, per second: a
/// write of `n` bytes must finish within `write_stall_ms` plus
/// `n` over this, or the connection is closed.
pub min_stream_bytes_per_sec: u32,
/// A spliced connection's longest life.
pub stream_max_age_ms: u64,
/// The grace on every write, before the rate above is asked for: a
/// slow reader is closed, not buffered for.
pub write_stall_ms: u64,
/// A line from which nothing has been read this long is dropped. The
/// app sends a keep-alive well inside this.
pub line_idle_ms: u64,
/// A control request, read to reply, must finish in this long.
pub control_timeout_ms: u64,
/// How long a published proof record lives.
pub txt_ttl_ms: u64,
/// Proof records held at most, over all apps.
pub txt_max_entries: usize,
/// Values one name may hold at once (the wildcard and the apex).
pub txt_per_name: usize,
/// Publishes one name may make in an hour.
pub txt_publishes_per_hour: u32,
/// New names that may be claimed in one window, over all apps: a
/// safety ceiling on the registry, far above real use. It is not the
/// certificate authority's budget (see `cert_publishes_per_window`).
pub claims_per_window: u32,
/// The window for `claims_per_window`.
pub claim_window_ms: u64,
/// New names one address (an IPv4 address, an IPv6 /64) may claim in
/// `claim_ip_window_ms`.
pub claims_per_ip: u32,
/// New names one network (an IPv4 /24, an IPv6 /48) may claim in the
/// same window.
pub claims_per_net: u32,
/// The window for `claims_per_ip` and `claims_per_net`.
pub claim_ip_window_ms: u64,
/// Names that may first publish a proof record in one window, over all
/// apps: the certificate authority's new-certificate limit (50 a
/// week). A name is charged once, the first time it publishes; a
/// renewal is not a new name and is not charged.
pub cert_publishes_per_window: u32,
/// The window for the certificate budget: a week.
pub cert_window_ms: u64,
/// First publishes one address (an IPv4 address, an IPv6 /64) may
/// make in `cert_window_ms`.
pub cert_publishes_per_ip: u32,
/// First publishes one network (an IPv4 /24, an IPv6 /48) may make in
/// the same window.
pub cert_publishes_per_net: u32,
/// How often the running relay asks the registry which names are
/// blocked and closes their lines: a block takes effect within this.
pub block_check_ms: u64,
/// Registry requests queued at most; past this the relay says busy.
pub registry_queue: usize,
/// Slots in each fixed per-address table (a power of two).
pub ip_slots: usize,
/// DNS queries per second one address may send, sustained. Past it a
/// query is answered "truncated", which sends a real resolver to TCP.
pub dns_qps_per_ip: u32,
/// DNS queries per second answered over UDP in all: past it a query
/// gets no answer at all.
pub dns_qps_global: u32,
/// TCP DNS connections open at once.
pub dns_tcp_max: usize,
/// TCP DNS connections from one address.
pub dns_tcp_per_ip: u32,
/// A TCP DNS connection's wait for its next query.
pub dns_tcp_timeout_ms: u64,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_lines: 500_000,
max_connections: 1_000_000,
max_pending_hellos: 4_096,
max_pending_per_ip: 32,
max_pending_per_net: 256,
hello_reserve: 512,
known_bits: 1 << 23,
known_period_ms: 12 * 3_600_000,
max_connections_per_ip: 20_000,
hello_timeout_ms: 8_000,
max_handshakes: 1_024,
max_handshakes_per_ip: 4,
max_handshakes_per_net: 64,
handshake_timeout_ms: 10_000,
open_stream_timeout_ms: 5_000,
streams_per_app: 8,
control_streams_per_app: 2,
copy_buffer: 8 * 1024,
stream_idle_ms: 10 * 60_000,
stream_max_age_ms: 6 * 3_600_000,
min_stream_bytes_per_sec: 2_048,
write_stall_ms: 5_000,
line_idle_ms: 180_000,
control_timeout_ms: 10_000,
txt_ttl_ms: 10 * 60_000,
txt_max_entries: 100_000,
txt_per_name: 4,
txt_publishes_per_hour: 12,
claims_per_window: 5_000,
claim_window_ms: 24 * 3_600_000,
claims_per_ip: 5,
claims_per_net: 20,
claim_ip_window_ms: 24 * 3_600_000,
cert_publishes_per_window: 50,
cert_window_ms: 7 * 24 * 3_600_000,
cert_publishes_per_ip: 3,
cert_publishes_per_net: 10,
block_check_ms: 10_000,
registry_queue: 256,
ip_slots: 1 << 16,
dns_qps_per_ip: 20,
dns_qps_global: 5_000,
dns_tcp_max: 512,
dns_tcp_per_ip: 8,
dns_tcp_timeout_ms: 5_000,
}
}
}
macro_rules! durations {
($($name:ident => $field:ident),* $(,)?) => {
impl Limits {
$(
#[doc = concat!("`", stringify!($field), "` as a duration.")]
pub fn $name(&self) -> Duration { Duration::from_millis(self.$field) }
)*
}
};
}
durations! {
hello_timeout => hello_timeout_ms,
handshake_timeout => handshake_timeout_ms,
open_stream_timeout => open_stream_timeout_ms,
stream_idle => stream_idle_ms,
stream_max_age => stream_max_age_ms,
write_stall => write_stall_ms,
line_idle => line_idle_ms,
control_timeout => control_timeout_ms,
txt_ttl => txt_ttl_ms,
claim_window => claim_window_ms,
claim_ip_window => claim_ip_window_ms,
cert_window => cert_window_ms,
known_period => known_period_ms,
block_check => block_check_ms,
dns_tcp_timeout => dns_tcp_timeout_ms,
}
/// The relay's configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
/// The domain the relay serves (`wanderbooks.link`).
pub domain: String,
/// The host an app's line dials (`relay.wanderbooks.link`).
pub relay_host: String,
/// Where the router listens (443 in production).
pub router_addr: SocketAddr,
/// Where DNS listens, UDP and TCP (53 in production).
pub dns_addr: SocketAddr,
/// The registry's file: the one durable table (D-85).
pub registry_path: PathBuf,
/// The relay's own certificate chain, PEM, for `relay_host`.
pub tls_cert: PathBuf,
/// Its private key, PEM.
pub tls_key: PathBuf,
/// The certificate authorities, served to apps; read again when it
/// changes. See [`crate::authorities`].
pub authorities_path: Option<PathBuf>,
/// IPv4 addresses every name under the domain points at.
pub address_v4: Vec<Ipv4Addr>,
/// IPv6 addresses every name under the domain points at.
pub address_v6: Vec<Ipv6Addr>,
/// The domain's name servers, at least two in production.
pub nameservers: Vec<NameServer>,
/// Limits and timeouts.
pub limits: Limits,
}
impl Default for Config {
fn default() -> Self {
Config {
domain: "wanderbooks.link".into(),
relay_host: "relay.wanderbooks.link".into(),
router_addr: SocketAddr::from(([0, 0, 0, 0], 443)),
dns_addr: SocketAddr::from(([0, 0, 0, 0], 53)),
registry_path: PathBuf::from("registry.sqlite3"),
tls_cert: PathBuf::from("relay-cert.pem"),
tls_key: PathBuf::from("relay-key.pem"),
authorities_path: None,
address_v4: Vec::new(),
address_v6: Vec::new(),
nameservers: Vec::new(),
limits: Limits::default(),
}
}
}
impl Config {
/// Read a TOML configuration.
pub fn from_toml(text: &str) -> Result<Self, toml::de::Error> {
toml::from_str(text)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_load_and_unknown_keys_are_refused() {
let c = Config::from_toml("").expect("empty is the defaults");
assert_eq!(c.limits.streams_per_app, 8);
let c = Config::from_toml("[limits]\nstreams_per_app = 4\n").unwrap();
assert_eq!(c.limits.streams_per_app, 4);
assert!(Config::from_toml("bogus = 1").is_err());
assert!(Config::from_toml("[limits]\nbogus = 1").is_err());
}
}
+809
View File
@@ -0,0 +1,809 @@
//! The domain's authoritative DNS server.
//!
//! The relay answers for `wanderbooks.link` itself, over UDP and TCP.
//! It answers three questions and refuses the rest:
//!
//! - any name under the domain is at the relay's address (A, AAAA), the
//! name servers at their own;
//! - `TXT _acme-challenge.<four-words>.<domain>` is the proof value that
//! app just handed in, held in memory for minutes;
//! - `CAA` at the apex (which a certificate authority finds by climbing
//! from any name below it, RFC 8659) permits the listed authorities to
//! issue, by the DNS-01 method only (RFC 8657), derived from the
//! authority list so swapping one is a data change.
//!
//! Nothing is stored per user: the answers are made, not looked up, so a
//! catch-all that stops covering names under a label of its own (RFC 4592)
//! is not a risk here: every name below the zone is answered the same way
//! whatever else exists beneath it.
//!
//! ```text
//! GOAL: be the domain's DNS: point every name at the relay, publish an
//! app's proof record and nobody else's, and be no use to someone
//! who wants a resolver, an amplifier, or a way to make the relay
//! hold memory.
//! SOURCE: WB-relay-5 (the proof records and the domain's DNS), RFC 1035,
//! RFC 4592 (wildcards), RFC 6891 (EDNS), RFC 8482 (ANY).
//! INVARIANTS:
//! 1. A query outside the zone is refused; recursion is never offered.
//! 2. Every name under the zone has A and AAAA answers at the relay's
//! addresses, including names beneath a label that has a TXT record.
//! 3. A TXT answer exists only at `_acme-challenge.<name>` for a name
//! with a live published value, and holds only those values.
//! 4. A UDP answer never exceeds the client's stated size (512 without
//! EDNS, at most 1 232 with it); an oversized one is truncated
//! (TC) and the client retries over TCP.
//! 5. The server holds no per-query state: the UDP loop answers inline
//! from fixed tables, and TCP is capped in connections, in queries
//! per connection and in time.
//! 6. Per address (an IPv4 address, an IPv6 /64; a mapped IPv4 address
//! is its IPv4 address), UDP queries are rate limited from a fixed
//! table; one over its rate is answered "truncated" with no data,
//! which sends a real resolver to TCP and sends a spoofed source
//! nothing larger than its query. All UDP answers together are
//! limited by a global rate; past it, silence.
//! 7. The CAA answer at the apex lists exactly the authority list's
//! issuer domains, each with `validationmethods=dns-01`; with no
//! authority listed there is no CAA record.
//! SCENARIOS:
//! 1. A for `x.<secret>.<name>.<domain>` is the relay's address, with
//! and without a TXT record published for that name.
//! 2. TXT for `_acme-challenge.<name>` returns the published value, and
//! returns nothing after the value expires.
//! 3. A for `example.com` is REFUSED; ANY is answered with no data.
//! 4. A hundred queries in a burst from one address: the excess is
//! answered truncated, not dropped.
//! 5. CAA for the apex is `issue "letsencrypt.org;
//! validationmethods=dns-01"` for a list of one authority, and follows
//! the list when it is edited.
//! ```
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use std::time::Instant;
use hickory_proto::op::{Edns, Message, MessageType, OpCode, ResponseCode};
use hickory_proto::rr::rdata::caa::{CAA, KeyValue};
use hickory_proto::rr::rdata::{A, AAAA, NS, SOA, TXT};
use hickory_proto::rr::{DNSClass, Name as DnsName, RData, Record, RecordType};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, UdpSocket};
use tokio::sync::Semaphore;
use tokio_util::sync::CancellationToken;
use crate::authorities::AuthorityList;
use crate::config::Config;
use crate::gate::{IpGate, RateTable, TokenBucket};
use crate::names::{Name, Zone};
use crate::txt::TxtStore;
const TTL_ADDR: u32 = 300;
const TTL_APEX: u32 = 3600;
const TTL_TXT: u32 = 5;
const TTL_NEGATIVE: u32 = 60;
/// The biggest UDP answer ever sent, whatever the client asks for.
const UDP_MAX: usize = 1232;
/// The biggest query read, over either transport.
const QUERY_MAX: usize = 1232;
/// The DNS service: pure, no sockets. Feed it a query, get the answer.
pub struct DnsService {
zone: Zone,
domain: DnsName,
v4: Vec<Ipv4Addr>,
v6: Vec<Ipv6Addr>,
nameservers: Vec<(String, DnsName, Vec<IpAddr>)>,
txt: Arc<TxtStore>,
authorities: Arc<AuthorityList>,
}
impl DnsService {
/// A service for the configured domain. `authorities` is the list the
/// zone's CAA record is made from, read at each query.
pub fn new(
zone: Zone,
cfg: &Config,
txt: Arc<TxtStore>,
authorities: Arc<AuthorityList>,
) -> Result<Self, String> {
let domain =
DnsName::from_ascii(format!("{}.", zone.domain())).map_err(|e| e.to_string())?;
let mut nameservers = Vec::new();
for ns in &cfg.nameservers {
let name = DnsName::from_ascii(format!("{}.", ns.name.trim_end_matches('.')))
.map_err(|e| e.to_string())?;
let ips = ns
.v4
.iter()
.map(|a| IpAddr::V4(*a))
.chain(ns.v6.iter().map(|a| IpAddr::V6(*a)))
.collect();
nameservers.push((
ns.name.trim_end_matches('.').to_ascii_lowercase(),
name,
ips,
));
}
Ok(DnsService {
zone,
domain,
v4: cfg.address_v4.clone(),
v6: cfg.address_v6.clone(),
nameservers,
txt,
authorities,
})
}
/// The CAA record set of the apex: one `issue` per listed authority,
/// DNS-01 only (RFC 8657).
fn caa(&self) -> Vec<Record> {
self.authorities
.caa_issuers()
.iter()
.filter_map(|issuer| {
let issuer = DnsName::from_ascii(issuer).ok()?;
let data = CAA::new_issue(
false,
Some(issuer),
vec![KeyValue::new("validationmethods", "dns-01")],
);
Some(Record::from_rdata(
self.domain.clone(),
TTL_ADDR,
RData::CAA(data),
))
})
.collect()
}
/// The answer to give a sender over its rate: the question, the
/// truncation bit, and nothing else, so a real resolver retries over
/// TCP and a spoofed source is sent no more than it sent. `None` for
/// anything that is not a plain query.
pub fn truncated(&self, wire: &[u8]) -> Option<Vec<u8>> {
if wire.len() > QUERY_MAX {
return None;
}
let query = Message::from_vec(wire).ok()?;
if query.metadata.message_type == MessageType::Response
|| query.metadata.op_code != OpCode::Query
{
return None;
}
let [q] = query.queries.as_slice() else {
return None;
};
let mut resp = Message::response(query.metadata.id, OpCode::Query);
resp.metadata.truncation = true;
resp.metadata.recursion_desired = query.metadata.recursion_desired;
resp.queries.push(q.clone());
resp.to_vec().ok()
}
fn soa(&self) -> Record {
let mname = self
.nameservers
.first()
.map(|(_, n, _)| n.clone())
.unwrap_or_else(|| {
DnsName::from_ascii(format!("ns1.{}", self.domain))
.unwrap_or_else(|_| self.domain.clone())
});
let rname = DnsName::from_ascii(format!("hostmaster.{}", self.domain))
.unwrap_or_else(|_| self.domain.clone());
Record::from_rdata(
self.domain.clone(),
TTL_APEX,
RData::SOA(SOA::new(mname, rname, 1, 3600, 600, 86_400, TTL_NEGATIVE)),
)
}
fn addresses(&self, owner: &DnsName, text: &str, want_v6: bool) -> Vec<Record> {
if let Some((_, _, ips)) = self.nameservers.iter().find(|(n, _, _)| n == text) {
return ips
.iter()
.filter_map(|ip| match (ip, want_v6) {
(IpAddr::V4(a), false) => Some(RData::A(A::from(*a))),
(IpAddr::V6(a), true) => Some(RData::AAAA(AAAA::from(*a))),
_ => None,
})
.map(|d| Record::from_rdata(owner.clone(), TTL_ADDR, d))
.collect();
}
if want_v6 {
self.v6
.iter()
.map(|a| Record::from_rdata(owner.clone(), TTL_ADDR, RData::AAAA(AAAA::from(*a))))
.collect()
} else {
self.v4
.iter()
.map(|a| Record::from_rdata(owner.clone(), TTL_ADDR, RData::A(A::from(*a))))
.collect()
}
}
/// The answer to a query message, or `None` to say nothing at all (a
/// response, or too little to answer). `udp` limits the size.
pub fn answer(&self, wire: &[u8], udp: bool, now: Instant) -> Option<Vec<u8>> {
if wire.len() > QUERY_MAX {
return None;
}
let query = match Message::from_vec(wire) {
Ok(m) => m,
Err(_) => {
// Too short to have an id: nothing to answer. A response
// (QR set) is never answered, so no two servers can loop.
let id = wire.get(..2).map(|b| u16::from_be_bytes([b[0], b[1]]))?;
if wire.get(2).is_none_or(|b| b & 0x80 != 0) {
return None;
}
return Message::error_msg(id, OpCode::Query, ResponseCode::FormErr)
.to_vec()
.ok();
}
};
if query.metadata.message_type == MessageType::Response {
return None;
}
let id = query.metadata.id;
let reply = |code| {
Message::error_msg(id, query.metadata.op_code, code)
.to_vec()
.ok()
};
if query.metadata.op_code != OpCode::Query {
return reply(ResponseCode::NotImp);
}
let [q] = query.queries.as_slice() else {
return reply(ResponseCode::FormErr);
};
if q.query_class() != DNSClass::IN {
return reply(ResponseCode::Refused);
}
let qname = q.name().to_ascii();
let lower = qname.trim_end_matches('.').to_ascii_lowercase();
let Some(labels) = self.zone.below(&lower) else {
return reply(ResponseCode::Refused);
};
let mut resp = Message::response(id, OpCode::Query);
resp.metadata.authoritative = true;
resp.metadata.recursion_desired = query.metadata.recursion_desired;
resp.queries.push(q.clone());
if let Some(e) = &query.edns {
let mut edns = Edns::new();
edns.set_max_payload(u16::try_from(UDP_MAX).unwrap_or(1232));
edns.set_version(0);
resp.edns = Some(edns);
let _ = e;
}
let owner = q.name().clone();
let apex = labels.is_empty();
match q.query_type() {
RecordType::A => resp.answers = self.addresses(&owner, &lower, false),
RecordType::AAAA => resp.answers = self.addresses(&owner, &lower, true),
RecordType::SOA if apex => resp.answers.push(self.soa()),
RecordType::NS if apex => {
for (_, ns, ips) in &self.nameservers {
resp.answers.push(Record::from_rdata(
owner.clone(),
TTL_APEX,
RData::NS(NS(ns.clone())),
));
for ip in ips {
let data = match ip {
IpAddr::V4(a) => RData::A(A::from(*a)),
IpAddr::V6(a) => RData::AAAA(AAAA::from(*a)),
};
resp.additionals
.push(Record::from_rdata(ns.clone(), TTL_ADDR, data));
}
}
}
RecordType::CAA if apex => resp.answers = self.caa(),
RecordType::TXT => {
if let ["_acme-challenge", name] = labels.as_slice()
&& let Ok(name) = Name::parse(&name.to_ascii_lowercase())
{
for v in self.txt.get(&name, now) {
resp.answers.push(Record::from_rdata(
owner.clone(),
TTL_TXT,
RData::TXT(TXT::new(vec![v])),
));
}
}
}
// ANY (RFC 8482), and every type the relay has nothing of: no
// data, which is not a refusal and not a missing name.
_ => {}
}
if resp.answers.is_empty() {
resp.authorities.push(self.soa());
}
let mut bytes = resp.to_vec().ok()?;
if udp {
let limit = query
.edns
.as_ref()
.map_or(512, |e| usize::from(e.max_payload()).clamp(512, UDP_MAX));
if bytes.len() > limit {
resp.metadata.truncation = true;
resp.answers.clear();
resp.authorities.clear();
resp.additionals.clear();
bytes = resp.to_vec().ok()?;
}
}
Some(bytes)
}
}
/// Serve UDP until cancelled. Answers are made inline, with no task per
/// query. Past `global_qps` in all a query gets no answer; a sender over
/// its own rate gets the truncated answer, which a real resolver follows
/// over TCP.
pub async fn serve_udp(
socket: Arc<UdpSocket>,
svc: Arc<DnsService>,
qps: u32,
global_qps: u32,
slots: usize,
cancel: CancellationToken,
) {
let mut rate = RateTable::new(slots, qps, qps.saturating_mul(2).max(1));
let mut global = TokenBucket::new(
global_qps,
global_qps.saturating_mul(2).max(1),
Instant::now(),
);
let mut buf = vec![0u8; QUERY_MAX + 1];
loop {
let (n, from) = tokio::select! {
() = cancel.cancelled() => return,
r = socket.recv_from(&mut buf) => match r {
Ok(x) => x,
// On Windows a UDP socket reports an ICMP "port unreachable"
// for an earlier answer as a reset on the next receive. It
// is about one peer's packet, not about the socket: go on at
// once, as a sleep here would let such packets throttle
// everyone.
Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => continue,
Err(_) => {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
continue;
}
},
};
let now = Instant::now();
if !global.allow(now) {
continue;
}
if !rate.allow(from.ip(), now) {
if let Some(out) = svc.truncated(&buf[..n]) {
let _ = socket.try_send_to(&out, from);
}
continue;
}
if let Some(out) = svc.answer(&buf[..n], true, now) {
// A full send buffer drops the answer: a client retries.
let _ = socket.try_send_to(&out, from);
}
}
}
/// The limits of the TCP side.
#[derive(Debug, Clone, Copy)]
pub struct TcpLimits {
/// Connections at once.
pub max: usize,
/// Connections at once from one address.
pub per_ip: u32,
/// The wait for each query, and for the rest of one that began.
pub timeout: std::time::Duration,
/// Queries answered on one connection.
pub queries: u32,
}
/// Serve TCP until cancelled.
pub async fn serve_tcp(
listener: TcpListener,
svc: Arc<DnsService>,
limits: TcpLimits,
slots: usize,
cancel: CancellationToken,
) {
let permits = Arc::new(Semaphore::new(limits.max));
let gate = IpGate::new(slots, limits.per_ip);
loop {
let (mut stream, from) = tokio::select! {
() = cancel.cancelled() => return,
r = listener.accept() => match r {
Ok(x) => x,
Err(_) => {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
continue;
}
},
};
let (Ok(permit), Some(ip_permit)) = (
Arc::clone(&permits).try_acquire_owned(),
gate.acquire(from.ip()),
) else {
continue; // over the limit: close it
};
let svc = Arc::clone(&svc);
tokio::spawn(async move {
let _held = (permit, ip_permit);
for _ in 0..limits.queries {
let mut len = [0u8; 2];
let read = async {
stream.read_exact(&mut len).await?;
let n = usize::from(u16::from_be_bytes(len));
if n == 0 || n > QUERY_MAX {
return Err(std::io::ErrorKind::InvalidData.into());
}
let mut body = vec![0u8; n];
stream.read_exact(&mut body).await?;
Ok::<_, std::io::Error>(body)
};
let Ok(Ok(body)) = tokio::time::timeout(limits.timeout, read).await else {
return;
};
let Some(out) = svc.answer(&body, false, Instant::now()) else {
return;
};
let Ok(n) = u16::try_from(out.len()) else {
return;
};
let mut framed = n.to_be_bytes().to_vec();
framed.extend(out);
if tokio::time::timeout(limits.timeout, stream.write_all(&framed))
.await
.is_err()
{
return;
}
}
});
}
}
/// A socket address for tests and the binary: where DNS is listening.
pub fn bound(addr: SocketAddr) -> SocketAddr {
addr
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use hickory_proto::op::Query;
use super::*;
fn svc() -> (DnsService, Arc<TxtStore>) {
let cfg = Config {
address_v4: vec!["198.51.100.7".parse().unwrap()],
address_v6: vec!["2001:db8::7".parse().unwrap()],
nameservers: vec![
crate::config::NameServer {
name: "ns1.wanderbooks.link".into(),
v4: vec!["198.51.100.53".parse().unwrap()],
v6: vec![],
},
crate::config::NameServer {
name: "ns2.wanderbooks.link".into(),
v4: vec!["203.0.113.53".parse().unwrap()],
v6: vec![],
},
],
..Config::default()
};
let txt = Arc::new(TxtStore::new(Duration::from_secs(60), 100, 4, 100));
let zone = Zone::new(&cfg.domain, &cfg.relay_host);
let list = AuthorityList::from_toml(
"[[authority]]\nid='letsencrypt'\ndirectory='https://acme-v02.api.letsencrypt.org/directory'\ncaa_domain='letsencrypt.org'\n",
)
.unwrap();
(
DnsService::new(zone, &cfg, Arc::clone(&txt), Arc::new(list)).unwrap(),
txt,
)
}
fn ask(svc: &DnsService, name: &str, ty: RecordType, udp: bool) -> Message {
let mut m = Message::query();
m.queries
.push(Query::query(DnsName::from_ascii(name).unwrap(), ty));
let out = svc
.answer(&m.to_vec().unwrap(), udp, Instant::now())
.expect("an answer");
Message::from_vec(&out).unwrap()
}
const APP: &str = "ledger-accrual-tally-mint.wanderbooks.link.";
const SECRET: &str = "k3j9x0q7m2z8c5v1b4n6a9s2d";
const PROOF: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ";
#[test]
fn every_name_under_the_zone_is_at_the_relay_even_beneath_a_label_with_a_record() {
let (svc, txt) = svc();
let deep = format!("{SECRET}.{APP}");
for publish in [false, true] {
if publish {
txt.publish(
Name::parse("ledger-accrual-tally-mint").unwrap(),
PROOF,
Instant::now(),
)
.unwrap();
}
for name in [
APP,
deep.as_str(),
"relay.wanderbooks.link.",
"wanderbooks.link.",
"A.B.C.D.wanderbooks.link.",
] {
let m = ask(&svc, name, RecordType::A, true);
assert_eq!(m.metadata.response_code, ResponseCode::NoError, "{name}");
assert!(m.metadata.authoritative);
assert!(
matches!(m.answers.as_slice(), [r] if r.data == RData::A(A::from(Ipv4Addr::new(198, 51, 100, 7)))),
"{name}: {:?}",
m.answers
);
let m6 = ask(&svc, name, RecordType::AAAA, true);
assert_eq!(m6.answers.len(), 1, "{name}");
}
}
}
#[test]
fn the_name_servers_are_at_their_own_addresses() {
let (svc, _) = svc();
let m = ask(&svc, "ns2.wanderbooks.link.", RecordType::A, true);
assert!(
matches!(m.answers.as_slice(), [r] if r.data == RData::A(A::from(Ipv4Addr::new(203, 0, 113, 53))))
);
let ns = ask(&svc, "wanderbooks.link.", RecordType::NS, true);
assert_eq!(ns.answers.len(), 2);
assert_eq!(ns.additionals.len(), 2);
let soa = ask(&svc, "wanderbooks.link.", RecordType::SOA, true);
assert_eq!(soa.answers.len(), 1);
}
#[test]
fn the_proof_record_is_answered_for_its_own_name_until_it_expires() {
let (svc, txt) = svc();
let mint = Name::parse("ledger-accrual-tally-mint").unwrap();
let t0 = Instant::now();
txt.publish(mint, PROOF, t0).unwrap();
let q = format!("_acme-challenge.{APP}");
let m = ask(&svc, &q, RecordType::TXT, true);
assert_eq!(m.answers.len(), 1);
let RData::TXT(t) = &m.answers[0].data else {
panic!("a TXT")
};
assert_eq!(t.to_string(), PROOF);
// Another app's challenge name has nothing; so does a made-up one.
for other in [
"_acme-challenge.ledger-accrual-tally-vault.wanderbooks.link.",
"_acme-challenge.not-a-name.wanderbooks.link.",
&format!("_acme-challenge.{SECRET}.{APP}"),
APP,
] {
let m = ask(&svc, other, RecordType::TXT, true);
assert_eq!(m.metadata.response_code, ResponseCode::NoError, "{other}");
assert!(m.answers.is_empty(), "{other}");
assert_eq!(m.authorities.len(), 1, "a no-data answer carries the SOA");
}
// After the value's life it is gone.
txt.sweep(t0 + Duration::from_secs(61));
let gone = svc
.answer(
&{
let mut m = Message::query();
m.queries.push(Query::query(
DnsName::from_ascii(&q).unwrap(),
RecordType::TXT,
));
m.to_vec().unwrap()
},
true,
t0 + Duration::from_secs(61),
)
.unwrap();
assert!(Message::from_vec(&gone).unwrap().answers.is_empty());
}
#[test]
fn outside_the_zone_is_refused_and_odd_queries_are_answered_plainly() {
let (svc, _) = svc();
for name in [
"example.com.",
"link.",
"xwanderbooks.link.",
"wanderbooks.link.example.com.",
] {
let m = ask(&svc, name, RecordType::A, true);
assert_eq!(m.metadata.response_code, ResponseCode::Refused, "{name}");
assert!(m.answers.is_empty());
}
let any = ask(&svc, APP, RecordType::ANY, true);
assert_eq!(any.metadata.response_code, ResponseCode::NoError);
assert!(any.answers.is_empty());
let mx = ask(&svc, APP, RecordType::MX, true);
assert!(mx.answers.is_empty() && mx.metadata.response_code == ResponseCode::NoError);
// Not a query, and a response: refused to be answered.
let mut upd = Message::query();
upd.metadata.op_code = OpCode::Update;
upd.queries.push(Query::query(
DnsName::from_ascii(APP).unwrap(),
RecordType::A,
));
let out = svc
.answer(&upd.to_vec().unwrap(), true, Instant::now())
.unwrap();
assert_eq!(
Message::from_vec(&out).unwrap().metadata.response_code,
ResponseCode::NotImp
);
let mut resp = Message::response(7, OpCode::Query);
resp.queries.push(Query::query(
DnsName::from_ascii(APP).unwrap(),
RecordType::A,
));
assert!(
svc.answer(&resp.to_vec().unwrap(), true, Instant::now())
.is_none()
);
// Two questions, no questions.
let mut two = Message::query();
two.queries.push(Query::query(
DnsName::from_ascii(APP).unwrap(),
RecordType::A,
));
two.queries.push(Query::query(
DnsName::from_ascii(APP).unwrap(),
RecordType::AAAA,
));
let out = svc
.answer(&two.to_vec().unwrap(), true, Instant::now())
.unwrap();
assert_eq!(
Message::from_vec(&out).unwrap().metadata.response_code,
ResponseCode::FormErr
);
let none = Message::query().to_vec().unwrap();
let out = svc.answer(&none, true, Instant::now()).unwrap();
assert_eq!(
Message::from_vec(&out).unwrap().metadata.response_code,
ResponseCode::FormErr
);
}
#[test]
fn garbage_never_panics_and_is_mostly_ignored() {
let (svc, _) = svc();
assert!(svc.answer(b"", true, Instant::now()).is_none());
assert!(svc.answer(b"x", true, Instant::now()).is_none());
assert!(
svc.answer(&vec![0u8; QUERY_MAX + 1], true, Instant::now())
.is_none()
);
let mut seed = 0x9e37_79b9u32;
for len in 0..300usize {
let bytes: Vec<u8> = (0..len)
.map(|_| {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(seed >> 24) as u8
})
.collect();
let _ = svc.answer(&bytes, true, Instant::now());
let _ = svc.answer(&bytes, false, Instant::now());
}
}
#[test]
fn a_udp_answer_never_exceeds_the_clients_size() {
let (svc, _) = svc();
// A query with no EDNS gets at most 512 bytes; ours are far less,
// so check the cap by forcing a tiny limit through truncation of
// a big NS set.
let m = ask(&svc, "wanderbooks.link.", RecordType::NS, true);
let bytes = m.to_vec().unwrap();
assert!(bytes.len() <= 512);
assert!(!m.metadata.truncation);
}
#[test]
fn caa_at_the_apex_permits_the_listed_authorities_by_dns_01_only() {
let (svc, _) = svc();
let m = ask(&svc, "wanderbooks.link.", RecordType::CAA, true);
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
let shown: Vec<String> = m.answers.iter().map(|r| r.data.to_string()).collect();
assert_eq!(
shown,
[r#"0 issue "letsencrypt.org; validationmethods=dns-01""#]
);
// Nothing below the apex has a CAA of its own: a certificate
// authority climbs to this one.
let below = ask(&svc, APP, RecordType::CAA, true);
assert!(below.answers.is_empty());
assert_eq!(below.authorities.len(), 1);
}
#[test]
fn caa_is_made_from_the_list_and_follows_it() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.toml");
let one = "[[authority]]\nid='a'\ndirectory='https://x/d'\ncaa_domain='ca-one.example'\n";
std::fs::write(&path, one).unwrap();
let list = Arc::new(AuthorityList::from_file(path.clone()).unwrap());
let cfg = Config::default();
let txt = Arc::new(TxtStore::new(Duration::from_secs(60), 10, 4, 100));
let svc = DnsService::new(
Zone::new(&cfg.domain, &cfg.relay_host),
&cfg,
txt,
Arc::clone(&list),
)
.unwrap();
let caa = |svc: &DnsService| -> Vec<String> {
ask(svc, "wanderbooks.link.", RecordType::CAA, true)
.answers
.iter()
.map(|r| r.data.to_string())
.collect()
};
assert_eq!(
caa(&svc),
[r#"0 issue "ca-one.example; validationmethods=dns-01""#]
);
let two = format!(
"{one}[[authority]]\nid='b'\ndirectory='https://y/d'\ncaa_domain='ca-two.example'\n"
);
std::fs::write(&path, two).unwrap();
assert!(list.reload().unwrap());
assert_eq!(caa(&svc).len(), 2);
// No authority listed: no CAA record, which restricts nobody.
let none = DnsService::new(
Zone::new(&cfg.domain, &cfg.relay_host),
&cfg,
Arc::new(TxtStore::new(Duration::from_secs(60), 10, 4, 100)),
Arc::new(AuthorityList::empty()),
)
.unwrap();
assert!(caa(&none).is_empty());
}
#[test]
fn the_truncated_answer_is_the_question_with_the_tc_bit_and_nothing_more() {
let (svc, _) = svc();
let mut q = Message::query();
q.metadata.id = 0x4242;
q.queries.push(Query::query(
DnsName::from_ascii(APP).unwrap(),
RecordType::A,
));
let wire = q.to_vec().unwrap();
let out = svc.truncated(&wire).expect("a truncated answer");
assert!(out.len() <= wire.len() + 12, "no bigger than the query");
let m = Message::from_vec(&out).unwrap();
assert!(m.metadata.truncation);
assert_eq!(m.metadata.id, 0x4242);
assert_eq!(m.metadata.message_type, MessageType::Response);
assert!(m.answers.is_empty() && m.authorities.is_empty() && m.additionals.is_empty());
assert_eq!(m.queries.len(), 1);
// Garbage, a response and a non-query are not answered at all.
assert!(svc.truncated(b"x").is_none());
assert!(svc.truncated(&vec![0u8; QUERY_MAX + 1]).is_none());
let mut resp = Message::response(7, OpCode::Query);
resp.queries.push(q.queries[0].clone());
assert!(svc.truncated(&resp.to_vec().unwrap()).is_none());
}
}
+131
View File
@@ -0,0 +1,131 @@
//! A connection with its first bytes put back, and a clock on its reads.
//!
//! The router reads the ClientHello itself to find the server name. For
//! the relay's own host the same bytes must then go to TLS, so the stream
//! is wrapped to give them back first. The wrapper also stamps the time of
//! every read, which is how a silent line is told from a quiet one.
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::Instant;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
/// The time of the last read, in milliseconds since `base`.
#[derive(Debug)]
pub struct Activity {
base: Instant,
last_ms: AtomicU64,
}
impl Activity {
/// A clock that reads "now" as its last activity.
pub fn new() -> Arc<Self> {
Arc::new(Activity {
base: Instant::now(),
last_ms: AtomicU64::new(0),
})
}
/// Record activity.
pub fn touch(&self) {
let ms = u64::try_from(self.base.elapsed().as_millis()).unwrap_or(u64::MAX);
self.last_ms.store(ms, Ordering::Relaxed);
}
/// How long since the last activity.
pub fn since(&self) -> std::time::Duration {
let now = u64::try_from(self.base.elapsed().as_millis()).unwrap_or(u64::MAX);
std::time::Duration::from_millis(now.saturating_sub(self.last_ms.load(Ordering::Relaxed)))
}
}
/// `inner`, with `prefix` read first, and every read stamped on `activity`.
pub struct Front<S> {
prefix: Vec<u8>,
at: usize,
inner: S,
activity: Option<Arc<Activity>>,
}
impl<S> Front<S> {
/// Give `prefix` back before anything from `inner`.
pub fn new(prefix: Vec<u8>, inner: S, activity: Option<Arc<Activity>>) -> Self {
Front {
prefix,
at: 0,
inner,
activity,
}
}
}
impl<S: AsyncRead + Unpin> AsyncRead for Front<S> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let this = &mut *self;
if this.at < this.prefix.len() {
let rest = &this.prefix[this.at..];
let n = rest.len().min(buf.remaining());
buf.put_slice(&rest[..n]);
this.at += n;
if this.at == this.prefix.len() {
// Give the memory back: a line lives for days.
this.prefix = Vec::new();
this.at = 0;
}
return Poll::Ready(Ok(()));
}
let before = buf.filled().len();
let r = Pin::new(&mut this.inner).poll_read(cx, buf);
if matches!(r, Poll::Ready(Ok(())))
&& buf.filled().len() > before
&& let Some(a) = &this.activity
{
a.touch();
}
r
}
}
impl<S: AsyncWrite + Unpin> AsyncWrite for Front<S> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
#[cfg(test)]
mod tests {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use super::*;
#[tokio::test]
async fn the_prefix_comes_first_then_the_stream() {
let (mut a, b) = tokio::io::duplex(64);
a.write_all(b"world").await.unwrap();
drop(a);
let act = Activity::new();
let mut f = Front::new(b"hello ".to_vec(), b, Some(act.clone()));
let mut out = String::new();
f.read_to_string(&mut out).await.unwrap();
assert_eq!(out, "hello world");
assert!(act.since() < std::time::Duration::from_secs(5));
}
}
+534
View File
@@ -0,0 +1,534 @@
//! Fixed-size per-address tables.
//!
//! A hash map keyed by address grows with the number of strangers. These
//! tables do not: an address hashes (with a key picked at start) to one of
//! a fixed number of slots, and the slot holds a counter. Two addresses
//! may share a slot, which makes the limit slightly stricter for both,
//! never looser. The memory is the same however many addresses call.
//!
//! Addresses are counted by what a subscriber holds, never by the full
//! address. An IPv4-mapped IPv6 address (`::ffff:a.b.c.d`, what a
//! dual-stack listener reports for an IPv4 caller) is made canonical
//! first, so every IPv4 caller is its own and not all of them one /64
//! with zero for a prefix. Then:
//!
//! - *host* reach: an IPv4 address, or an IPv6 /64;
//! - *net* reach: an IPv4 /24, or an IPv6 /48 (a site's allocation).
//!
//! ```text
//! GOAL: limit what one address, and one network, can hold open or ask
//! for, in memory that does not depend on how many addresses there
//! are.
//! SOURCE: WB-relay-7 (bounds).
//! INVARIANTS:
//! 1. The table never allocates after it is made.
//! 2. A permit's drop gives back exactly what it took: after every
//! permit is dropped every slot reads zero.
//! 3. An address is refused once its slot holds `limit` permits, and
//! never admitted past it.
//! 4. An IPv4-mapped IPv6 address and the IPv4 address it maps are one
//! address, in every table.
//! 5. A windowed count never lets more than its limit through in one
//! window, for the host prefix and for the net prefix both.
//! SCENARIOS:
//! 1. A limit of 2: two permits for one address, the third is refused;
//! dropping one lets a new one in.
//! 2. IPv6 addresses count by /64 (host reach) and /48 (net reach).
//! 3. Fifty distinct IPv6 addresses in one /64 get the /64's limit, not
//! fifty times it.
//! 4. Two different IPv4 callers on a dual-stack listener do not share
//! a slot.
//! ```
use std::hash::{BuildHasher, RandomState};
use std::net::IpAddr;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// How much of an address is one "address" for a table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reach {
/// An IPv4 address, or an IPv6 /64: one subscriber.
Host,
/// An IPv4 /24, or an IPv6 /48: one site or one small provider's block.
Net,
}
/// The key an address has at this reach, after making it canonical.
pub fn prefix_key(ip: IpAddr, reach: Reach) -> u128 {
match ip.to_canonical() {
IpAddr::V4(v4) => {
let bits = u32::from(v4);
u128::from(match reach {
Reach::Host => bits,
Reach::Net => bits & 0xffff_ff00,
})
}
IpAddr::V6(v6) => {
let octets = v6.octets();
let take = match reach {
Reach::Host => 8,
Reach::Net => 6,
};
let mut key = 0u64;
for b in &octets[..take] {
key = (key << 8) | u64::from(*b);
}
u128::from(key) | (1 << 100)
}
}
}
/// A fixed table of per-address counters.
pub struct IpGate {
slots: Box<[AtomicU32]>,
mask: usize,
state: RandomState,
limit: u32,
reach: Reach,
}
/// One held place in an [`IpGate`]; dropping it frees the place.
pub struct IpPermit {
gate: Arc<IpGate>,
slot: usize,
}
impl IpGate {
/// A table of `slots` (rounded up to a power of two), each address
/// (an IPv4 address, an IPv6 /64) allowed `limit` permits at once.
pub fn new(slots: usize, limit: u32) -> Arc<Self> {
Self::with_reach(slots, limit, Reach::Host)
}
/// The same, counting a whole network (an IPv4 /24, an IPv6 /48).
pub fn net(slots: usize, limit: u32) -> Arc<Self> {
Self::with_reach(slots, limit, Reach::Net)
}
fn with_reach(slots: usize, limit: u32, reach: Reach) -> Arc<Self> {
let n = slots.max(2).next_power_of_two();
Arc::new(IpGate {
slots: (0..n).map(|_| AtomicU32::new(0)).collect(),
mask: n - 1,
state: RandomState::new(),
limit,
reach,
})
}
fn slot(&self, ip: IpAddr) -> usize {
// Truncating a hash to a table index is the point.
(self.state.hash_one(prefix_key(ip, self.reach)) as usize) & self.mask
}
/// Take a place for `ip`, or `None` when it already holds its limit.
pub fn acquire(self: &Arc<Self>, ip: IpAddr) -> Option<IpPermit> {
let slot = self.slot(ip);
let cell = &self.slots[slot];
let mut cur = cell.load(Ordering::Relaxed);
loop {
if cur >= self.limit {
return None;
}
match cell.compare_exchange_weak(cur, cur + 1, Ordering::AcqRel, Ordering::Relaxed) {
Ok(_) => {
return Some(IpPermit {
gate: Arc::clone(self),
slot,
});
}
Err(seen) => cur = seen,
}
}
}
/// Permits held now, over all slots (for tests and the stats line).
pub fn held(&self) -> u64 {
self.slots
.iter()
.map(|c| u64::from(c.load(Ordering::Relaxed)))
.fold(0, u64::saturating_add)
}
}
impl Drop for IpPermit {
fn drop(&mut self) {
self.gate.slots[self.slot].fetch_sub(1, Ordering::AcqRel);
}
}
/// One token bucket.
#[derive(Debug, Clone, Copy)]
pub struct TokenBucket {
last: Instant,
tokens: f64,
rate: f64,
burst: f64,
}
impl TokenBucket {
/// `rate` tokens a second sustained, `burst` at once; starts full.
pub fn new(rate: u32, burst: u32, now: Instant) -> Self {
TokenBucket {
last: now,
tokens: f64::from(burst),
rate: f64::from(rate),
burst: f64::from(burst),
}
}
/// Spend one token at `now`; false when there is none.
pub fn allow(&mut self, now: Instant) -> bool {
let gained = now.saturating_duration_since(self.last).as_secs_f64() * self.rate;
self.tokens = (self.tokens + gained).min(self.burst);
self.last = now;
if self.tokens >= 1.0 {
self.tokens -= 1.0;
true
} else {
false
}
}
}
/// A fixed table of token buckets, one per address slot, for a loop that
/// owns it (the UDP DNS loop). Memory is fixed.
pub struct RateTable {
slots: Vec<TokenBucket>,
mask: usize,
state: RandomState,
}
impl RateTable {
/// `rate` queries per second sustained, `burst` at once.
pub fn new(slots: usize, rate: u32, burst: u32) -> Self {
let n = slots.max(2).next_power_of_two();
RateTable {
slots: vec![TokenBucket::new(rate, burst, Instant::now()); n],
mask: n - 1,
state: RandomState::new(),
}
}
/// Spend one token for `ip` at `now`; false when it has none.
pub fn allow(&mut self, ip: IpAddr, now: Instant) -> bool {
let slot = (self.state.hash_one(prefix_key(ip, Reach::Host)) as usize) & self.mask;
self.slots[slot].allow(now)
}
}
/// A windowed count per address prefix, in fixed memory: at most `host`
/// events per window for one IPv4 address or IPv6 /64, and at most `net`
/// for one IPv4 /24 or IPv6 /48. A count is `(window start, events)` in a
/// slot chosen by a hash with a key picked at start; two prefixes sharing
/// a slot only make the limit stricter for both.
pub struct PrefixLimit {
inner: Mutex<PrefixTables>,
state: RandomState,
mask: usize,
base: Instant,
host: u32,
net: u32,
window: Duration,
}
struct PrefixTables {
host: Vec<(u32, u32)>,
net: Vec<(u32, u32)>,
}
impl PrefixLimit {
/// Tables of `slots` each (a power of two is made of it).
pub fn new(slots: usize, host: u32, net: u32, window: Duration) -> Self {
let n = slots.max(2).next_power_of_two();
PrefixLimit {
inner: Mutex::new(PrefixTables {
host: vec![(0, 0); n],
net: vec![(0, 0); n],
}),
state: RandomState::new(),
mask: n - 1,
base: Instant::now(),
host,
net,
window,
}
}
/// Count one event for `ip` at `now`; false (and nothing counted) when
/// either its host prefix or its network prefix is at its limit.
pub fn allow(&self, ip: IpAddr, now: Instant) -> bool {
let secs =
u32::try_from(now.saturating_duration_since(self.base).as_secs()).unwrap_or(u32::MAX);
let window = u32::try_from(self.window.as_secs()).unwrap_or(u32::MAX);
let hs = (self.state.hash_one(prefix_key(ip, Reach::Host)) as usize) & self.mask;
let ns = (self.state.hash_one(prefix_key(ip, Reach::Net)) as usize) & self.mask;
let mut guard = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let t = &mut *guard;
for cell in [&mut t.host[hs], &mut t.net[ns]] {
if secs.saturating_sub(cell.0) >= window {
*cell = (secs, 0);
}
}
if t.host[hs].1 >= self.host || t.net[ns].1 >= self.net {
return false;
}
t.host[hs].1 += 1;
t.net[ns].1 += 1;
true
}
}
/// Addresses that held a proven line lately, in a fixed bitmap: two
/// generations of a two-hash Bloom filter, the old one dropped every
/// `period`. An address is "known" if it marked itself within one to two
/// periods. A false "known" lets a stranger into the small hello reserve;
/// a false "unknown" cannot happen inside the window.
pub struct KnownAddrs {
inner: Mutex<KnownGens>,
state: RandomState,
mask: usize,
period: Duration,
}
struct KnownGens {
cur: Vec<u64>,
prev: Vec<u64>,
rotated: Instant,
}
impl KnownAddrs {
/// A filter of `bits` bits per generation (rounded up to a power of
/// two, at least 64), generations `period` long.
pub fn new(bits: usize, period: Duration) -> Self {
let n = bits.max(64).next_power_of_two();
KnownAddrs {
inner: Mutex::new(KnownGens {
cur: vec![0; n / 64],
prev: vec![0; n / 64],
rotated: Instant::now(),
}),
state: RandomState::new(),
mask: n - 1,
period,
}
}
fn bits(&self, ip: IpAddr) -> [usize; 2] {
let key = prefix_key(ip, Reach::Host);
// Truncating a hash to a bit index is the point.
[
(self.state.hash_one((key, 0u8)) as usize) & self.mask,
(self.state.hash_one((key, 1u8)) as usize) & self.mask,
]
}
fn rotate(&self, g: &mut KnownGens, now: Instant) {
if now.saturating_duration_since(g.rotated) >= self.period {
std::mem::swap(&mut g.cur, &mut g.prev);
g.cur.fill(0);
g.rotated = now;
}
}
/// Remember `ip` as an address that held a proven line.
pub fn mark(&self, ip: IpAddr, now: Instant) {
let bits = self.bits(ip);
let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner());
self.rotate(&mut g, now);
for b in bits {
g.cur[b / 64] |= 1 << (b % 64);
}
}
/// Did `ip` hold a proven line within one to two periods?
pub fn contains(&self, ip: IpAddr, now: Instant) -> bool {
let bits = self.bits(ip);
let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner());
self.rotate(&mut g, now);
let has = |bitmap: &[u64]| bits.iter().all(|b| bitmap[b / 64] & (1 << (b % 64)) != 0);
has(&g.cur) || has(&g.prev)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_limit_of_two_admits_two_and_frees_on_drop() {
let gate = IpGate::new(1024, 2);
let ip: IpAddr = "203.0.113.9".parse().unwrap();
let a = gate.acquire(ip).unwrap();
let _b = gate.acquire(ip).unwrap();
assert!(gate.acquire(ip).is_none());
assert_eq!(gate.held(), 2);
drop(a);
let _c = gate.acquire(ip).expect("a place was freed");
assert!(gate.acquire(ip).is_none());
assert!(gate.acquire("198.51.100.1".parse().unwrap()).is_some());
}
#[test]
fn every_permit_gives_back_what_it_took() {
let gate = IpGate::new(64, 1000);
let mut held = Vec::new();
for i in 0..500u32 {
let ip = IpAddr::from(std::net::Ipv4Addr::from(i.wrapping_mul(2_654_435_761)));
if let Some(p) = gate.acquire(ip) {
held.push(p);
}
}
assert_eq!(gate.held(), held.len() as u64);
drop(held);
assert_eq!(gate.held(), 0);
}
#[test]
fn ipv6_counts_by_the_slash_64() {
let gate = IpGate::new(1 << 12, 1);
let a: IpAddr = "2001:db8:1:2::1".parse().unwrap();
let b: IpAddr = "2001:db8:1:2:ffff::9".parse().unwrap();
let _p = gate.acquire(a).unwrap();
assert!(gate.acquire(b).is_none(), "same /64");
}
#[test]
fn a_rate_table_allows_a_burst_then_the_rate() {
let mut t = RateTable::new(256, 10, 3);
let ip: IpAddr = "203.0.113.9".parse().unwrap();
let t0 = std::time::Instant::now();
assert!(t.allow(ip, t0) && t.allow(ip, t0) && t.allow(ip, t0));
assert!(!t.allow(ip, t0));
assert!(t.allow(ip, t0 + std::time::Duration::from_millis(150)));
}
fn v6(a: &str) -> IpAddr {
a.parse().unwrap()
}
#[test]
fn two_ipv4_callers_on_a_dual_stack_listener_do_not_share_a_slot() {
// `::ffff:a.b.c.d` has a zero first 64 bits: keyed by /64 raw, every
// IPv4 caller would be one address and one would exhaust the limit.
let gate = IpGate::new(1 << 12, 1);
let _a = gate.acquire(v6("::ffff:203.0.113.9")).unwrap();
assert!(
gate.acquire(v6("::ffff:198.51.100.1")).is_some(),
"another IPv4 caller shared the first one's slot"
);
// And the mapped form and the plain form are one address.
assert!(gate.acquire("203.0.113.9".parse().unwrap()).is_none());
let mut rates = RateTable::new(1 << 12, 1, 1);
let t0 = Instant::now();
assert!(rates.allow(v6("::ffff:203.0.113.9"), t0));
assert!(rates.allow(v6("::ffff:198.51.100.1"), t0));
assert!(!rates.allow("203.0.113.9".parse().unwrap(), t0));
}
#[test]
fn a_net_gate_counts_a_slash_48_and_an_ipv4_slash_24() {
let gate = IpGate::net(1 << 12, 2);
let a = gate.acquire(v6("2001:db8:1:1::1")).unwrap();
let _b = gate.acquire(v6("2001:db8:1:ffff::1")).unwrap(); // same /48
assert!(gate.acquire(v6("2001:db8:1:7::9")).is_none());
assert!(gate.acquire(v6("2001:db8:2::1")).is_some(), "another /48");
drop(a);
assert!(gate.acquire(v6("2001:db8:1:5::1")).is_some());
let v4 = IpGate::net(1 << 12, 1);
let _c = v4.acquire("203.0.113.9".parse().unwrap()).unwrap();
assert!(v4.acquire("203.0.113.200".parse().unwrap()).is_none());
assert!(v4.acquire("203.0.114.9".parse().unwrap()).is_some());
}
#[test]
fn fifty_addresses_in_one_slash_64_get_the_slash_64s_limit_not_fifty_times_it() {
let limit = PrefixLimit::new(1 << 12, 5, 1000, Duration::from_secs(3600));
let t0 = Instant::now();
let allowed = (1..=50u32)
.filter(|i| limit.allow(v6(&format!("2001:db8:1:2::{i:x}")), t0))
.count();
assert_eq!(allowed, 5);
// The same addresses written as one /64's other half too.
assert!(!limit.allow(v6("2001:db8:1:2:aaaa:bbbb:cccc:dddd"), t0));
// Another /64 is another subscriber.
assert!(limit.allow(v6("2001:db8:1:3::1"), t0));
}
#[test]
fn one_slash_48_cannot_use_many_slash_64s_to_beat_the_limit() {
// 5 each per /64, 12 for the /48: a hundred /64s in one /48 get 12.
let limit = PrefixLimit::new(1 << 12, 5, 12, Duration::from_secs(3600));
let t0 = Instant::now();
let allowed = (0..100u32)
.filter(|i| limit.allow(v6(&format!("2001:db8:9:{i:x}::1")), t0))
.count();
assert_eq!(allowed, 12);
// IPv4: five per address, twelve per /24.
let allowed = (0..100u32)
.filter(|i| limit.allow(format!("203.0.113.{i}").parse().unwrap(), t0))
.count();
assert_eq!(allowed, 12);
assert!(
limit.allow("203.0.114.1".parse().unwrap(), t0),
"another /24"
);
}
#[test]
fn a_mapped_address_is_counted_with_its_ipv4_address() {
let limit = PrefixLimit::new(1 << 12, 2, 100, Duration::from_secs(3600));
let t0 = Instant::now();
assert!(limit.allow(v6("::ffff:203.0.113.9"), t0));
assert!(limit.allow("203.0.113.9".parse().unwrap(), t0));
assert!(!limit.allow(v6("::ffff:203.0.113.9"), t0));
// Another mapped IPv4 address is not the same /64 as the first.
assert!(limit.allow(v6("::ffff:198.51.100.1"), t0));
}
#[test]
fn a_prefix_limit_resets_with_its_window_and_a_refusal_counts_nothing() {
let limit = PrefixLimit::new(1 << 12, 1, 2, Duration::from_secs(60));
let t0 = Instant::now();
assert!(limit.allow("203.0.113.1".parse().unwrap(), t0));
assert!(limit.allow("203.0.113.2".parse().unwrap(), t0));
// The /24 is at 2 now; a third address is refused, and that refusal
// did not spend its own host count.
assert!(!limit.allow("203.0.113.3".parse().unwrap(), t0));
let later = t0 + Duration::from_secs(61);
assert!(limit.allow("203.0.113.3".parse().unwrap(), later));
}
#[test]
fn known_addresses_are_remembered_for_one_to_two_periods() {
let known = KnownAddrs::new(1 << 16, Duration::from_secs(100));
let t0 = Instant::now();
let a: IpAddr = "203.0.113.9".parse().unwrap();
assert!(!known.contains(a, t0));
known.mark(a, t0);
assert!(known.contains(a, t0));
assert!(known.contains(v6("::ffff:203.0.113.9"), t0), "mapped form");
assert!(known.contains(a, t0 + Duration::from_secs(150)));
assert!(!known.contains(a, t0 + Duration::from_secs(250)));
// A stranger, among many marked addresses, is almost never known.
let k2 = KnownAddrs::new(1 << 20, Duration::from_secs(100));
for i in 0..5000u32 {
k2.mark(
IpAddr::from(std::net::Ipv4Addr::from(i.wrapping_mul(2_654_435_761))),
t0,
);
}
let hits = (0..5000u32)
.filter(|i| {
k2.contains(
IpAddr::from(std::net::Ipv4Addr::from(
i.wrapping_mul(40_503).wrapping_add(0x0a00_0001) ^ 0x5555_aaaa,
)),
t0,
)
})
.count();
assert!(hits < 50, "{hits} of 5000 strangers looked known");
}
}
+317
View File
@@ -0,0 +1,317 @@
//! Reading the server name from a TLS ClientHello, without terminating TLS.
//!
//! The first record of a TLS connection is unencrypted. The router reads
//! it, takes the server name, and forwards the bytes untouched. The
//! parser works on a byte slice, never allocates beyond the name it
//! returns, and treats every length as hostile.
//!
//! ```text
//! GOAL: find the server name in the first TLS record, or say it is not
//! there, on any bytes a stranger can send, without panicking and
//! without reading past what was given.
//! SOURCE: WB-relay-1 (the router), RFC 8446 section 4.1.2 and RFC 6066
//! section 3 (the record and the server_name extension).
//! INVARIANTS:
//! 1. `record_len` and `server_name` never panic and never read beyond
//! the slice, whatever the bytes.
//! 2. A name is returned only from a well-formed server_name extension
//! of a complete ClientHello that fits one record, and only when it
//! is a plausible host name (ASCII letters, digits, `-`, `.`, `_`,
//! at most 253 bytes, no empty label).
//! 3. The record length is read from five bytes and is at most 16 384,
//! so a caller never holds more than 16 389 bytes for the hello.
//! SCENARIOS:
//! 1. A real rustls ClientHello for `a.example` gives `a.example`.
//! 2. A hello with no server_name, a truncated hello, an SSLv2 hello
//! and random bytes give an error, not a name.
//! ```
/// The most a TLS record may carry (RFC 8446 section 5.1).
pub const MAX_RECORD: usize = 16 * 1024;
/// A record's header: type, version, length.
pub const RECORD_HEADER: usize = 5;
/// Why the first bytes are not a hello with a name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum HelloError {
/// Not a TLS handshake record, or one longer than TLS allows.
#[error("not a TLS handshake record")]
NotTls,
/// The record is well formed but has no usable server name.
#[error("no server name")]
NoName,
/// The bytes are not a well-formed ClientHello.
#[error("malformed ClientHello")]
Malformed,
}
/// From the first five bytes: how many more bytes the record has.
///
/// Refuses anything that is not a handshake record of a TLS version
/// 1.0 to 1.3, or longer than a TLS record may be.
pub fn record_len(header: &[u8]) -> Result<usize, HelloError> {
let [kind, major, minor, hi, lo] = *header
.first_chunk::<RECORD_HEADER>()
.ok_or(HelloError::NotTls)?;
if kind != 0x16 || major != 3 || minor > 4 {
return Err(HelloError::NotTls);
}
let len = usize::from(u16::from_be_bytes([hi, lo]));
if len == 0 || len > MAX_RECORD {
return Err(HelloError::NotTls);
}
Ok(len)
}
/// A cursor over a slice that refuses to read past its end.
struct Cur<'a>(&'a [u8]);
impl<'a> Cur<'a> {
fn take(&mut self, n: usize) -> Result<&'a [u8], HelloError> {
let (head, rest) = self.0.split_at_checked(n).ok_or(HelloError::Malformed)?;
self.0 = rest;
Ok(head)
}
fn u8(&mut self) -> Result<u8, HelloError> {
Ok(self.take(1)?[0])
}
fn u16(&mut self) -> Result<usize, HelloError> {
let b = self.take(2)?;
Ok(usize::from(u16::from_be_bytes([b[0], b[1]])))
}
fn u24(&mut self) -> Result<usize, HelloError> {
let b = self.take(3)?;
Ok((usize::from(b[0]) << 16) | (usize::from(b[1]) << 8) | usize::from(b[2]))
}
fn vec8(&mut self) -> Result<&'a [u8], HelloError> {
let n = usize::from(self.u8()?);
self.take(n)
}
fn vec16(&mut self) -> Result<&'a [u8], HelloError> {
let n = self.u16()?;
self.take(n)
}
}
/// The server name in a complete first record (header and body), lower
/// case and without a trailing dot.
///
/// The record must hold the whole ClientHello: a hello split over several
/// records is refused (`Malformed`), as no client sends one in practice
/// and holding several records would let a stranger make us hold more.
pub fn server_name(record: &[u8]) -> Result<String, HelloError> {
let len = record_len(record)?;
let body = record
.get(RECORD_HEADER..RECORD_HEADER + len)
.ok_or(HelloError::Malformed)?;
let mut hs = Cur(body);
if hs.u8()? != 0x01 {
return Err(HelloError::Malformed); // not a ClientHello
}
let hello_len = hs.u24()?;
let mut hello = Cur(hs.take(hello_len)?);
hello.take(2)?; // client_version
hello.take(32)?; // random
hello.vec8()?; // session_id
hello.vec16()?; // cipher_suites
hello.vec8()?; // compression_methods
if hello.0.is_empty() {
return Err(HelloError::NoName); // a hello with no extensions
}
let mut exts = Cur(hello.vec16()?);
let mut found: Option<String> = None;
while !exts.0.is_empty() {
let kind = exts.u16()?;
let data = exts.vec16()?;
if kind == 0 {
if found.is_some() {
return Err(HelloError::Malformed); // two server_name extensions
}
found = Some(parse_server_name_ext(data)?);
}
}
found.ok_or(HelloError::NoName)
}
fn parse_server_name_ext(data: &[u8]) -> Result<String, HelloError> {
let mut ext = Cur(data);
let mut list = Cur(ext.vec16()?);
if !ext.0.is_empty() {
return Err(HelloError::Malformed);
}
let mut host: Option<&[u8]> = None;
while !list.0.is_empty() {
let name_type = list.u8()?;
let name = list.vec16()?;
if name_type == 0 {
if host.is_some() {
return Err(HelloError::Malformed);
}
host = Some(name);
}
}
let host = host.ok_or(HelloError::NoName)?;
plausible_host(host)
}
/// A host name the router can look at: ASCII, at most 253 bytes, labels
/// of 1 to 63 bytes from letters, digits, `-` and `_`; lowered, and the
/// trailing dot dropped. An IP address is a host name that will not match
/// any app, which is the right answer.
fn plausible_host(raw: &[u8]) -> Result<String, HelloError> {
let text = std::str::from_utf8(raw).map_err(|_| HelloError::Malformed)?;
let text = text.strip_suffix('.').unwrap_or(text);
if text.is_empty() || text.len() > 253 {
return Err(HelloError::NoName);
}
for label in text.split('.') {
if label.is_empty()
|| label.len() > 63
|| !label
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
{
return Err(HelloError::NoName);
}
}
Ok(text.to_ascii_lowercase())
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
/// A ClientHello record built by hand, with the given extensions.
pub(crate) fn hello_record(exts: &[(u16, Vec<u8>)]) -> Vec<u8> {
let mut ext_bytes = Vec::new();
for (kind, data) in exts {
ext_bytes.extend(kind.to_be_bytes());
ext_bytes.extend(u16::try_from(data.len()).unwrap().to_be_bytes());
ext_bytes.extend(data);
}
let mut hello = vec![3, 3];
hello.extend([7u8; 32]);
hello.push(0); // session id
hello.extend([0, 2, 0x13, 0x01]); // one cipher suite
hello.extend([1, 0]); // null compression
hello.extend(u16::try_from(ext_bytes.len()).unwrap().to_be_bytes());
hello.extend(ext_bytes);
let mut hs = vec![1];
hs.extend(&u32::try_from(hello.len()).unwrap().to_be_bytes()[1..]);
hs.extend(hello);
let mut rec = vec![0x16, 3, 1];
rec.extend(u16::try_from(hs.len()).unwrap().to_be_bytes());
rec.extend(hs);
rec
}
pub(crate) fn sni_ext(host: &str) -> (u16, Vec<u8>) {
let mut entry = vec![0];
entry.extend(u16::try_from(host.len()).unwrap().to_be_bytes());
entry.extend(host.as_bytes());
let mut data = u16::try_from(entry.len()).unwrap().to_be_bytes().to_vec();
data.extend(entry);
(0, data)
}
#[test]
fn a_hand_built_hello_gives_its_name_lowered() {
let rec = hello_record(&[(43, vec![2, 3, 4]), sni_ext("A.Example.")]);
assert_eq!(server_name(&rec).as_deref(), Ok("a.example"));
}
#[test]
fn no_name_no_extensions_and_odd_names_are_refused() {
assert_eq!(server_name(&hello_record(&[])), Err(HelloError::NoName));
assert_eq!(
server_name(&hello_record(&[(43, vec![2, 3, 4])])),
Err(HelloError::NoName)
);
for bad in ["", "a..b", "a b", "ex\u{e9}.com", &"a".repeat(64)] {
assert!(
server_name(&hello_record(&[sni_ext(bad)])).is_err(),
"{bad:?}"
);
}
let long = format!(
"{}.{}.{}.{}",
"a".repeat(63),
"b".repeat(63),
"c".repeat(63),
"d".repeat(63)
);
assert!(server_name(&hello_record(&[sni_ext(&long)])).is_err());
// Two server_name extensions are ambiguous: refused.
assert_eq!(
server_name(&hello_record(&[sni_ext("a.example"), sni_ext("b.example")])),
Err(HelloError::Malformed)
);
}
#[test]
fn not_tls_and_cut_off_bytes_are_refused() {
assert_eq!(record_len(b""), Err(HelloError::NotTls));
assert_eq!(record_len(b"GET /"), Err(HelloError::NotTls));
assert_eq!(record_len(&[0x16, 3, 1, 0, 0]), Err(HelloError::NotTls));
assert_eq!(record_len(&[0x16, 3, 1, 0x40, 1]), Err(HelloError::NotTls));
assert_eq!(record_len(&[0x16, 3, 1, 0x40, 0]), Ok(16384));
// SSLv2-style hello.
assert_eq!(record_len(&[0x80, 0x2e, 1, 0, 2]), Err(HelloError::NotTls));
let rec = hello_record(&[sni_ext("a.example")]);
for cut in 0..rec.len() {
assert!(server_name(&rec[..cut]).is_err(), "cut at {cut}");
}
// A handshake that is not a ClientHello.
let mut other = rec.clone();
other[5] = 2;
assert_eq!(server_name(&other), Err(HelloError::Malformed));
}
#[test]
fn a_real_rustls_hello_gives_its_name() {
use std::io::Write;
let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider());
let config = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(rustls::RootCertStore::empty())
.with_no_client_auth();
let name = rustls::pki_types::ServerName::try_from("real.example").unwrap();
let mut conn = rustls::ClientConnection::new(std::sync::Arc::new(config), name).unwrap();
let mut out = Vec::new();
conn.write_tls(&mut out).unwrap();
out.flush().unwrap();
assert_eq!(server_name(&out).as_deref(), Ok("real.example"));
assert_eq!(record_len(&out[..5]).unwrap(), out.len() - 5);
}
proptest::proptest! {
#![proptest_config(proptest::prelude::ProptestConfig::with_cases(4000))]
/// Invariant 1: random bytes never panic.
#[test]
fn random_bytes_never_panic(bytes in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..600)) {
let _ = record_len(&bytes);
let _ = server_name(&bytes);
}
/// Invariant 1 again, on bytes that look like a hello: a valid
/// one with a few bytes flipped, or cut anywhere.
#[test]
fn a_mutated_hello_never_panics(
flips in proptest::collection::vec((0usize..400, proptest::prelude::any::<u8>()), 0..8),
cut in 0usize..400,
) {
let mut rec = hello_record(&[(43, vec![2, 3, 4]), sni_ext("a.example")]);
for (at, to) in flips {
if let Some(b) = rec.get_mut(at) { *b = to; }
}
rec.truncate(cut.max(1));
if let Ok(name) = server_name(&rec) {
// Whatever came out is a plausible host name.
proptest::prop_assert!(!name.is_empty() && name.len() <= 253);
proptest::prop_assert!(name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'.' || b == b'_'));
}
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//! The relay for `wanderbooks.link`.
//!
//! A person runs the Wanderbooks desktop app at home. Web assistants can
//! only call servers on the public internet. The app dials out to this
//! relay and holds one multiplexed line open; the relay routes an
//! assistant's incoming TLS connection, by its server name, down that
//! line to the app. The relay never holds the app's private key and
//! cannot read the traffic: it forwards encrypted bytes. It is also the
//! domain's authoritative DNS server, which lets an app prove its own
//! name to a certificate authority and no other.
//!
//! The crate depends on no `ledger-*` crate. The modules [`proto`],
//! [`names`] and [`client`] are the app's side of the protocol too.
//!
//! ```text
//! GOAL: let a web assistant reach an app behind a home network, with
//! the relay unable to read anything, unable to be made to hold
//! unbounded memory, and unable to give a stranger an app's name
//! or a certificate for it.
//! SOURCE: WB-relay-1 (the router), WB-relay-2 (the line and its proof),
//! WB-relay-3 (names), WB-relay-4 (the registry), WB-relay-5
//! (proof records, DNS and authorities), WB-relay-6 (the
//! caller's address), WB-relay-7 (bounds); D-80, D-82, D-85, D-87.
//! INVARIANTS:
//! 1. No unsafe code anywhere in the crate.
//! 2. The relay holds no key or certificate for any app and never
//! decrypts an app's traffic.
//! 3. The only durable state is the registry (name, key, created,
//! blocked); proof records live minutes, in memory.
//! SCENARIOS:
//! 1. See `tests/relay.rs`: a real TLS client reaches a real TLS
//! server through the relay, and the relay never sees plaintext.
//! ```
#![forbid(unsafe_code)]
pub mod authorities;
pub mod client;
pub mod config;
pub mod dns;
pub mod front;
pub mod gate;
pub mod hello;
pub mod mux;
pub mod names;
pub mod proto;
pub mod registry;
pub mod server;
pub mod splice;
pub mod tls;
pub mod txt;
pub use config::{Config, Limits};
pub use server::Relay;
+108
View File
@@ -0,0 +1,108 @@
//! `wanderbooks-relay`: run the relay from a configuration file.
//!
//! ```text
//! wanderbooks-relay <config.toml>
//! wanderbooks-relay <config.toml> block <four-word-name>
//! wanderbooks-relay <config.toml> unblock <four-word-name>
//! ```
use std::process::ExitCode;
use std::sync::atomic::Ordering;
use std::time::Duration;
use relay::authorities::AuthorityList;
use relay::names::Name;
use relay::registry::Registry;
use relay::{Config, Relay, tls};
fn fail(msg: &str) -> ExitCode {
eprintln!("wanderbooks-relay: {msg}");
ExitCode::FAILURE
}
#[tokio::main]
async fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let Some(path) = args.first() else {
return fail("usage: wanderbooks-relay <config.toml> [block|unblock <name>]");
};
let text = match std::fs::read_to_string(path) {
Ok(t) => t,
Err(e) => return fail(&format!("{path}: {e}")),
};
let cfg = match Config::from_toml(&text) {
Ok(c) => c,
Err(e) => return fail(&format!("{path}: {e}")),
};
let words: Vec<&str> = args.iter().map(String::as_str).collect();
if let [_, verb @ ("block" | "unblock"), name] = words.as_slice() {
let Ok(name) = Name::parse(name) else {
return fail("a name is four words from the list, joined by hyphens");
};
let registry = match Registry::open(&cfg.registry_path, 4) {
Ok(r) => r,
Err(e) => return fail(&e.to_string()),
};
return match registry.set_blocked(&name, *verb == "block").await {
Ok(true) => {
println!("{verb}ed {name}");
ExitCode::SUCCESS
}
Ok(false) => fail("no such name"),
Err(e) => fail(&e.to_string()),
};
}
if args.len() != 1 {
return fail("usage: wanderbooks-relay <config.toml> [block|unblock <name>]");
}
let tls = match tls::server_config_from_files(&cfg.tls_cert, &cfg.tls_key) {
Ok(t) => t,
Err(e) => return fail(&e),
};
// No per-app binding source is installed: an authority that needs an
// external account binding is listed, served without one and marked
// not usable until a deployment supplies a `BindingSource`. The list
// file never carries a binding secret (it is refused at load).
let authorities = match &cfg.authorities_path {
Some(p) => match AuthorityList::from_file(p.clone()) {
Ok(l) => l,
Err(e) => return fail(&e.to_string()),
},
None => AuthorityList::empty(),
};
let relay = match Relay::start(cfg, tls, authorities).await {
Ok(r) => r,
Err(e) => return fail(&format!("could not start: {e}")),
};
eprintln!(
"wanderbooks-relay: router on {}, DNS on {} (udp) and {} (tcp)",
relay.router_addr(),
relay.dns_udp_addr(),
relay.dns_tcp_addr()
);
let shared = relay.shared().clone();
let stats = tokio::spawn(async move {
let mut tick = tokio::time::interval(Duration::from_secs(60));
loop {
tick.tick().await;
let m = &shared.metrics;
eprintln!(
"lines {} routed {} unknown_or_offline {} shed {} hello_timeouts {} bad_hello {} claims {}",
m.lines_up.load(Ordering::Relaxed),
m.routed.load(Ordering::Relaxed),
m.unknown_or_offline.load(Ordering::Relaxed),
m.shed.load(Ordering::Relaxed),
m.hello_timeouts.load(Ordering::Relaxed),
m.bad_hello.load(Ordering::Relaxed),
m.claims.load(Ordering::Relaxed),
);
}
});
let _ = tokio::signal::ctrl_c().await;
eprintln!("wanderbooks-relay: shutting down");
stats.abort();
relay.shutdown().await;
ExitCode::SUCCESS
}
+358
View File
@@ -0,0 +1,358 @@
//! One multiplexed line: streams in both directions over one connection.
//!
//! A line is a yamux connection over the app's TLS. One task drives it:
//! it answers the peer's frames, accepts the streams the peer opens, and
//! opens streams on request. Opening is by a bounded request queue, so a
//! caller who wants a stream waits its turn and cannot make the line hold
//! more than a request at a time.
//!
//! ```text
//! GOAL: many assistant connections ride one line, with the number of
//! streams, the bytes buffered per stream and the time a silent
//! line may live all capped, and a line that is closed or dropped
//! stops its task.
//! SOURCE: WB-relay-7 (bounds), the yamux specification.
//! INVARIANTS:
//! 1. At most `max_streams` streams exist on a line, in both
//! directions together. A line asked for one more, from either
//! side, is ended (that is yamux's rule), so the relay keeps its
//! own per-line permits below the limit.
//! 2. Each stream's receive window is 256 KiB and a line's windows sum
//! to at most 256 KiB times `max_streams`: no window grows. The size
//! is yamux's own constant (the specification's initial credit; the
//! 0.14 crate offers no way to start a stream with less), so what a
//! line can be made to hold, by an app whose own caller reads slowly,
//! is set by how many streams it may have, which is why the relay's
//! stream limits are small. The splice's minimum rate bounds how long
//! a stream can stay full.
//! 3. A line from which nothing was read for `idle` is closed.
//! 4. Dropping every handle, or `close`, ends the driver.
//! SCENARIOS:
//! 1. Streams opened on one side arrive on the other.
//! 2. With `max_streams` open, one more open does not succeed.
//! 3. A line with a silent peer is closed after `idle`.
//! ```
use std::future::poll_fn;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio::time::Instant;
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
use tokio_util::sync::CancellationToken;
use yamux::{Config, Connection, Mode};
use crate::front::Activity;
/// A stream on a line, as tokio's `AsyncRead` and `AsyncWrite`.
pub type Stream = Compat<yamux::Stream>;
/// Why a stream could not be opened.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum MuxError {
/// The line is closed.
#[error("the line is closed")]
Closed,
/// Waited too long.
#[error("timed out opening a stream")]
Timeout,
/// The line refused (too many streams, or the peer is gone).
#[error("the line refused the stream")]
Refused,
}
type Open = oneshot::Sender<Result<Stream, MuxError>>;
/// A handle for opening streams on a line. Clones share the line.
#[derive(Clone)]
pub struct Mux {
cmd: mpsc::Sender<Open>,
cancel: CancellationToken,
}
/// What a line is allowed.
#[derive(Debug, Clone, Copy)]
pub struct MuxLimits {
/// Streams at once, both directions together.
pub max_streams: usize,
/// A line from which nothing was read for this long is closed.
pub idle: Duration,
}
fn yamux_config(max_streams: usize) -> Config {
let mut cfg = Config::default();
cfg.set_max_num_streams(max_streams);
// 256 KiB is yamux's initial window per stream, and the crate fixes
// it (`DEFAULT_CREDIT`; the connection's cap must be at least that
// times the stream limit, or it panics). Capping the sum at exactly
// that stops the auto-tuning from growing any window: this is the
// most a line can ever hold in receive buffers, and the only lever
// left on it is `max_streams`.
cfg.set_max_connection_receive_window(Some(max_streams * yamux::DEFAULT_CREDIT as usize));
cfg
}
impl Mux {
/// Open a stream, waiting at most `wait` for the line to take the
/// request and for the peer to accept it.
pub async fn open(&self, wait: Duration) -> Result<Stream, MuxError> {
let (reply, answer) = oneshot::channel();
let deadline = Instant::now() + wait;
match tokio::time::timeout_at(deadline, self.cmd.send(reply)).await {
Err(_) => return Err(MuxError::Timeout),
Ok(Err(_)) => return Err(MuxError::Closed),
Ok(Ok(())) => {}
}
match tokio::time::timeout_at(deadline, answer).await {
Err(_) => Err(MuxError::Timeout),
Ok(Err(_)) => Err(MuxError::Closed),
Ok(Ok(r)) => r,
}
}
/// Close the line.
pub fn close(&self) {
self.cancel.cancel();
}
/// True once the line is closed or its driver has ended.
pub fn is_closed(&self) -> bool {
self.cancel.is_cancelled() || self.cmd.is_closed()
}
}
enum Event {
Inbound(Stream),
Ended,
}
fn step<T>(
conn: &mut Connection<T>,
cmds: &mut mpsc::Receiver<Open>,
pending: &mut Option<Open>,
cx: &mut Context<'_>,
) -> Poll<Event>
where
T: futures::AsyncRead + futures::AsyncWrite + Unpin,
{
// The connection makes progress only when polled for inbound streams,
// so that always comes first.
match conn.poll_next_inbound(cx) {
Poll::Ready(Some(Ok(s))) => return Poll::Ready(Event::Inbound(s.compat())),
Poll::Ready(Some(Err(_)) | None) => return Poll::Ready(Event::Ended),
Poll::Pending => {}
}
loop {
if pending.is_none() {
match cmds.poll_recv(cx) {
Poll::Ready(Some(open)) => *pending = Some(open),
Poll::Ready(None) => return Poll::Ready(Event::Ended),
Poll::Pending => return Poll::Pending,
}
}
if pending.as_ref().is_some_and(|p| p.is_closed()) {
*pending = None; // the asker gave up: do not open for nobody
continue;
}
match conn.poll_new_outbound(cx) {
Poll::Ready(Ok(s)) => {
if let Some(p) = pending.take() {
let _ = p.send(Ok(s.compat()));
}
// Opening queued a frame; only polling for inbound frames
// sends it, so come round again at once.
cx.waker().wake_by_ref();
return Poll::Pending;
}
Poll::Ready(Err(yamux::ConnectionError::TooManyStreams)) => {
if let Some(p) = pending.take() {
let _ = p.send(Err(MuxError::Refused));
}
}
Poll::Ready(Err(_)) => return Poll::Ready(Event::Ended),
Poll::Pending => return Poll::Pending,
}
}
}
/// Start driving a line. `on_inbound` is called, inline and without
/// blocking, with each stream the peer opens; it must spawn or drop.
pub fn spawn<T>(
socket: T,
mode: Mode,
limits: MuxLimits,
activity: Option<Arc<Activity>>,
mut on_inbound: impl FnMut(Stream) + Send + 'static,
) -> (Mux, JoinHandle<()>)
where
T: futures::AsyncRead + futures::AsyncWrite + Unpin + Send + 'static,
{
let (cmd, mut cmds) = mpsc::channel::<Open>(4);
let cancel = CancellationToken::new();
let mux = Mux {
cmd,
cancel: cancel.clone(),
};
let mut conn = Connection::new(socket, yamux_config(limits.max_streams), mode);
let task = tokio::spawn(async move {
let mut pending: Option<Open> = None;
let idle = limits.idle;
let timer = tokio::time::sleep(idle);
tokio::pin!(timer);
loop {
tokio::select! {
() = cancel.cancelled() => break,
() = &mut timer => {
let quiet = activity.as_ref().map_or(Duration::ZERO, |a| a.since());
if quiet >= idle {
break;
}
timer.as_mut().reset(Instant::now() + (idle - quiet));
}
event = poll_fn(|cx| step(&mut conn, &mut cmds, &mut pending, cx)) => match event {
Event::Inbound(stream) => on_inbound(stream),
Event::Ended => break,
},
}
}
cancel.cancel();
// Refuse anyone still waiting, then close the connection politely
// but briefly.
if let Some(p) = pending.take() {
let _ = p.send(Err(MuxError::Closed));
}
cmds.close();
let _ =
tokio::time::timeout(Duration::from_secs(2), poll_fn(|cx| conn.poll_close(cx))).await;
});
(mux, task)
}
#[cfg(test)]
mod tests {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_util::compat::TokioAsyncReadCompatExt;
use super::*;
fn pair(
max: usize,
idle: Duration,
on_server_inbound: impl FnMut(Stream) + Send + 'static,
) -> (Mux, Mux, mpsc::UnboundedReceiver<Stream>) {
let (a, b) = tokio::io::duplex(64 * 1024);
let limits = MuxLimits {
max_streams: max,
idle,
};
let (tx, rx) = mpsc::unbounded_channel();
let (server, _) = spawn(a.compat(), Mode::Server, limits, None, on_server_inbound);
let (client, _) = spawn(b.compat(), Mode::Client, limits, None, move |s| {
let _ = tx.send(s);
});
(server, client, rx)
}
#[tokio::test]
async fn a_stream_opened_by_one_side_arrives_on_the_other() {
let (server, _client, mut rx) = pair(8, Duration::from_secs(60), |_| {});
let mut s = server.open(Duration::from_secs(2)).await.unwrap();
s.write_all(b"ping").await.unwrap();
s.flush().await.unwrap();
let mut got = rx.recv().await.unwrap();
let mut buf = [0u8; 4];
got.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"ping");
got.write_all(b"pong").await.unwrap();
got.flush().await.unwrap();
s.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"pong");
}
#[tokio::test]
async fn a_line_holds_only_its_streams() {
let (server, _client, mut rx) = pair(2, Duration::from_secs(60), |_| {});
let mut held = Vec::new();
for _ in 0..2 {
let mut s = server.open(Duration::from_secs(2)).await.unwrap();
s.write_all(b"x").await.unwrap();
s.flush().await.unwrap();
held.push(s);
held.push(rx.recv().await.unwrap()); // keep the far end open too
}
let third = server.open(Duration::from_millis(500)).await;
assert!(third.is_err(), "a third stream was opened past the limit");
}
#[tokio::test]
async fn a_silent_line_is_closed_after_its_idle_time() {
let (a, b) = tokio::io::duplex(1024);
let activity = Activity::new();
let limits = MuxLimits {
max_streams: 2,
idle: Duration::from_millis(150),
};
let (mux, task) = spawn(a.compat(), Mode::Server, limits, Some(activity), |_| {});
let _keep = b; // the peer is there and says nothing
tokio::time::timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert!(mux.is_closed());
assert_eq!(
mux.open(Duration::from_millis(100)).await.err(),
Some(MuxError::Closed)
);
}
#[tokio::test]
async fn closing_ends_the_driver() {
let (server, client, _rx) = pair(2, Duration::from_secs(60), |_| {});
server.close();
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(server.is_closed());
assert!(client.open(Duration::from_secs(2)).await.is_err() || client.is_closed());
}
#[tokio::test]
async fn a_large_transfer_both_ways_completes() {
let (server, _client, mut rx) = pair(8, Duration::from_secs(60), |_| {});
let mut near = server.open(Duration::from_secs(2)).await.unwrap();
near.write_all(b"x").await.unwrap();
near.flush().await.unwrap();
let mut far = rx.recv().await.unwrap();
let mut one = [0u8; 1];
far.read_exact(&mut one).await.unwrap();
let echo = tokio::spawn(async move {
let mut buf = [0u8; 4096];
loop {
let n = far.read(&mut buf).await.unwrap();
if n == 0 {
far.shutdown().await.unwrap();
return;
}
far.write_all(&buf[..n]).await.unwrap();
}
});
let (mut rd, mut wr) = tokio::io::split(near);
let data = vec![9u8; 2_000_000];
let send = tokio::spawn({
let data = data.clone();
async move {
wr.write_all(&data).await.unwrap();
wr.shutdown().await.unwrap();
}
});
let mut got = Vec::new();
tokio::time::timeout(Duration::from_secs(20), rd.read_to_end(&mut got))
.await
.expect("the echo completes")
.unwrap();
assert_eq!(got.len(), data.len());
send.await.unwrap();
echo.await.unwrap();
}
}
+404
View File
@@ -0,0 +1,404 @@
//! Names: four words from the curated list, and the address they make.
//!
//! An app's public name is four words from `words.txt` joined by hyphens
//! (`ledger-accrual-tally-mint`). Its endpoint is a long random label
//! beneath it (`<secret>.<four-words>.wanderbooks.link`). The relay routes
//! on the four words and checks only that the secret label has the right
//! shape; the app, which made the label, is the one that checks its value.
//!
//! ```text
//! GOAL: an app's public name is four words from a curated finance and
//! accounting list, never a word a customer would not want in an
//! address; the relay accepts no other name, so no stranger can
//! claim `relay`, `ns1`, `_acme-challenge` or anything else that
//! is not four listed words.
//! SOURCE: WB-relay-3 (names), D-82 in plan/p15-app-and-relay.md.
//! INVARIANTS:
//! 1. A `Name` is four indices into the list, so a name that exists is
//! four listed words: there is no way to hold any other.
//! 2. Parsing is exact: `Name::parse(&name.to_string()) == name`, and
//! any string that is not four listed words, hyphen-joined in
//! lower case, is refused.
//! 3. A host name is routed only as `<secret>.<name>.<domain>`; the
//! domain's apex, the relay's own host and every other shape are
//! not an app's.
//! SCENARIOS:
//! 1. `ledger-accrual-tally-mint` parses, and prints as itself.
//! 2. `ledger-accrual-tally` (three words) and `ledger-accrual-tally-zzzz`
//! (an unlisted word) are refused.
//! 3. `<secret>.ledger-accrual-tally-mint.wanderbooks.link` is that
//! app's; `relay.wanderbooks.link` is the relay's own host.
//! ```
use std::fmt;
use std::sync::OnceLock;
use ring::rand::{SecureRandom, SystemRandom};
const WORDS_TXT: &str = include_str!("../words.txt");
/// The curated list: one lower-case word per line, sorted, no duplicates.
/// The words are for recognition, so they are finance and accounting
/// terms and pleasant plain words, and none a customer would not want in
/// an address (the list's tests refuse a set of unwelcome words).
pub fn words() -> &'static [&'static str] {
static WORDS: OnceLock<Vec<&'static str>> = OnceLock::new();
WORDS.get_or_init(|| WORDS_TXT.lines().filter(|l| !l.is_empty()).collect())
}
/// How many bits of choice four words from the list make.
pub fn name_bits() -> f64 {
// The list is a few thousand words at most, far inside f64's exact range.
4.0 * (words().len() as f64).log2()
}
/// Why a name or host was refused.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum NameError {
/// Not exactly four hyphen-joined words.
#[error("a name is four words joined by hyphens")]
Shape,
/// A word that is not on the list.
#[error("a word that is not on the list")]
UnknownWord,
}
/// An app's public name: four words from the list, held as their indices.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Name([u16; 4]);
impl Name {
/// Parse `a-b-c-d`: four listed words, lower case, hyphen-joined.
pub fn parse(text: &str) -> Result<Self, NameError> {
let list = words();
let mut idx = [0u16; 4];
let mut parts = text.split('-');
for slot in &mut idx {
let word = parts.next().ok_or(NameError::Shape)?;
let at = list
.binary_search(&word)
.map_err(|_| NameError::UnknownWord)?;
*slot = u16::try_from(at).map_err(|_| NameError::Shape)?;
}
if parts.next().is_some() {
return Err(NameError::Shape);
}
Ok(Name(idx))
}
/// A uniformly random name (rejection sampling, no modulo bias).
pub fn random() -> Self {
let rng = SystemRandom::new();
// Words are fewer than 65 536, so an index fits in a `u16` and the
// largest multiple of the list's length below 2^16 is the cut.
let n = u32::try_from(words().len()).unwrap_or(u32::MAX);
let limit = (0x1_0000 / n) * n;
let mut idx = [0u16; 4];
for slot in &mut idx {
loop {
let mut b = [0u8; 2];
if rng.fill(&mut b).is_err() {
// The system generator failing is not recoverable.
panic!("the system random number generator failed");
}
let v = u32::from(u16::from_be_bytes(b));
if v < limit {
*slot = u16::try_from(v % n).unwrap_or(0);
break;
}
}
}
Name(idx)
}
/// The four words.
pub fn words(&self) -> [&'static str; 4] {
let list = words();
self.0
.map(|i| list.get(usize::from(i)).copied().unwrap_or(""))
}
}
impl fmt::Display for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let w = self.words();
write!(f, "{}-{}-{}-{}", w[0], w[1], w[2], w[3])
}
}
impl fmt::Debug for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Name({self})")
}
}
/// The shortest and longest secret label the relay will route. The app
/// makes the label, from at least 128 random bits (25 or more random
/// base 36 characters: 25 of them are 129.2 bits); the relay checks only
/// its shape, and refuses a label too short to hold that much.
pub const SECRET_LEN: std::ops::RangeInclusive<usize> = 25..=63;
/// What a host name (a TLS server name or a DNS name) is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HostKind {
/// The relay's own host: an app's line dials it.
Relay,
/// An assistant reaching the app of this name.
App(Name),
/// Anything else.
Other,
}
/// Which of the relay's own host names is the line's, and the domain.
#[derive(Debug, Clone)]
pub struct Zone {
domain: String,
relay_host: String,
}
impl Zone {
/// `domain` is `wanderbooks.link`, `relay_host` is
/// `relay.wanderbooks.link`; both are lowered and unrooted.
pub fn new(domain: &str, relay_host: &str) -> Self {
Zone {
domain: normalize(domain),
relay_host: normalize(relay_host),
}
}
/// The domain this relay serves.
pub fn domain(&self) -> &str {
&self.domain
}
/// Classify a host name from a ClientHello.
pub fn classify(&self, host: &str) -> HostKind {
let host = normalize(host);
if host == self.relay_host {
return HostKind::Relay;
}
let Some(front) = host
.strip_suffix(&self.domain)
.and_then(|f| f.strip_suffix('.'))
else {
return HostKind::Other;
};
let mut labels = front.split('.');
let (Some(secret), Some(name), None) = (labels.next(), labels.next(), labels.next()) else {
return HostKind::Other;
};
if !SECRET_LEN.contains(&secret.len())
|| !secret
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
{
return HostKind::Other;
}
match Name::parse(name) {
Ok(n) => HostKind::App(n),
Err(_) => HostKind::Other,
}
}
/// The part of a DNS name below the zone, as labels from the left, or
/// `None` when the name is outside the zone. The apex gives no labels.
pub fn below<'a>(&self, host: &'a str) -> Option<Vec<&'a str>> {
let host = host.strip_suffix('.').unwrap_or(host);
if host.eq_ignore_ascii_case(&self.domain) {
return Some(Vec::new());
}
let cut = host.len().checked_sub(self.domain.len() + 1)?;
let (front, rest) = host.split_at_checked(cut)?;
let rest = rest.strip_prefix('.')?;
if !rest.eq_ignore_ascii_case(&self.domain) {
return None;
}
Some(front.split('.').collect())
}
}
fn normalize(host: &str) -> String {
host.trim_end_matches('.').to_ascii_lowercase()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_list_is_sorted_unique_plain_and_welcome() {
let list = words();
assert!(list.len() >= 1024, "{} words", list.len());
assert!(list.windows(2).all(|w| w[0] < w[1]), "sorted, no repeats");
for w in list {
assert!(
(3..=11).contains(&w.len()) && w.bytes().all(|b| b.is_ascii_lowercase()),
"{w}"
);
}
// Words a customer would not want in an address.
for bad in [
"ass", "sex", "gay", "nig", "fuck", "shit", "damn", "hell", "death", "dead", "kill",
"war", "gun", "bomb", "poor", "debt", "fail", "bust", "scam", "fraud", "loss", "lose",
"owe", "deficit", "default", "bankrupt", "arrears", "penalty", "fine", "cancer",
"porn", "rape", "nazi", "slave", "hate", "drug", "sin",
] {
assert!(list.binary_search(&bad).is_err(), "{bad} is on the list");
}
// Words with a reading a customer would not want in an address, and
// words of death and estates (an assistant's name should not be
// "executor" or "testament" of anything).
for bad in ["dong", "probate", "testament", "executor"] {
assert!(list.binary_search(&bad).is_err(), "{bad} is on the list");
}
assert!(name_bits() > 40.0, "{} bits", name_bits());
}
/// Four words must be at least 40 bits of choice (1 024 words is the
/// floor), so a name is hard to guess and rare to collide. Removing
/// words for being confusable must be made up with finance and
/// accounting words before this goes red.
#[test]
fn four_words_are_at_least_40_bits() {
assert!(words().len() >= 1024, "{} words", words().len());
assert!(name_bits() >= 40.0, "{} bits", name_bits());
}
/// A name read aloud must be unambiguous: no word is the inflection of
/// another on the list (the base form stays), and no two words sound
/// alike.
#[test]
fn no_word_is_an_inflection_or_a_homophone_of_another() {
let list = words();
let has = |w: &str| list.binary_search(&w).is_ok();
for w in list {
for suffix in ["s", "es", "d", "ed", "ing", "ies", "ied"] {
assert!(!has(&format!("{w}{suffix}")), "{w} and {w}{suffix}");
}
if let Some(stem) = w.strip_suffix('e') {
assert!(!has(&format!("{stem}ing")), "{w} and {stem}ing");
}
if let Some(stem) = w.strip_suffix('y') {
for suffix in ["ied", "ies"] {
assert!(!has(&format!("{stem}{suffix}")), "{w} and {stem}{suffix}");
}
}
if let Some(last) = w.chars().last() {
for suffix in ["ed", "ing"] {
assert!(
!has(&format!("{w}{last}{suffix}")),
"{w} and {w}{last}{suffix}"
);
}
}
}
// Words that sound alike: at most one of each group is listed.
for group in [
["peer", "pier", "", ""],
["sell", "cell", "", ""],
["current", "currant", "", ""],
["real", "riel", "reel", ""],
["sum", "som", "some", ""],
["sole", "sol", "soul", ""],
["site", "sight", "cite", ""],
["cache", "cash", "", ""],
["fair", "fare", "", ""],
["steel", "steal", "", ""],
["suite", "sweet", "", ""],
["route", "root", "", ""],
["counsel", "council", "", ""],
["principal", "principle", "", ""],
["profit", "prophet", "", ""],
["stake", "steak", "", ""],
] {
let listed: Vec<_> = group.iter().filter(|w| !w.is_empty() && has(w)).collect();
assert!(listed.len() <= 1, "alike-sounding words listed: {listed:?}");
}
assert!(!has("fulfil"), "it is fulfill");
assert!(has("fulfill"));
}
#[test]
fn a_name_is_four_listed_words_and_prints_as_itself() {
let n = Name::parse("ledger-accrual-tally-mint").expect("listed words");
assert_eq!(n.to_string(), "ledger-accrual-tally-mint");
assert_eq!(Name::parse(&n.to_string()), Ok(n));
assert_eq!(Name::parse("ledger-accrual-tally"), Err(NameError::Shape));
assert_eq!(
Name::parse("ledger-accrual-tally-mint-mint"),
Err(NameError::Shape)
);
assert_eq!(
Name::parse("ledger-accrual-tally-zzzz"),
Err(NameError::UnknownWord)
);
assert_eq!(
Name::parse("Ledger-accrual-tally-mint"),
Err(NameError::UnknownWord)
);
for reserved in ["relay", "ns1", "_acme-challenge", "www", "", "-", "---"] {
assert!(Name::parse(reserved).is_err(), "{reserved}");
}
let r = Name::random();
assert_eq!(Name::parse(&r.to_string()), Ok(r));
}
#[test]
fn a_host_is_routed_only_as_secret_dot_name_dot_domain() {
let zone = Zone::new("wanderbooks.link", "relay.wanderbooks.link");
let secret = "k3j9x0q7m2z8c5v1b4n6a9s2d";
let name = Name::parse("ledger-accrual-tally-mint").unwrap();
let host = format!("{secret}.ledger-accrual-tally-mint.wanderbooks.link");
assert_eq!(zone.classify(&host), HostKind::App(name));
assert_eq!(zone.classify(&format!("{host}.")), HostKind::App(name));
assert_eq!(zone.classify(&host.to_uppercase()), HostKind::App(name));
assert_eq!(zone.classify("relay.wanderbooks.link"), HostKind::Relay);
for other in [
"ledger-accrual-tally-mint.wanderbooks.link",
"wanderbooks.link",
"short.ledger-accrual-tally-mint.wanderbooks.link",
"k3j9x0q7m2z8c5v1b4n6a9s2d.ledger-accrual-tally.wanderbooks.link",
"a.k3j9x0q7m2z8c5v1b4n6a9s2d.ledger-accrual-tally-mint.wanderbooks.link",
"k3j9x0q7m2z8c5v1b4n6a9s2d.ledger-accrual-tally-mint.example.com",
"K3J9X0Q7M2Z8C5V1B4N6A9S2D_.ledger-accrual-tally-mint.wanderbooks.link",
"xwanderbooks.link",
"",
] {
assert_eq!(zone.classify(other), HostKind::Other, "{other}");
}
}
/// The secret label is at least 128 bits when the app makes it (25 or
/// more random base 36 characters); a label too short to hold that is
/// not routed, whatever it spells.
#[test]
fn a_secret_label_under_25_characters_is_not_routed() {
let zone = Zone::new("wanderbooks.link", "relay.wanderbooks.link");
let name = Name::parse("ledger-accrual-tally-mint").unwrap();
let on = |secret: &str| {
zone.classify(&format!(
"{secret}.ledger-accrual-tally-mint.wanderbooks.link"
))
};
assert_eq!(on("aaaaaaaaaaaaaaaa"), HostKind::Other, "16 characters");
assert_eq!(on(&"a".repeat(24)), HostKind::Other, "24 characters");
assert_eq!(on(&"a".repeat(25)), HostKind::App(name), "25 characters");
assert_eq!(on(&"a".repeat(63)), HostKind::App(name), "63 characters");
assert_eq!(on(&"a".repeat(64)), HostKind::Other, "64 characters");
assert!(
25.0 * 36f64.log2() >= 128.0,
"25 base 36 characters are 128 bits"
);
assert!(24.0 * 36f64.log2() < 128.0);
}
#[test]
fn below_names_the_labels_under_the_zone() {
let zone = Zone::new("wanderbooks.link", "relay.wanderbooks.link");
assert_eq!(zone.below("wanderbooks.link."), Some(vec![]));
assert_eq!(zone.below("A.b.Wanderbooks.Link"), Some(vec!["A", "b"]));
assert_eq!(zone.below("xwanderbooks.link"), None);
assert_eq!(zone.below("example.com"), None);
assert_eq!(zone.below("link"), None);
}
}
+552
View File
@@ -0,0 +1,552 @@
//! The wire protocol between an app and the relay.
//!
//! Three things travel the app's line, all small and bounded:
//!
//! 1. The **handshake**, once, right after the line's TLS: the relay sends
//! a challenge; the app answers with its name, its public key and a
//! signature; the relay says yes, or why not.
//! 2. **Caller streams**, opened by the relay: the caller's address in a
//! PROXY protocol version 2 header, then the caller's own encrypted
//! bytes.
//! 3. **Control streams**, opened by the app: one request, one reply.
//!
//! ```text
//! GOAL: an app proves it holds the key for its name on every connection,
//! so that neither a stranger nor a replayed recording of an old
//! proof can take the name's line; and the app is told the caller's
//! real address in a form no caller can forge.
//! SOURCE: WB-relay-2 (the line and its proof), WB-relay-6 (the caller's
//! address); RFC 8032 (Ed25519), RFC 5705 and RFC 8446 section 7.5
//! (TLS exporters), the PROXY protocol specification version 2.
//! INVARIANTS:
//! 1. The proof signs the line's own TLS exporter value, a fresh 32-byte
//! nonce, the name and the claim flag: it is good for one TLS
//! session and no other, and no relay or stranger who sat in the
//! middle of another session can use it.
//! 2. Every frame is at most 2 048 bytes and every field has a length:
//! a stranger cannot make the relay read or hold more.
//! 3. The caller-address header is written by the relay before any
//! byte of the caller's, and parses only in its exact form.
//! SCENARIOS:
//! 1. A proof made for one session fails on another session's exporter,
//! on another nonce, with another name, and with the claim flag
//! flipped.
//! 2. A PROXY header for IPv4 and for IPv6 round-trips; a header with
//! trailing bytes, a wrong signature, or a wrong length is refused.
//! ```
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use ring::rand::SecureRandom;
use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey};
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use crate::names::Name;
/// The protocol version in every handshake message.
pub const VERSION: u8 = 1;
/// The most a handshake or control frame may carry.
pub const MAX_FRAME: usize = 2048;
/// The TLS exporter label the proof binds to.
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-wanderbooks-relay-line-v1";
const PROOF_CONTEXT: &[u8] = b"wanderbooks-relay/line/v1\0";
/// The relay's opening message on a new line.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Challenge {
/// Protocol version.
pub v: u8,
/// 32 fresh random bytes, hex.
pub nonce: String,
}
/// The app's answer: who it is, and the proof.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Hello {
/// Protocol version.
pub v: u8,
/// The four-word name.
pub name: String,
/// The Ed25519 public key (32 bytes), hex.
pub public_key: String,
/// True to claim the name if nobody has it. False to reconnect.
pub claim: bool,
/// The signature (64 bytes), hex, over [`proof_message`].
pub signature: String,
}
/// Why the relay turned a line away.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Refusal {
/// The name is already held by another key.
Taken,
/// Reserved. A reconnect for a name nobody has claimed is answered
/// [`Refusal::BadProof`], the same as a wrong key and a block, so a
/// caller without the key learns nothing about which names exist.
UnknownName,
/// The proof did not verify, or the key is not the name's, or there is
/// no such name, or the name is blocked and this is not its key: one
/// answer for all of them.
BadProof,
/// The name is blocked by the operator, said only to the holder of its
/// key.
Blocked,
/// The relay is busy; try again later.
Busy,
/// Too many new names, or too many tries, from here or in total.
RateLimited,
/// The message was malformed or of another version.
BadRequest,
}
/// The relay's verdict on a [`Hello`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Verdict {
/// True: the line is up.
pub ok: bool,
/// Why not, when not.
pub refusal: Option<Refusal>,
/// True when this connection claimed the name for the first time.
pub claimed: bool,
/// The most caller streams the relay will open on this line at once.
pub max_streams: u32,
}
/// What an app asks of the relay on a control stream. The name is never
/// in a request: it is the line's, proven at the handshake.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum Request {
/// A keep-alive; the reply shows the relay is there.
Ping,
/// Publish this ACME DNS-01 proof value at `_acme-challenge.<name>`.
PublishTxt {
/// The 43-character base64url value.
value: String,
},
/// Remove this app's proof records.
ClearTxt,
/// The certificate authorities to try, in order.
Authorities,
}
/// A certificate authority the app may try, and how to reach it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Authority {
/// A short stable id (`letsencrypt`).
pub id: String,
/// The ACME directory address (RFC 8555).
pub directory: String,
/// True when the authority requires an external account binding.
pub needs_binding: bool,
/// True when the app can use this authority now: it needs no binding,
/// or the relay has one for this app. An authority that needs a
/// binding the relay has none for is listed (so the app can say what
/// it is waiting for) and is not usable yet.
#[serde(default = "yes")]
pub usable: bool,
/// The binding credential for this app, when one is needed and the
/// relay has one for it.
pub binding: Option<Binding>,
}
fn yes() -> bool {
true
}
/// An external account binding credential (RFC 8555 section 7.3.4).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
/// The key identifier.
pub kid: String,
/// The HMAC key, base64url.
pub hmac_key: String,
}
/// The reply to a [`Request`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Response {
/// True when the request was done.
pub ok: bool,
/// A short reason when not.
pub error: Option<String>,
/// The list, for [`Request::Authorities`].
pub authorities: Option<Vec<Authority>>,
}
/// A frame could not be read or written.
#[derive(Debug, thiserror::Error)]
pub enum FrameError {
/// The peer closed, or the stream failed.
#[error("i/o: {0}")]
Io(#[from] std::io::Error),
/// The frame is longer than [`MAX_FRAME`].
#[error("frame too long")]
TooLong,
/// The frame is not the message it should be.
#[error("bad message: {0}")]
Bad(#[from] serde_json::Error),
}
/// Read one frame: a two-byte length (at most [`MAX_FRAME`]), then that
/// many bytes of JSON.
pub async fn read_frame<R, T>(r: &mut R) -> Result<T, FrameError>
where
R: AsyncRead + Unpin,
T: for<'de> Deserialize<'de>,
{
let mut len = [0u8; 2];
r.read_exact(&mut len).await?;
let len = usize::from(u16::from_be_bytes(len));
if len > MAX_FRAME {
return Err(FrameError::TooLong);
}
let mut buf = vec![0u8; len];
r.read_exact(&mut buf).await?;
Ok(serde_json::from_slice(&buf)?)
}
/// Write one frame.
pub async fn write_frame<W, T>(w: &mut W, msg: &T) -> Result<(), FrameError>
where
W: AsyncWrite + Unpin,
T: Serialize,
{
let body = serde_json::to_vec(msg)?;
if body.len() > MAX_FRAME {
return Err(FrameError::TooLong);
}
let mut out = Vec::with_capacity(2 + body.len());
out.extend(
u16::try_from(body.len())
.map_err(|_| FrameError::TooLong)?
.to_be_bytes(),
);
out.extend(body);
w.write_all(&out).await?;
w.flush().await?;
Ok(())
}
/// Lower-case hex.
pub fn hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for b in bytes {
out.push(char::from(DIGITS[usize::from(b >> 4)]));
out.push(char::from(DIGITS[usize::from(b & 15)]));
}
out
}
/// Decode exactly `N` bytes of hex, or `None`.
pub fn unhex<const N: usize>(text: &str) -> Option<[u8; N]> {
let bytes = text.as_bytes();
if bytes.len() != N * 2 {
return None;
}
let mut out = [0u8; N];
let (pairs, _) = bytes.as_chunks::<2>();
for (slot, [h, l]) in out.iter_mut().zip(pairs) {
let hi = char::from(*h).to_digit(16)?;
let lo = char::from(*l).to_digit(16)?;
*slot = u8::try_from(hi * 16 + lo).ok()?;
}
Some(out)
}
/// 32 random bytes.
pub fn random32() -> [u8; 32] {
let mut b = [0u8; 32];
if ring::rand::SystemRandom::new().fill(&mut b).is_err() {
// The system generator failing is not recoverable.
panic!("the system random number generator failed");
}
b
}
/// What the app signs: the context, this TLS session's exporter value,
/// the relay's nonce, the name and the claim flag.
pub fn proof_message(exporter: &[u8; 32], nonce: &[u8; 32], name: &Name, claim: bool) -> Vec<u8> {
let text = name.to_string();
let mut m = Vec::with_capacity(PROOF_CONTEXT.len() + 32 + 32 + 2 + text.len());
m.extend(PROOF_CONTEXT);
m.extend(exporter);
m.extend(nonce);
m.push(u8::from(claim));
// A name is under 255 bytes by construction (four words of at most 11).
m.push(u8::try_from(text.len()).unwrap_or(u8::MAX));
m.extend(text.as_bytes());
m
}
/// Verify an Ed25519 signature.
pub fn verify(public_key: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
UnparsedPublicKey::new(&ED25519, public_key)
.verify(message, signature)
.is_ok()
}
/// An app's own key: it owns the name.
pub struct AppKey(Ed25519KeyPair);
impl AppKey {
/// A new key, and its PKCS#8 encoding to keep.
pub fn generate() -> (Self, Vec<u8>) {
let rng = ring::rand::SystemRandom::new();
let Ok(doc) = Ed25519KeyPair::generate_pkcs8(&rng) else {
// The system generator failing is not recoverable.
panic!("the system random number generator failed");
};
let bytes = doc.as_ref().to_vec();
let key = Self::from_pkcs8(&bytes).unwrap_or_else(|| unreachable!("a fresh key parses"));
(key, bytes)
}
/// A key from its PKCS#8 encoding.
pub fn from_pkcs8(bytes: &[u8]) -> Option<Self> {
Ed25519KeyPair::from_pkcs8(bytes).ok().map(AppKey)
}
/// The public key, 32 bytes.
pub fn public_key(&self) -> [u8; 32] {
let mut out = [0u8; 32];
out.copy_from_slice(self.0.public_key().as_ref());
out
}
/// Sign.
pub fn sign(&self, message: &[u8]) -> [u8; 64] {
let mut out = [0u8; 64];
out.copy_from_slice(self.0.sign(message).as_ref());
out
}
}
const PP2_SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
/// The caller's address and the one it reached, as the relay saw them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Caller {
/// Who connected to the relay.
pub source: SocketAddr,
/// The relay address they connected to.
pub destination: SocketAddr,
}
/// An IPv4-mapped IPv6 address is the IPv4 address.
fn unmap(addr: SocketAddr) -> SocketAddr {
match addr {
SocketAddr::V6(v6) => match v6.ip().to_ipv4_mapped() {
Some(v4) => SocketAddr::new(IpAddr::V4(v4), v6.port()),
None => addr,
},
v4 => v4,
}
}
impl Caller {
/// The PROXY protocol version 2 header for this caller (28 bytes for
/// IPv4, 52 for IPv6), with no extensions.
pub fn encode(&self) -> Vec<u8> {
let (src, dst) = (unmap(self.source), unmap(self.destination));
let mut out = Vec::with_capacity(52);
out.extend(PP2_SIGNATURE);
out.push(0x21); // version 2, PROXY
match (src, dst) {
(SocketAddr::V4(s), SocketAddr::V4(d)) => {
out.push(0x11); // TCP over IPv4
out.extend(12u16.to_be_bytes());
out.extend(s.ip().octets());
out.extend(d.ip().octets());
out.extend(s.port().to_be_bytes());
out.extend(d.port().to_be_bytes());
}
(s, d) => {
let (s6, d6) = (to_v6(s), to_v6(d));
out.push(0x21); // TCP over IPv6
out.extend(36u16.to_be_bytes());
out.extend(s6.0.octets());
out.extend(d6.0.octets());
out.extend(s6.1.to_be_bytes());
out.extend(d6.1.to_be_bytes());
}
}
out
}
/// Read a header from the front of a stream. Exactly the forms
/// [`Caller::encode`] writes are accepted.
pub async fn read<R: AsyncRead + Unpin>(r: &mut R) -> Result<Caller, FrameError> {
let mut head = [0u8; 16];
r.read_exact(&mut head).await?;
let bad = || FrameError::Io(std::io::ErrorKind::InvalidData.into());
if head[..12] != PP2_SIGNATURE || head[12] != 0x21 {
return Err(bad());
}
let len = usize::from(u16::from_be_bytes([head[14], head[15]]));
match (head[13], len) {
(0x11, 12) => {
let mut b = [0u8; 12];
r.read_exact(&mut b).await?;
Ok(Caller {
source: SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(b[0], b[1], b[2], b[3])),
u16::from_be_bytes([b[8], b[9]]),
),
destination: SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(b[4], b[5], b[6], b[7])),
u16::from_be_bytes([b[10], b[11]]),
),
})
}
(0x21, 36) => {
let mut b = [0u8; 36];
r.read_exact(&mut b).await?;
let ip = |at: usize| {
let mut o = [0u8; 16];
o.copy_from_slice(&b[at..at + 16]);
IpAddr::V6(Ipv6Addr::from(o))
};
Ok(Caller {
source: SocketAddr::new(ip(0), u16::from_be_bytes([b[32], b[33]])),
destination: SocketAddr::new(ip(16), u16::from_be_bytes([b[34], b[35]])),
})
}
_ => Err(bad()),
}
}
}
fn to_v6(addr: SocketAddr) -> (Ipv6Addr, u16) {
match addr {
SocketAddr::V4(v4) => (v4.ip().to_ipv6_mapped(), v4.port()),
SocketAddr::V6(v6) => (*v6.ip(), v6.port()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_round_trips_and_refuses_the_wrong_length() {
let b = random32();
assert_eq!(unhex::<32>(&hex(&b)), Some(b));
assert_eq!(unhex::<32>("00"), None);
assert_eq!(unhex::<2>("zz00"), None);
assert_eq!(unhex::<2>("+f00"), None);
}
#[test]
fn a_proof_holds_for_one_session_and_nothing_else() {
let (key, _) = AppKey::generate();
let name = Name::parse("ledger-accrual-tally-mint").unwrap();
let other = Name::parse("ledger-accrual-tally-vault").unwrap();
let (exporter, nonce) = (random32(), random32());
let sig = key.sign(&proof_message(&exporter, &nonce, &name, true));
let pk = key.public_key();
assert!(verify(
&pk,
&proof_message(&exporter, &nonce, &name, true),
&sig
));
assert!(!verify(
&pk,
&proof_message(&random32(), &nonce, &name, true),
&sig
));
assert!(!verify(
&pk,
&proof_message(&exporter, &random32(), &name, true),
&sig
));
assert!(!verify(
&pk,
&proof_message(&exporter, &nonce, &other, true),
&sig
));
assert!(!verify(
&pk,
&proof_message(&exporter, &nonce, &name, false),
&sig
));
let (stranger, _) = AppKey::generate();
assert!(!verify(
&stranger.public_key(),
&proof_message(&exporter, &nonce, &name, true),
&sig
));
}
#[tokio::test]
async fn a_caller_header_round_trips_for_v4_and_v6_and_nothing_else_parses() {
let v4 = Caller {
source: "203.0.113.9:51000".parse().unwrap(),
destination: "198.51.100.1:443".parse().unwrap(),
};
let v6 = Caller {
source: "[2001:db8::7]:51000".parse().unwrap(),
destination: "[2001:db8::1]:443".parse().unwrap(),
};
assert_eq!(v4.encode().len(), 28);
assert_eq!(v6.encode().len(), 52);
for c in [v4, v6] {
let bytes = c.encode();
assert_eq!(Caller::read(&mut &bytes[..]).await.unwrap(), c);
}
// A mapped IPv4 caller is written as IPv4.
let mapped = Caller {
source: "[::ffff:203.0.113.9]:51000".parse().unwrap(),
destination: "198.51.100.1:443".parse().unwrap(),
};
assert_eq!(mapped.encode(), v4.encode());
let good = v4.encode();
for at in 0..good.len() {
let mut cut = good.clone();
cut.truncate(at);
assert!(Caller::read(&mut &cut[..]).await.is_err(), "cut at {at}");
}
let mut wrong = good.clone();
wrong[0] = b'G';
assert!(Caller::read(&mut &wrong[..]).await.is_err());
let mut wrong_len = good.clone();
wrong_len[15] = 13;
assert!(Caller::read(&mut &wrong_len[..]).await.is_err());
assert!(
Caller::read(&mut &b"GET / HTTP/1.1\r\n\r\n"[..])
.await
.is_err()
);
}
#[tokio::test]
async fn frames_are_bounded() {
let mut buf = Vec::new();
write_frame(&mut buf, &Request::Ping).await.unwrap();
let back: Request = read_frame(&mut &buf[..]).await.unwrap();
assert!(matches!(back, Request::Ping));
let long = [0xffu8, 0xff];
assert!(matches!(
read_frame::<_, Request>(&mut &long[..]).await,
Err(FrameError::TooLong)
));
let junk = [0u8, 3, b'n', b'o', b'!'];
assert!(matches!(
read_frame::<_, Request>(&mut &junk[..]).await,
Err(FrameError::Bad(_))
));
let unknown = br#"{"op":"publish_txt","value":"x","extra":1}"#;
let mut framed = u16::try_from(unknown.len()).unwrap().to_be_bytes().to_vec();
framed.extend(unknown);
assert!(read_frame::<_, Request>(&mut &framed[..]).await.is_err());
}
}
+633
View File
@@ -0,0 +1,633 @@
//! The registry: the one small durable table (D-85).
//!
//! It holds, per name, the app's public key, when the name was claimed,
//! whether the operator has blocked it, and when it first published a
//! proof record (the one moment a name costs the certificate authority's
//! weekly budget). Nothing else about an app is kept anywhere: not an
//! address, not a label, not a log of connections. A claim, and the limit
//! on new names, are one transaction; so is a first publish and the
//! certificate budget.
//!
//! SQLite is driven from one thread of its own, through a bounded queue,
//! so a slow disk makes the relay say "busy" and never makes it hold more.
//!
//! ```text
//! GOAL: a name belongs to the first key that claims it and to no other,
//! for as long as the registry file lives, however many connections
//! race for it and however often the relay restarts.
//! SOURCE: WB-relay-4 (the registry), D-85 in plan/p15-app-and-relay.md.
//! INVARIANTS:
//! 1. A name has at most one key: a second claim, with the same key or
//! another, never changes the row.
//! 2. A claim is durable before it is acknowledged (synchronous = FULL).
//! 3. At most `max_new` names are claimed in any `window`, counted from
//! the rows' own creation times, so a restart does not reset it.
//! 4. The queue to the database thread is bounded: past it a request
//! is refused as busy, not held.
//! 5. A name is charged to the certificate budget once, the first time
//! it publishes; at most `max` names are charged in any `window`,
//! counted from the rows' own charge times, so a restart does not
//! reset it, and a name already charged is never charged again.
//! SCENARIOS:
//! 1. Two claims of one name with different keys: one wins, the other
//! sees `Exists`.
//! 2. A claim, a restart (reopen), a lookup: the key is still there.
//! 3. The window limit counts rows made before a reopen.
//! 4. Three names first publish under a budget of two: the third is
//! refused, the first renews without a charge, and a reopen keeps
//! the count.
//! ```
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use rusqlite::{Connection, OptionalExtension, params};
use tokio::sync::{mpsc, oneshot};
use crate::names::Name;
/// What the registry holds for a name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Entry {
/// The app's Ed25519 public key.
pub public_key: [u8; 32],
/// True when the operator has blocked the name.
pub blocked: bool,
/// True when the name has been charged to the certificate budget: it
/// has published a proof record before.
pub published: bool,
}
/// How a first publish ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Charged {
/// The name had been charged before: a renewal, free.
Already,
/// This publish charged the budget.
New,
/// The budget for the window is spent.
LimitReached,
/// No such name.
NoSuchName,
}
/// How a claim ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Claimed {
/// This claim made the row.
New,
/// The name was already held, by this entry.
Exists(Entry),
/// Too many names were claimed in the window.
LimitReached,
}
/// Why the registry could not answer.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RegistryError {
/// The queue to the database is full.
#[error("the registry is busy")]
Busy,
/// The database thread is gone.
#[error("the registry is closed")]
Closed,
/// The database refused.
#[error("registry database: {0}")]
Db(String),
}
type Reply<T> = oneshot::Sender<Result<T, RegistryError>>;
enum Cmd {
Lookup(String, Reply<Option<Entry>>),
Claim {
name: String,
key: [u8; 32],
now: i64,
window_secs: i64,
max_new: u32,
reply: Reply<Claimed>,
},
SetBlocked(String, bool, Reply<bool>),
Count(Reply<u64>),
Charge {
name: String,
now: i64,
window_secs: i64,
max: u32,
reply: Reply<Charged>,
},
Blocked(Reply<Vec<String>>),
}
/// A handle to the registry. Clones share one database thread.
#[derive(Clone)]
pub struct Registry {
tx: mpsc::Sender<Cmd>,
}
fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
}
fn db(e: rusqlite::Error) -> RegistryError {
RegistryError::Db(e.to_string())
}
impl Registry {
/// Open (or create) the registry file, and start its thread. `queue`
/// is how many requests may wait.
pub fn open(path: &Path, queue: usize) -> Result<Self, RegistryError> {
let conn = Connection::open(path).map_err(db)?;
conn.execute_batch(
"PRAGMA journal_mode = WAL;
PRAGMA synchronous = FULL;
PRAGMA busy_timeout = 5000;
CREATE TABLE IF NOT EXISTS apps (
name TEXT PRIMARY KEY,
public_key BLOB NOT NULL CHECK (length(public_key) = 32),
created INTEGER NOT NULL,
blocked INTEGER NOT NULL DEFAULT 0,
first_publish INTEGER
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS apps_created ON apps (created);",
)
.map_err(db)?;
// A file made before the column existed gets it, empty: its names
// have not been charged, which is the generous way to be wrong.
let has: i64 = conn
.query_row(
"SELECT count(*) FROM pragma_table_info('apps') WHERE name = 'first_publish'",
[],
|r| r.get(0),
)
.map_err(db)?;
if has == 0 {
conn.execute_batch("ALTER TABLE apps ADD COLUMN first_publish INTEGER")
.map_err(db)?;
}
conn.execute_batch(
"CREATE INDEX IF NOT EXISTS apps_first_publish ON apps (first_publish);
CREATE INDEX IF NOT EXISTS apps_blocked ON apps (blocked) WHERE blocked = 1;",
)
.map_err(db)?;
let (tx, mut rx) = mpsc::channel::<Cmd>(queue.max(1));
std::thread::Builder::new()
.name("relay-registry".into())
.spawn(move || {
while let Some(cmd) = rx.blocking_recv() {
serve(&conn, cmd);
}
})
.map_err(|e| RegistryError::Db(e.to_string()))?;
Ok(Registry { tx })
}
async fn ask<T>(&self, make: impl FnOnce(Reply<T>) -> Cmd) -> Result<T, RegistryError> {
let (reply, answer) = oneshot::channel();
self.tx.try_send(make(reply)).map_err(|e| match e {
mpsc::error::TrySendError::Full(_) => RegistryError::Busy,
mpsc::error::TrySendError::Closed(_) => RegistryError::Closed,
})?;
answer.await.map_err(|_| RegistryError::Closed)?
}
/// The entry for a name, if claimed.
pub async fn lookup(&self, name: &Name) -> Result<Option<Entry>, RegistryError> {
self.ask(|r| Cmd::Lookup(name.to_string(), r)).await
}
/// Claim a name for a key, unless more than `max_new` names were
/// claimed within `window` already.
pub async fn claim(
&self,
name: &Name,
key: [u8; 32],
window: std::time::Duration,
max_new: u32,
) -> Result<Claimed, RegistryError> {
self.ask(|reply| Cmd::Claim {
name: name.to_string(),
key,
now: unix_now(),
window_secs: i64::try_from(window.as_secs()).unwrap_or(i64::MAX),
max_new,
reply,
})
.await
}
/// Block or unblock a name; false when there is no such name.
pub async fn set_blocked(&self, name: &Name, blocked: bool) -> Result<bool, RegistryError> {
self.ask(|r| Cmd::SetBlocked(name.to_string(), blocked, r))
.await
}
/// How many names are claimed.
pub async fn count(&self) -> Result<u64, RegistryError> {
self.ask(Cmd::Count).await
}
/// Charge `name` to the certificate budget if it has not been: the
/// first time a name publishes a proof record. At most `max` names are
/// charged in any `window`. A name already charged is `Already`, and
/// costs nothing.
pub async fn charge_publish(
&self,
name: &Name,
window: std::time::Duration,
max: u32,
) -> Result<Charged, RegistryError> {
self.ask(|reply| Cmd::Charge {
name: name.to_string(),
now: unix_now(),
window_secs: i64::try_from(window.as_secs()).unwrap_or(i64::MAX),
max,
reply,
})
.await
}
/// The names the operator has blocked (at most 100 000 are returned).
pub async fn blocked_names(&self) -> Result<Vec<Name>, RegistryError> {
let names = self.ask(Cmd::Blocked).await?;
Ok(names.iter().filter_map(|n| Name::parse(n).ok()).collect())
}
}
fn entry_of(key: Vec<u8>, blocked: i64, first_publish: Option<i64>) -> Option<Entry> {
Some(Entry {
public_key: key.try_into().ok()?,
blocked: blocked != 0,
published: first_publish.is_some(),
})
}
fn lookup(conn: &Connection, name: &str) -> Result<Option<Entry>, RegistryError> {
let row: Option<(Vec<u8>, i64, Option<i64>)> = conn
.query_row(
"SELECT public_key, blocked, first_publish FROM apps WHERE name = ?1",
params![name],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()
.map_err(db)?;
match row {
None => Ok(None),
Some((key, blocked, first)) => entry_of(key, blocked, first)
.map(Some)
.ok_or_else(|| RegistryError::Db("a stored key is not 32 bytes".into())),
}
}
fn serve(conn: &Connection, cmd: Cmd) {
match cmd {
Cmd::Lookup(name, reply) => {
let _ = reply.send(lookup(conn, &name));
}
Cmd::Count(reply) => {
let n = conn
.query_row("SELECT count(*) FROM apps", [], |r| r.get::<_, i64>(0))
.map(|n| u64::try_from(n).unwrap_or(0))
.map_err(db);
let _ = reply.send(n);
}
Cmd::SetBlocked(name, blocked, reply) => {
let r = conn
.execute(
"UPDATE apps SET blocked = ?2 WHERE name = ?1",
params![name, i64::from(blocked)],
)
.map(|n| n > 0)
.map_err(db);
let _ = reply.send(r);
}
Cmd::Claim {
name,
key,
now,
window_secs,
max_new,
reply,
} => {
let _ = reply.send(claim(conn, &name, key, now, window_secs, max_new));
}
Cmd::Charge {
name,
now,
window_secs,
max,
reply,
} => {
let _ = reply.send(charge(conn, &name, now, window_secs, max));
}
Cmd::Blocked(reply) => {
let r = (|| {
let mut st = conn
.prepare("SELECT name FROM apps WHERE blocked = 1 LIMIT 100000")
.map_err(db)?;
st.query_map([], |r| r.get::<_, String>(0))
.map_err(db)?
.collect::<Result<Vec<_>, _>>()
.map_err(db)
})();
let _ = reply.send(r);
}
}
}
fn charge(
conn: &Connection,
name: &str,
now: i64,
window_secs: i64,
max: u32,
) -> Result<Charged, RegistryError> {
conn.execute_batch("BEGIN IMMEDIATE").map_err(db)?;
let result = (|| {
let Some(e) = lookup(conn, name)? else {
return Ok(Charged::NoSuchName);
};
if e.published {
return Ok(Charged::Already);
}
let recent: i64 = conn
.query_row(
"SELECT count(*) FROM apps WHERE first_publish > ?1",
params![now.saturating_sub(window_secs)],
|r| r.get(0),
)
.map_err(db)?;
if recent >= i64::from(max) {
return Ok(Charged::LimitReached);
}
conn.execute(
"UPDATE apps SET first_publish = ?2 WHERE name = ?1",
params![name, now],
)
.map_err(db)?;
Ok(Charged::New)
})();
match result {
Ok(c) => {
conn.execute_batch("COMMIT").map_err(db)?;
Ok(c)
}
Err(e) => {
let _ = conn.execute_batch("ROLLBACK");
Err(e)
}
}
}
fn claim(
conn: &Connection,
name: &str,
key: [u8; 32],
now: i64,
window_secs: i64,
max_new: u32,
) -> Result<Claimed, RegistryError> {
// One immediate transaction: the count and the insert are one step.
conn.execute_batch("BEGIN IMMEDIATE").map_err(db)?;
let result = (|| {
if let Some(e) = lookup(conn, name)? {
return Ok(Claimed::Exists(e));
}
let recent: i64 = conn
.query_row(
"SELECT count(*) FROM apps WHERE created > ?1",
params![now.saturating_sub(window_secs)],
|r| r.get(0),
)
.map_err(db)?;
if recent >= i64::from(max_new) {
return Ok(Claimed::LimitReached);
}
conn.execute(
"INSERT INTO apps (name, public_key, created, blocked) VALUES (?1, ?2, ?3, 0)",
params![name, key.as_slice(), now],
)
.map_err(db)?;
Ok(Claimed::New)
})();
match result {
Ok(c) => {
conn.execute_batch("COMMIT").map_err(db)?;
Ok(c)
}
Err(e) => {
let _ = conn.execute_batch("ROLLBACK");
Err(e)
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
const DAY: Duration = Duration::from_secs(86_400);
fn name(s: &str) -> Name {
Name::parse(s).unwrap()
}
#[tokio::test]
async fn the_first_claim_wins_and_the_row_never_changes() {
let dir = tempfile::tempdir().unwrap();
let reg = Registry::open(&dir.path().join("r.db"), 16).unwrap();
let n = name("ledger-accrual-tally-mint");
assert_eq!(reg.lookup(&n).await.unwrap(), None);
assert_eq!(reg.claim(&n, [1; 32], DAY, 10).await.unwrap(), Claimed::New);
let held = Entry {
public_key: [1; 32],
blocked: false,
published: false,
};
assert_eq!(
reg.claim(&n, [2; 32], DAY, 10).await.unwrap(),
Claimed::Exists(held)
);
assert_eq!(
reg.claim(&n, [1; 32], DAY, 10).await.unwrap(),
Claimed::Exists(held)
);
assert_eq!(reg.lookup(&n).await.unwrap(), Some(held));
assert_eq!(reg.count().await.unwrap(), 1);
}
#[tokio::test]
async fn racing_claims_have_one_winner() {
let dir = tempfile::tempdir().unwrap();
let reg = Registry::open(&dir.path().join("r.db"), 64).unwrap();
let n = name("ledger-accrual-tally-mint");
let mut tasks = Vec::new();
for i in 0..20u8 {
let reg = reg.clone();
tasks.push(tokio::spawn(async move {
reg.claim(&n, [i; 32], DAY, 100).await.unwrap()
}));
}
let mut wins = 0;
for t in tasks {
if t.await.unwrap() == Claimed::New {
wins += 1;
}
}
assert_eq!(wins, 1);
}
#[tokio::test]
async fn a_claim_outlives_a_restart_and_the_window_counts_old_rows() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("r.db");
{
let reg = Registry::open(&path, 16).unwrap();
for w in ["ledger-accrual-tally-mint", "ledger-accrual-tally-vault"] {
assert_eq!(
reg.claim(&name(w), [7; 32], DAY, 2).await.unwrap(),
Claimed::New
);
}
}
let reg = Registry::open(&path, 16).unwrap();
let held = reg
.lookup(&name("ledger-accrual-tally-mint"))
.await
.unwrap();
assert_eq!(held.map(|e| e.public_key), Some([7; 32]));
assert_eq!(
reg.claim(&name("ledger-accrual-tally-audit"), [8; 32], DAY, 2)
.await
.unwrap(),
Claimed::LimitReached
);
// The limit is for new names only: an existing one still answers.
assert!(matches!(
reg.claim(&name("ledger-accrual-tally-mint"), [8; 32], DAY, 2)
.await
.unwrap(),
Claimed::Exists(_)
));
// A window that has passed counts nothing.
assert_eq!(
reg.claim(
&name("ledger-accrual-tally-audit"),
[8; 32],
Duration::from_secs(0),
2
)
.await
.unwrap(),
Claimed::New
);
}
#[tokio::test]
async fn blocking_a_name_is_kept() {
let dir = tempfile::tempdir().unwrap();
let reg = Registry::open(&dir.path().join("r.db"), 16).unwrap();
let n = name("ledger-accrual-tally-mint");
assert!(!reg.set_blocked(&n, true).await.unwrap(), "no such name");
reg.claim(&n, [1; 32], DAY, 10).await.unwrap();
assert!(reg.set_blocked(&n, true).await.unwrap());
assert!(reg.lookup(&n).await.unwrap().unwrap().blocked);
}
#[tokio::test]
async fn the_certificate_budget_charges_a_name_once_and_survives_a_restart() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("r.db");
let week = Duration::from_secs(7 * 86_400);
let names = [
name("ledger-accrual-tally-mint"),
name("ledger-accrual-tally-vault"),
name("ledger-accrual-tally-audit"),
];
{
let reg = Registry::open(&path, 16).unwrap();
// Claiming costs the certificate budget nothing: all three claim.
for (i, n) in names.iter().enumerate() {
let key = [u8::try_from(i).unwrap(); 32];
assert_eq!(reg.claim(n, key, DAY, 100).await.unwrap(), Claimed::New);
}
assert_eq!(
reg.charge_publish(&names[0], week, 2).await.unwrap(),
Charged::New
);
assert_eq!(
reg.charge_publish(&names[1], week, 2).await.unwrap(),
Charged::New
);
assert_eq!(
reg.charge_publish(&names[2], week, 2).await.unwrap(),
Charged::LimitReached
);
// A renewal is free, even with the budget spent.
assert_eq!(
reg.charge_publish(&names[0], week, 2).await.unwrap(),
Charged::Already
);
}
let reg = Registry::open(&path, 16).unwrap();
assert_eq!(
reg.charge_publish(&names[2], week, 2).await.unwrap(),
Charged::LimitReached,
"the count outlives the restart"
);
assert!(reg.lookup(&names[0]).await.unwrap().unwrap().published);
assert!(!reg.lookup(&names[2]).await.unwrap().unwrap().published);
assert_eq!(
reg.charge_publish(&name("ledger-accrual-tally-seal"), week, 2)
.await
.unwrap(),
Charged::NoSuchName
);
// Once the window has passed the budget is free again.
assert_eq!(
reg.charge_publish(&names[2], Duration::from_secs(0), 2)
.await
.unwrap(),
Charged::New
);
}
#[tokio::test]
async fn the_blocked_names_are_listed_and_a_file_without_the_column_is_upgraded() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("r.db");
{
// The table as the first release made it.
let conn = Connection::open(&path).unwrap();
conn.execute_batch(
"CREATE TABLE apps (name TEXT PRIMARY KEY,
public_key BLOB NOT NULL CHECK (length(public_key) = 32),
created INTEGER NOT NULL, blocked INTEGER NOT NULL DEFAULT 0) WITHOUT ROWID;
INSERT INTO apps VALUES ('ledger-accrual-tally-mint', zeroblob(32), 1, 1);",
)
.unwrap();
}
let reg = Registry::open(&path, 16).unwrap();
let e = reg
.lookup(&name("ledger-accrual-tally-mint"))
.await
.unwrap()
.unwrap();
assert!(e.blocked && !e.published);
assert_eq!(
reg.blocked_names().await.unwrap(),
[name("ledger-accrual-tally-mint")]
);
assert!(
reg.set_blocked(&name("ledger-accrual-tally-mint"), false)
.await
.unwrap()
);
assert!(reg.blocked_names().await.unwrap().is_empty());
}
}
+979
View File
@@ -0,0 +1,979 @@
//! The relay itself: the router, the lines, the control streams, DNS.
//!
//! ```text
//! GOAL: route an assistant's TLS connection, by the server name in its
//! first message, down the line of the app that owns the name, and
//! forward the encrypted bytes both ways, holding no certificate
//! for any app and reading nothing; and keep every table, buffer
//! and queue bounded whoever connects.
//! SOURCE: WB-relay-1 (the router), WB-relay-2 (the line and its proof),
//! WB-relay-6 (the caller's address), WB-relay-7 (bounds), D-80.
//! INVARIANTS:
//! 1. The router never terminates TLS for an app's name: for a name
//! under the domain it reads only the ClientHello's server name and
//! then copies bytes. The only TLS the relay ends is the line's, for
//! its own host.
//! 2. An unknown name, an app that is not connected, an app over its
//! stream limit, and every malformed first message are closed in the
//! same way (a TLS alert, then close): a stranger cannot tell which.
//! 3. The caller's address is written by the relay, as the first bytes
//! on the stream, before any byte of the caller's; it is the socket's
//! peer address, never a value the caller sent.
//! 4. A name's line is replaced when its owner reconnects with a good
//! proof, and removed when it ends; the table holds one entry per
//! connected app and no more than `max_lines`.
//! 5. Every connection is counted against a global limit and a
//! per-address and per-network limit (an IPv4 address and /24, an
//! IPv6 /64 and /48; a mapped IPv4 address is its IPv4 address)
//! before any work is done for it, and a hello that is not complete
//! in `hello_timeout` is closed. When the pool of unfinished hellos
//! is full, an address that held a proven line lately may still use
//! a small reserve, so lines can reconnect through a flood.
//! 6. Per app: at most `streams_per_app` caller streams and
//! `control_streams_per_app` control streams, each with its own
//! timeouts; nothing queues without a bound.
//! 7. A line handshake holds a place for its address and its network
//! from the moment the router sees the relay's own host name until
//! the verdict, so one address cannot hold the pool of handshakes.
//! 8. A name that is not the caller's, unclaimed, or blocked, to a
//! caller who has not shown its key, is refused with one answer.
//! 9. A blocked name's live line is closed: at its next publish, and
//! within `block_check_ms` in any case.
//! 10. Claiming a name costs the registry's safety ceiling and the
//! per-prefix claim limits; the certificate authority's weekly
//! budget is charged when a name first publishes a proof record,
//! under per-prefix limits of its own.
//! SCENARIOS:
//! 1. An assistant connects with the app's name as server name; the app
//! sees the caller's address, then the assistant's ClientHello, and
//! TLS completes between them with the app's own certificate.
//! 2. An unknown name, and an offline app, are closed with the same
//! alert.
//! 3. A peer that connects and sends nothing, or one byte a second, is
//! closed at the hello timeout.
//! 4. A client holding the right key but a recorded old proof is
//! refused.
//! 5. An unclaimed name, a name held by another key and a blocked name
//! get the same refusal when the key is not the name's.
//! 6. The operator blocks a name whose line is up: the line is closed
//! and does not come back.
//! ```
use std::collections::HashMap;
use std::hash::{BuildHasher, RandomState};
use std::io;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream, UdpSocket};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinHandle;
use tokio::time::timeout;
use tokio_rustls::TlsAcceptor;
use tokio_util::compat::TokioAsyncReadCompatExt;
use tokio_util::sync::CancellationToken;
use crate::authorities::AuthorityList;
use crate::config::Config;
use crate::dns::{DnsService, TcpLimits};
use crate::front::{Activity, Front};
use crate::gate::{IpGate, IpPermit, KnownAddrs, PrefixLimit};
use crate::hello::{self, HelloError};
use crate::mux::{self, Mux, MuxLimits};
use crate::names::{HostKind, Name, Zone};
use crate::proto::{
self, Caller, Challenge, EXPORTER_LABEL, Hello, Refusal, Request, Response, VERSION, Verdict,
read_frame, write_frame,
};
use crate::registry::{Charged, Claimed, Registry};
use crate::splice::{self, SpliceLimits};
use crate::txt::{PublishError, TxtStore};
/// What happened, counted. Read by tests and printed by the binary.
#[derive(Default, Debug)]
pub struct Metrics {
/// Connections accepted by the router.
pub accepted: AtomicU64,
/// Connections dropped at once because a limit was reached.
pub shed: AtomicU64,
/// Hellos not finished in time.
pub hello_timeouts: AtomicU64,
/// First bytes that were not a ClientHello with a name.
pub bad_hello: AtomicU64,
/// Names that are not an app's, or apps that are not connected.
pub unknown_or_offline: AtomicU64,
/// Callers whose app was over its stream limit.
pub app_busy: AtomicU64,
/// Streams the app did not open in time, or refused.
pub open_failed: AtomicU64,
/// Callers spliced to an app.
pub routed: AtomicU64,
/// Line handshakes begun.
pub line_attempts: AtomicU64,
/// Lines refused for a bad or replayed proof.
pub refused_proof: AtomicU64,
/// Lines refused for any other reason.
pub refused_other: AtomicU64,
/// Names claimed for the first time.
pub claims: AtomicU64,
/// Names charged to the certificate budget (first publishes).
pub cert_charges: AtomicU64,
/// Lines closed because their name was blocked.
pub blocked_closed: AtomicU64,
/// Control requests served.
pub control: AtomicU64,
/// Lines up now.
pub lines_up: AtomicUsize,
}
impl Metrics {
/// Add one to a counter.
pub fn bump(counter: &AtomicU64) {
counter.fetch_add(1, Ordering::Relaxed);
}
}
/// An app's open line, as the router uses it.
#[derive(Clone)]
pub struct LineHandle {
id: u64,
mux: Mux,
streams: Arc<Semaphore>,
}
/// The routing table: name to open line, in memory, rebuilt as apps
/// reconnect. Sharded so no lock is held by many.
pub struct LineMap {
shards: Vec<Mutex<HashMap<Name, LineHandle>>>,
state: RandomState,
count: AtomicUsize,
next: AtomicU64,
max: usize,
}
impl LineMap {
fn new(max: usize) -> Self {
LineMap {
shards: (0..256).map(|_| Mutex::new(HashMap::new())).collect(),
state: RandomState::new(),
count: AtomicUsize::new(0),
next: AtomicU64::new(1),
max,
}
}
fn shard(&self, name: &Name) -> &Mutex<HashMap<Name, LineHandle>> {
// Truncating the hash to a shard index is the point.
&self.shards[(self.state.hash_one(name) as usize) % self.shards.len()]
}
fn lock<'a>(
m: &'a Mutex<HashMap<Name, LineHandle>>,
) -> std::sync::MutexGuard<'a, HashMap<Name, LineHandle>> {
m.lock().unwrap_or_else(|p| p.into_inner())
}
/// The line of `name`, if connected.
pub fn get(&self, name: &Name) -> Option<LineHandle> {
Self::lock(self.shard(name)).get(name).cloned()
}
/// Lines up.
pub fn len(&self) -> usize {
self.count.load(Ordering::Relaxed)
}
/// True when no line is up.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Whether a line for `name` could be taken now.
fn has_room(&self, name: &Name) -> bool {
self.len() < self.max || Self::lock(self.shard(name)).contains_key(name)
}
fn insert(&self, name: Name, handle: LineHandle) -> Result<(), ()> {
let mut shard = Self::lock(self.shard(&name));
let replaced = shard.contains_key(&name);
if !replaced && self.count.load(Ordering::Relaxed) >= self.max {
return Err(());
}
if let Some(old) = shard.insert(name, handle) {
old.mux.close(); // the owner reconnected: the old line is done
} else {
self.count.fetch_add(1, Ordering::Relaxed);
}
Ok(())
}
fn remove_if(&self, name: &Name, id: u64) {
let mut shard = Self::lock(self.shard(name));
if shard.get(name).is_some_and(|h| h.id == id) {
shard.remove(name);
self.count.fetch_sub(1, Ordering::Relaxed);
}
}
/// Close the line of `name`, if one is up. True when there was one.
fn close_name(&self, name: &Name) -> bool {
match self.get(name) {
Some(h) => {
h.mux.close();
true
}
None => false,
}
}
fn close_all(&self) {
for s in &self.shards {
for h in Self::lock(s).values() {
h.mux.close();
}
}
}
}
/// Everything the tasks share.
pub struct Shared {
/// The configuration.
pub cfg: Config,
zone: Zone,
/// Who is connected.
pub lines: LineMap,
/// The durable table.
pub registry: Registry,
/// Proof records.
pub txt: Arc<TxtStore>,
/// The certificate authorities offered.
pub authorities: Arc<AuthorityList>,
acceptor: TlsAcceptor,
/// What happened.
pub metrics: Metrics,
conn_permits: Arc<Semaphore>,
hello_permits: Arc<Semaphore>,
hello_reserve: Arc<Semaphore>,
handshake_permits: Arc<Semaphore>,
conn_gate: Arc<IpGate>,
pending_gate: Arc<IpGate>,
pending_net: Arc<IpGate>,
handshake_gate: Arc<IpGate>,
handshake_net: Arc<IpGate>,
known: KnownAddrs,
claim_ips: PrefixLimit,
cert_ips: PrefixLimit,
}
/// Everything a connection holds from accept until its hello is read.
struct Admission {
conn: OwnedSemaphorePermit,
conn_ip: IpPermit,
pending_ip: IpPermit,
pending_net: IpPermit,
hello: OwnedSemaphorePermit,
}
impl Shared {
/// Count a new connection from `ip` against every limit, or say no.
fn admit(&self, ip: std::net::IpAddr) -> Option<Admission> {
let conn = Arc::clone(&self.conn_permits).try_acquire_owned().ok()?;
let conn_ip = self.conn_gate.acquire(ip)?;
let pending_ip = self.pending_gate.acquire(ip)?;
let pending_net = self.pending_net.acquire(ip)?;
// The server name is not known until the hello is read, so the
// reserve is for who is calling: an address that held a proven
// line lately. It cannot be made by an address that never proved a
// name.
let hello = match Arc::clone(&self.hello_permits).try_acquire_owned() {
Ok(p) => p,
Err(_) if self.known.contains(ip, Instant::now()) => {
Arc::clone(&self.hello_reserve).try_acquire_owned().ok()?
}
Err(_) => return None,
};
Some(Admission {
conn,
conn_ip,
pending_ip,
pending_net,
hello,
})
}
}
/// A TLS fatal alert, `unrecognized_name`: the same for every refusal.
const ALERT: [u8; 7] = [0x15, 3, 3, 0, 2, 2, 112];
async fn refuse(tcp: &mut TcpStream) {
let _ = timeout(Duration::from_secs(1), async {
tcp.write_all(&ALERT).await?;
tcp.shutdown().await
})
.await;
}
/// Read the first TLS record. Memory grows only as bytes arrive.
async fn read_hello(tcp: &mut TcpStream) -> Result<(Vec<u8>, String), HelloError> {
let eof = || HelloError::Malformed;
let mut head = [0u8; hello::RECORD_HEADER];
tcp.read_exact(&mut head).await.map_err(|_| eof())?;
let len = hello::record_len(&head)?;
let total = hello::RECORD_HEADER + len;
let mut rec = Vec::with_capacity(hello::RECORD_HEADER + 1024);
rec.extend_from_slice(&head);
while rec.len() < total {
let at = rec.len();
let want = (total - at).min(4096);
rec.resize(at + want, 0);
let n = tcp.read(&mut rec[at..]).await.map_err(|_| eof())?;
rec.truncate(at + n);
if n == 0 {
return Err(eof());
}
}
let host = hello::server_name(&rec)?;
Ok((rec, host))
}
async fn handle(ctx: Arc<Shared>, mut tcp: TcpStream, peer: SocketAddr, admission: Admission) {
let Admission {
conn,
conn_ip,
pending_ip,
pending_net,
hello,
} = admission;
let _held = (conn, conn_ip);
let _ = tcp.set_nodelay(true);
let first = timeout(ctx.cfg.limits.hello_timeout(), read_hello(&mut tcp)).await;
drop((pending_ip, pending_net, hello));
let (record, host) = match first {
Err(_) => {
Metrics::bump(&ctx.metrics.hello_timeouts);
return;
}
Ok(Err(_)) => {
Metrics::bump(&ctx.metrics.bad_hello);
return;
}
Ok(Ok(x)) => x,
};
match ctx.zone.classify(&host) {
HostKind::Relay => serve_line(ctx, tcp, record, peer).await,
HostKind::App(name) => route(ctx, tcp, record, peer, name).await,
HostKind::Other => {
Metrics::bump(&ctx.metrics.unknown_or_offline);
refuse(&mut tcp).await;
}
}
}
async fn route(
ctx: Arc<Shared>,
mut tcp: TcpStream,
record: Vec<u8>,
peer: SocketAddr,
name: Name,
) {
let l = &ctx.cfg.limits;
let Some(line) = ctx.lines.get(&name) else {
Metrics::bump(&ctx.metrics.unknown_or_offline);
return refuse(&mut tcp).await;
};
let Ok(_stream_permit) = Arc::clone(&line.streams).try_acquire_owned() else {
Metrics::bump(&ctx.metrics.app_busy);
return refuse(&mut tcp).await;
};
let Ok(mut stream) = line.mux.open(l.open_stream_timeout()).await else {
Metrics::bump(&ctx.metrics.open_failed);
return refuse(&mut tcp).await;
};
let Ok(local) = tcp.local_addr() else {
return;
};
// The caller's address first, written by us from the socket, then the
// caller's own first bytes: nothing the caller sends can come before.
let mut first = Caller {
source: peer,
destination: local,
}
.encode();
first.extend_from_slice(&record);
drop(record);
let sent = timeout(l.write_stall(), async {
stream.write_all(&first).await?;
stream.flush().await
})
.await;
if !matches!(sent, Ok(Ok(()))) {
Metrics::bump(&ctx.metrics.open_failed);
return;
}
drop(first);
Metrics::bump(&ctx.metrics.routed);
let _ = splice::splice(
tcp,
stream,
SpliceLimits {
buffer: l.copy_buffer,
idle: l.stream_idle(),
stall: l.write_stall(),
min_rate: l.min_stream_bytes_per_sec,
max_age: l.stream_max_age(),
},
)
.await;
}
type LineTls = tokio_rustls::server::TlsStream<Front<TcpStream>>;
async fn serve_line(ctx: Arc<Shared>, tcp: TcpStream, record: Vec<u8>, peer: SocketAddr) {
let l = &ctx.cfg.limits;
let ip = peer.ip().to_canonical();
// The pool of handshakes, and this address's and network's share of
// it, held until the verdict: the hello's own permit is long gone, so
// without these one address could fill the pool by finishing a hello
// and stalling, over and over.
let (Ok(pool), Some(per_ip), Some(per_net)) = (
Arc::clone(&ctx.handshake_permits).try_acquire_owned(),
ctx.handshake_gate.acquire(ip),
ctx.handshake_net.acquire(ip),
) else {
Metrics::bump(&ctx.metrics.shed);
return;
};
let handshaking = (pool, per_ip, per_net);
Metrics::bump(&ctx.metrics.line_attempts);
let activity = Activity::new();
let front = Front::new(record, tcp, Some(Arc::clone(&activity)));
let up = timeout(l.handshake_timeout(), handshake(&ctx, front, ip)).await;
drop(handshaking);
let Ok(Ok((tls, name))) = up else { return };
ctx.known.mark(ip, Instant::now());
// A control request that finds the name blocked ends the line by this.
let kick = CancellationToken::new();
let streams = Arc::new(Semaphore::new(l.streams_per_app as usize));
let control = Arc::new(Semaphore::new(l.control_streams_per_app as usize));
let limits = MuxLimits {
// The permits, and a few over: a stream the app has closed may
// still be counted on its side for a moment after our permit is
// back, and yamux ends a line that is asked for a stream over its
// count. Every stream may hold a 256 KiB receive window, so the
// few are few.
max_streams: (l.streams_per_app + l.control_streams_per_app + STREAM_SLACK) as usize,
idle: l.line_idle(),
};
let ctx2 = Arc::clone(&ctx);
let kick2 = kick.clone();
let (mux, mut task) = mux::spawn(
tls.compat(),
yamux::Mode::Server,
limits,
Some(activity),
move |stream| {
if let Ok(permit) = Arc::clone(&control).try_acquire_owned() {
let ctx = Arc::clone(&ctx2);
let kick = kick2.clone();
tokio::spawn(async move {
serve_control(ctx, name, ip, kick, stream).await;
drop(permit);
});
}
},
);
let id = ctx.lines.next.fetch_add(1, Ordering::Relaxed);
let handle = LineHandle {
id,
mux: mux.clone(),
streams,
};
if ctx.lines.insert(name, handle).is_err() {
mux.close();
let _ = task.await;
return;
}
ctx.metrics.lines_up.fetch_add(1, Ordering::Relaxed);
tokio::select! {
_ = &mut task => {}
() = kick.cancelled() => {
mux.close();
let _ = task.await;
}
}
ctx.lines.remove_if(&name, id);
ctx.metrics.lines_up.fetch_sub(1, Ordering::Relaxed);
}
/// Streams over the permits that a line may count at once. Each can hold
/// a 256 KiB receive window; see `mux`.
const STREAM_SLACK: u32 = 4;
/// TLS, the challenge, the proof, the verdict.
async fn handshake(
ctx: &Arc<Shared>,
front: Front<TcpStream>,
ip: std::net::IpAddr,
) -> Result<(LineTls, Name), ()> {
let mut tls = ctx.acceptor.accept(front).await.map_err(|_| ())?;
let mut exporter = [0u8; 32];
tls.get_ref()
.1
.export_keying_material(&mut exporter[..], EXPORTER_LABEL, None)
.map_err(|_| ())?;
let nonce = proto::random32();
write_frame(
&mut tls,
&Challenge {
v: VERSION,
nonce: proto::hex(&nonce),
},
)
.await
.map_err(|_| ())?;
let hello: Hello = read_frame(&mut tls).await.map_err(|_| ())?;
let (verdict, name) = decide(ctx, &hello, &exporter, &nonce, ip).await;
write_frame(&mut tls, &verdict).await.map_err(|_| ())?;
match name {
Some(n) if verdict.ok => Ok((tls, n)),
_ => {
let _ = timeout(Duration::from_secs(1), tls.shutdown()).await;
Err(())
}
}
}
fn refused(why: Refusal) -> (Verdict, Option<Name>) {
(
Verdict {
ok: false,
refusal: Some(why),
claimed: false,
max_streams: 0,
},
None,
)
}
/// Is this hello a proof, for a name and key the registry will take?
async fn decide(
ctx: &Arc<Shared>,
hello: &Hello,
exporter: &[u8; 32],
nonce: &[u8; 32],
ip: std::net::IpAddr,
) -> (Verdict, Option<Name>) {
let l = &ctx.cfg.limits;
let (Ok(name), Some(key), Some(sig), true) = (
Name::parse(&hello.name),
proto::unhex::<32>(&hello.public_key),
proto::unhex::<64>(&hello.signature),
hello.v == VERSION,
) else {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::BadRequest);
};
// The proof first, before any database work: a stranger without a
// key never reaches the registry.
if !proto::verify(
&key,
&proto::proof_message(exporter, nonce, &name, hello.claim),
&sig,
) {
Metrics::bump(&ctx.metrics.refused_proof);
return refused(Refusal::BadProof);
}
let mut claimed = false;
match ctx.registry.lookup(&name).await {
Err(_) => {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::Busy);
}
Ok(Some(e)) => {
// The key first: only the holder of the name's key is told it
// is blocked. Anyone else gets what a wrong key gets, whether
// the name is blocked or not.
if e.public_key != key {
Metrics::bump(&ctx.metrics.refused_proof);
return refused(if hello.claim {
Refusal::Taken
} else {
Refusal::BadProof
});
}
if e.blocked {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::Blocked);
}
}
Ok(None) => {
if !hello.claim {
// The same answer as a wrong key: a caller with a key of
// its own cannot ask which names exist.
Metrics::bump(&ctx.metrics.refused_proof);
return refused(Refusal::BadProof);
}
if !ctx.claim_ips.allow(ip, Instant::now()) {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::RateLimited);
}
match ctx
.registry
.claim(&name, key, l.claim_window(), l.claims_per_window)
.await
{
Ok(Claimed::New) => {
claimed = true;
Metrics::bump(&ctx.metrics.claims);
}
Ok(Claimed::Exists(e)) if e.public_key == key && !e.blocked => {}
Ok(Claimed::Exists(_)) => {
Metrics::bump(&ctx.metrics.refused_proof);
return refused(Refusal::Taken);
}
Ok(Claimed::LimitReached) => {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::RateLimited);
}
Err(_) => {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::Busy);
}
}
}
}
if !ctx.lines.has_room(&name) {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::Busy);
}
(
Verdict {
ok: true,
refusal: None,
claimed,
max_streams: l.streams_per_app,
},
Some(name),
)
}
/// One request from an app on its own line. The name is the line's.
async fn serve_control(
ctx: Arc<Shared>,
name: Name,
ip: std::net::IpAddr,
kick: CancellationToken,
mut stream: mux::Stream,
) {
let _ = timeout(ctx.cfg.limits.control_timeout(), async {
let request: Request = read_frame(&mut stream).await.ok()?;
Metrics::bump(&ctx.metrics.control);
let response = match request {
Request::Ping => Response {
ok: true,
..Response::default()
},
Request::PublishTxt { value } => publish(&ctx, name, ip, &kick, &value).await,
Request::ClearTxt => {
ctx.txt.clear(&name);
Response {
ok: true,
..Response::default()
}
}
Request::Authorities => Response {
ok: true,
authorities: Some(ctx.authorities.for_app(&name)),
..Response::default()
},
};
write_frame(&mut stream, &response).await.ok()?;
let _ = stream.shutdown().await;
Some(())
})
.await;
}
fn failure(why: &str) -> Response {
Response {
ok: false,
error: Some(why.into()),
..Response::default()
}
}
/// Publish a proof record for the line's own name.
///
/// The name is asked of the registry on every publish: a blocked name's
/// line is closed here at its next publish, and by the sweep in any case.
/// The first publish of a name is the one that costs the certificate
/// authority's weekly budget, under the same per-prefix limits as a claim.
async fn publish(
ctx: &Arc<Shared>,
name: Name,
ip: std::net::IpAddr,
kick: &CancellationToken,
value: &str,
) -> Response {
if !crate::txt::is_proof_value(value) {
return failure("bad_value");
}
let l = &ctx.cfg.limits;
let entry = match ctx.registry.lookup(&name).await {
Ok(Some(e)) if !e.blocked => e,
Ok(_) => {
// Blocked (or gone): the line ends.
Metrics::bump(&ctx.metrics.blocked_closed);
kick.cancel();
return failure("blocked");
}
Err(_) => return failure("busy"),
};
if !entry.published {
if !ctx.cert_ips.allow(ip, Instant::now()) {
return failure("limit");
}
match ctx
.registry
.charge_publish(&name, l.cert_window(), l.cert_publishes_per_window)
.await
{
Ok(Charged::New) => Metrics::bump(&ctx.metrics.cert_charges),
Ok(Charged::Already) => {}
Ok(Charged::LimitReached) => return failure("limit"),
Ok(Charged::NoSuchName) => return failure("bad_value"),
Err(_) => return failure("busy"),
}
}
match ctx.txt.publish(name, value, Instant::now()) {
Ok(()) => Response {
ok: true,
..Response::default()
},
Err(PublishError::BadValue) => failure("bad_value"),
Err(PublishError::Limit) => failure("limit"),
}
}
async fn accept_loop(ctx: Arc<Shared>, listener: TcpListener, cancel: CancellationToken) {
loop {
let (tcp, peer) = tokio::select! {
() = cancel.cancelled() => return,
r = listener.accept() => match r {
Ok(x) => x,
Err(_) => {
// Out of descriptors, or a reset: do not spin.
tokio::time::sleep(Duration::from_millis(50)).await;
continue;
}
},
};
// An IPv4 caller on a dual-stack listener is `::ffff:a.b.c.d`:
// made canonical, it is its IPv4 address in every table.
let ip = peer.ip().to_canonical();
let Some(admission) = ctx.admit(ip) else {
Metrics::bump(&ctx.metrics.shed);
continue; // closed by drop, before any work
};
Metrics::bump(&ctx.metrics.accepted);
tokio::spawn(handle(Arc::clone(&ctx), tcp, peer, admission));
}
}
/// A running relay.
pub struct Relay {
shared: Arc<Shared>,
router: SocketAddr,
dns_udp: SocketAddr,
dns_tcp: SocketAddr,
cancel: CancellationToken,
tasks: Vec<JoinHandle<()>>,
}
impl Relay {
/// Bind and start the router and DNS. Port 0 picks a free port.
pub async fn start(
cfg: Config,
tls: Arc<rustls::ServerConfig>,
authorities: AuthorityList,
) -> io::Result<Relay> {
let l = cfg.limits.clone();
let zone = Zone::new(&cfg.domain, &cfg.relay_host);
let registry = Registry::open(&cfg.registry_path, l.registry_queue)
.map_err(|e| io::Error::other(e.to_string()))?;
let txt = Arc::new(TxtStore::new(
l.txt_ttl(),
l.txt_max_entries,
l.txt_per_name,
l.txt_publishes_per_hour,
));
let authorities = Arc::new(authorities);
let dns = Arc::new(
DnsService::new(
zone.clone(),
&cfg,
Arc::clone(&txt),
Arc::clone(&authorities),
)
.map_err(io::Error::other)?,
);
let router_listener = TcpListener::bind(cfg.router_addr).await?;
let router = router_listener.local_addr()?;
// TCP DNS on the same port number when it was asked for 0: a UDP
// port that is free is not always free for TCP, so ask again.
let mut attempt = 0;
let (udp, dns_udp, dns_tcp_listener, dns_tcp) = loop {
attempt += 1;
let udp = UdpSocket::bind(cfg.dns_addr).await?;
let dns_udp = udp.local_addr()?;
let tcp_addr = SocketAddr::new(cfg.dns_addr.ip(), dns_udp.port());
match TcpListener::bind(tcp_addr).await {
Ok(l) => {
let dns_tcp = l.local_addr()?;
break (udp, dns_udp, l, dns_tcp);
}
Err(e) if cfg.dns_addr.port() == 0 && attempt < 16 => {
let _ = e;
}
Err(e) => return Err(e),
}
};
let shared = Arc::new(Shared {
zone,
lines: LineMap::new(l.max_lines),
registry,
txt: Arc::clone(&txt),
authorities,
acceptor: TlsAcceptor::from(tls),
metrics: Metrics::default(),
conn_permits: Arc::new(Semaphore::new(l.max_connections)),
hello_permits: Arc::new(Semaphore::new(l.max_pending_hellos)),
hello_reserve: Arc::new(Semaphore::new(l.hello_reserve)),
handshake_permits: Arc::new(Semaphore::new(l.max_handshakes)),
conn_gate: IpGate::new(l.ip_slots, l.max_connections_per_ip),
pending_gate: IpGate::new(l.ip_slots, l.max_pending_per_ip),
pending_net: IpGate::net(l.ip_slots, l.max_pending_per_net),
handshake_gate: IpGate::new(l.ip_slots, l.max_handshakes_per_ip),
handshake_net: IpGate::net(l.ip_slots, l.max_handshakes_per_net),
known: KnownAddrs::new(l.known_bits, l.known_period()),
claim_ips: PrefixLimit::new(
l.ip_slots,
l.claims_per_ip,
l.claims_per_net,
l.claim_ip_window(),
),
cert_ips: PrefixLimit::new(
l.ip_slots,
l.cert_publishes_per_ip,
l.cert_publishes_per_net,
l.cert_window(),
),
cfg,
});
let cancel = CancellationToken::new();
let mut tasks = vec![
tokio::spawn(accept_loop(
Arc::clone(&shared),
router_listener,
cancel.clone(),
)),
tokio::spawn(crate::dns::serve_udp(
Arc::new(udp),
Arc::clone(&dns),
l.dns_qps_per_ip,
l.dns_qps_global,
l.ip_slots,
cancel.clone(),
)),
tokio::spawn(crate::dns::serve_tcp(
dns_tcp_listener,
dns,
TcpLimits {
max: l.dns_tcp_max,
per_ip: l.dns_tcp_per_ip,
timeout: l.dns_tcp_timeout(),
queries: 16,
},
l.ip_slots,
cancel.clone(),
)),
];
// Housekeeping: expired proof records, a changed authority list.
let (sweep_shared, sweep_cancel) = (Arc::clone(&shared), cancel.clone());
tasks.push(tokio::spawn(async move {
let mut tick = tokio::time::interval(Duration::from_secs(30));
loop {
tokio::select! {
() = sweep_cancel.cancelled() => return,
_ = tick.tick() => {
sweep_shared.txt.sweep(Instant::now());
let _ = sweep_shared.authorities.reload();
}
}
}
}));
// The operator blocks from another process, into the registry file;
// this is what makes a block reach a line that is already up.
let (block_shared, block_cancel) = (Arc::clone(&shared), cancel.clone());
tasks.push(tokio::spawn(async move {
let mut tick = tokio::time::interval(block_shared.cfg.limits.block_check());
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
tokio::select! {
() = block_cancel.cancelled() => return,
_ = tick.tick() => {
if let Ok(names) = block_shared.registry.blocked_names().await {
for n in names {
if block_shared.lines.close_name(&n) {
Metrics::bump(&block_shared.metrics.blocked_closed);
}
}
}
}
}
}
}));
Ok(Relay {
shared,
router,
dns_udp,
dns_tcp,
cancel,
tasks,
})
}
/// Where the router listens.
pub fn router_addr(&self) -> SocketAddr {
self.router
}
/// Where DNS listens over UDP.
pub fn dns_udp_addr(&self) -> SocketAddr {
self.dns_udp
}
/// Where DNS listens over TCP.
pub fn dns_tcp_addr(&self) -> SocketAddr {
self.dns_tcp
}
/// The shared state: tables and counters.
pub fn shared(&self) -> &Arc<Shared> {
&self.shared
}
/// Stop accepting, close every line, and wait for the listeners.
pub async fn shutdown(self) {
self.cancel.cancel();
self.shared.lines.close_all();
for t in self.tasks {
let _ = t.await;
}
}
}
+348
View File
@@ -0,0 +1,348 @@
//! Piping bytes both ways between a caller and a stream, with nothing
//! held back.
//!
//! Each direction has one buffer. It reads only when the buffer is empty
//! and writes it out before reading again, so a reader that is slow on
//! one side slows the writer on the other, and no more than one buffer
//! per direction ever sits in the relay. The relay reads none of it: the
//! bytes are TLS between the assistant and the app.
//!
//! ```text
//! GOAL: forward encrypted bytes both ways, with a slow, silent or
//! hostile end unable to make the relay hold more than two small
//! buffers or hold the connection past its limits.
//! SOURCE: WB-relay-1 (the router and its splice), WB-relay-7 (bounds).
//! INVARIANTS:
//! 1. At most `buffer` bytes are held per direction.
//! 2. A write of `n` bytes that is not finished within `stall` plus `n`
//! over `min_rate` bytes a second ends the connection: a reader
//! slower than that floor is closed, never buffered for. (A reader
//! that takes one byte just inside every stall would otherwise hold
//! the stream, and the receive window behind it, for hours.)
//! 3. A connection with no byte either way for `idle`, or alive for
//! `max_age`, is closed.
//! 4. A close in one direction (EOF) is passed on as a close of the
//! other side's write half; the other direction carries on until it
//! ends too.
//! SCENARIOS:
//! 1. Bytes written at either end arrive at the other, in order, and a
//! close at one end reaches the other.
//! 2. A peer that never reads: the splice ends after `stall`. A peer that
//! reads, but under `min_rate`, ends it too; one that keeps the pace
//! does not, however long the transfer.
//! 3. A peer that says nothing: the splice ends after `idle`.
//! ```
use std::io;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::time::{Instant, sleep, timeout};
/// The limits of one splice.
#[derive(Debug, Clone, Copy)]
pub struct SpliceLimits {
/// Buffer bytes per direction.
pub buffer: usize,
/// No byte either way for this long ends it.
pub idle: Duration,
/// The grace on every write: a write has at least this long.
pub stall: Duration,
/// The slowest a reader may take bytes, per second: a write of `n`
/// bytes has `stall` plus `n / min_rate` to finish.
pub min_rate: u32,
/// Its longest life.
pub max_age: Duration,
}
/// How a splice ended.
#[derive(Debug, PartialEq, Eq)]
pub enum End {
/// Both directions closed.
Done,
/// No traffic for the idle time.
Idle,
/// Lived to its maximum age.
MaxAge,
/// A write made no progress for the stall time.
Stalled,
/// An end failed.
Error(io::ErrorKind),
}
/// When bytes last moved, on tokio's clock (so tests can pause it).
struct Stamp {
base: Instant,
ms: AtomicU64,
}
impl Stamp {
fn new() -> Self {
Stamp {
base: Instant::now(),
ms: AtomicU64::new(0),
}
}
fn touch(&self) {
let ms = u64::try_from(self.base.elapsed().as_millis()).unwrap_or(u64::MAX);
self.ms.store(ms, Ordering::Relaxed);
}
fn quiet(&self) -> Duration {
let now = u64::try_from(self.base.elapsed().as_millis()).unwrap_or(u64::MAX);
Duration::from_millis(now.saturating_sub(self.ms.load(Ordering::Relaxed)))
}
}
/// How long a write of `n` bytes may take: the grace plus the floor rate.
fn write_deadline(stall: Duration, min_rate: u32, n: usize) -> Duration {
let secs = n as f64 / f64::from(min_rate.max(1));
stall.saturating_add(Duration::from_secs_f64(secs.min(86_400.0)))
}
async fn pump<R, W>(
from: &mut R,
to: &mut W,
buffer: usize,
stall: Duration,
min_rate: u32,
last: &Stamp,
) -> Result<(), End>
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
let mut buf = vec![0u8; buffer.max(1)];
loop {
let n = from
.read(&mut buf)
.await
.map_err(|e| End::Error(e.kind()))?;
if n == 0 {
// Pass the close on. A failure here only means the far end
// has already gone.
let _ = timeout(stall, to.shutdown()).await;
return Ok(());
}
last.touch();
match timeout(write_deadline(stall, min_rate, n), async {
to.write_all(&buf[..n]).await?;
to.flush().await
})
.await
{
Err(_) => return Err(End::Stalled),
Ok(Err(e)) => return Err(End::Error(e.kind())),
Ok(Ok(())) => last.touch(),
}
}
}
/// Splice `a` and `b` until both close or a limit is hit.
pub async fn splice<A, B>(a: A, b: B, limits: SpliceLimits) -> End
where
A: AsyncRead + AsyncWrite + Unpin,
B: AsyncRead + AsyncWrite + Unpin,
{
let (mut ar, mut aw) = tokio::io::split(a);
let (mut br, mut bw) = tokio::io::split(b);
let last = Stamp::new();
let both = async {
// The first failure ends both; a clean close in one direction
// lets the other carry on.
match tokio::try_join!(
pump(
&mut ar,
&mut bw,
limits.buffer,
limits.stall,
limits.min_rate,
&last
),
pump(
&mut br,
&mut aw,
limits.buffer,
limits.stall,
limits.min_rate,
&last
),
) {
Ok(((), ())) => End::Done,
Err(e) => e,
}
};
let idle = async {
loop {
let quiet = last.quiet();
if quiet >= limits.idle {
return End::Idle;
}
sleep(limits.idle - quiet).await;
}
};
tokio::select! {
end = both => end,
end = idle => end,
() = sleep(limits.max_age) => End::MaxAge,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn limits() -> SpliceLimits {
SpliceLimits {
buffer: 1024,
idle: Duration::from_secs(30),
stall: Duration::from_secs(30),
min_rate: 1024,
max_age: Duration::from_secs(60),
}
}
#[tokio::test]
async fn bytes_cross_both_ways_and_closes_are_passed_on() {
let (mut left, a) = tokio::io::duplex(256);
let (mut right, b) = tokio::io::duplex(256);
let task = tokio::spawn(splice(a, b, limits()));
left.write_all(b"to the right").await.unwrap();
left.shutdown().await.unwrap();
let mut got = Vec::new();
right.read_to_end(&mut got).await.unwrap();
assert_eq!(got, b"to the right");
right.write_all(b"and back").await.unwrap();
right.shutdown().await.unwrap();
let mut back = Vec::new();
left.read_to_end(&mut back).await.unwrap();
assert_eq!(back, b"and back");
assert_eq!(task.await.unwrap(), End::Done);
}
#[tokio::test]
async fn a_large_transfer_arrives_whole_in_small_buffers() {
let (mut left, a) = tokio::io::duplex(512);
let (mut right, b) = tokio::io::duplex(512);
let task = tokio::spawn(splice(a, b, limits()));
let data: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();
let send = data.clone();
let writer = tokio::spawn(async move {
left.write_all(&send).await.unwrap();
left.shutdown().await.unwrap();
left
});
let mut got = Vec::new();
right.read_to_end(&mut got).await.unwrap();
assert_eq!(got, data);
right.shutdown().await.unwrap();
let _left = writer.await.unwrap();
assert_eq!(task.await.unwrap(), End::Done);
}
#[tokio::test(start_paused = true)]
async fn a_peer_that_never_reads_stalls_the_splice_and_buffers_little() {
let (mut left, a) = tokio::io::duplex(1024);
let (_right, b) = tokio::io::duplex(1024); // never read
let l = SpliceLimits {
stall: Duration::from_secs(5),
..limits()
};
let task = tokio::spawn(splice(a, b, l));
// Keep writing; the relay must stop reading once its buffer and
// the pipes are full, so this write cannot complete in full.
let flood = tokio::spawn(async move {
let chunk = vec![1u8; 4096];
let mut sent = 0usize;
while left.write_all(&chunk).await.is_ok() {
sent += chunk.len();
if sent > 1_000_000 {
break;
}
}
sent
});
assert_eq!(task.await.unwrap(), End::Stalled);
let sent = flood.await.unwrap();
assert!(sent < 20_000, "{sent} bytes were taken from a stalled pipe");
}
#[tokio::test(start_paused = true)]
async fn a_silent_connection_is_closed_after_its_idle_time() {
let (_left, a) = tokio::io::duplex(64);
let (_right, b) = tokio::io::duplex(64);
let l = SpliceLimits {
idle: Duration::from_secs(10),
..limits()
};
assert_eq!(splice(a, b, l).await, End::Idle);
}
#[tokio::test(start_paused = true)]
async fn a_busy_connection_still_ends_at_its_maximum_age() {
let (mut left, a) = tokio::io::duplex(64);
let (_right, b) = tokio::io::duplex(64);
let l = SpliceLimits {
idle: Duration::from_secs(10),
max_age: Duration::from_secs(25),
..limits()
};
let task = tokio::spawn(splice(a, b, l));
for _ in 0..5 {
tokio::time::sleep(Duration::from_secs(6)).await;
let _ = left.write_all(b"x").await;
}
assert_eq!(task.await.unwrap(), End::MaxAge);
}
/// A reader that takes a little, often enough that no single wait is
/// long, but under the floor rate: cut. The old rule (a stall timer on
/// each write, here 30 s) would have let it hold the stream for hours.
#[tokio::test(start_paused = true)]
async fn a_reader_under_the_floor_rate_is_cut_and_one_at_the_floor_is_not() {
for (per_tick, expect_cut) in [(32usize, true), (512usize, false)] {
let (mut left, a) = tokio::io::duplex(1024);
let (mut right, b) = tokio::io::duplex(1024);
let l = SpliceLimits {
buffer: 1024,
// 2 s of grace and 1 KiB/s: a 1 KiB write has 3 s.
stall: Duration::from_secs(2),
min_rate: 1024,
idle: Duration::from_secs(3600),
max_age: Duration::from_secs(7200),
};
let task = tokio::spawn(splice(a, b, l));
let feed = tokio::spawn(async move {
let chunk = vec![5u8; 4096];
let _ = left.write_all(&chunk).await;
let _ = left.shutdown().await;
left
});
// The reader takes `per_tick` bytes every 250 ms: 128 B/s or 2 KiB/s.
let drain = tokio::spawn(async move {
let mut got = 0usize;
let mut buf = vec![0u8; per_tick];
loop {
tokio::time::sleep(Duration::from_millis(250)).await;
match right.read(&mut buf).await {
Ok(0) | Err(_) => return got,
Ok(n) => got += n,
}
}
});
let end = task.await.unwrap();
let _ = feed.await;
let got = drain.await.unwrap();
if expect_cut {
assert_eq!(end, End::Stalled, "128 B/s is under the 1 KiB/s floor");
assert!(
got < 4096,
"{got} bytes got through a reader under the floor"
);
} else {
assert_ne!(end, End::Stalled, "2 KiB/s keeps the pace");
assert_eq!(got, 4096);
}
}
}
}
+51
View File
@@ -0,0 +1,51 @@
//! TLS settings for the line, both ends.
//!
//! The line is TLS 1.3 only. The relay presents its own certificate for
//! its own host; the app checks it against the roots it is given. The app
//! proves itself not with a certificate but with the signature of
//! [`crate::proto`], bound to this session's exporter.
use std::path::Path;
use std::sync::Arc;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::{ClientConfig, RootCertStore, ServerConfig};
fn provider() -> Arc<rustls::crypto::CryptoProvider> {
Arc::new(rustls::crypto::ring::default_provider())
}
/// The relay's server settings from a chain and key.
pub fn server_config(
chain: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
) -> Result<Arc<ServerConfig>, rustls::Error> {
let mut cfg = ServerConfig::builder_with_provider(provider())
.with_protocol_versions(&[&rustls::version::TLS13])?
.with_no_client_auth()
.with_single_cert(chain, key)?;
// A line is long-lived and proven by signature: no tickets to hold.
cfg.send_tls13_tickets = 0;
Ok(Arc::new(cfg))
}
/// The relay's server settings from PEM files.
pub fn server_config_from_files(cert: &Path, key: &Path) -> Result<Arc<ServerConfig>, String> {
let chain = CertificateDer::pem_file_iter(cert)
.map_err(|e| format!("{}: {e}", cert.display()))?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("{}: {e}", cert.display()))?;
let key = PrivateKeyDer::from_pem_file(key).map_err(|e| format!("{}: {e}", key.display()))?;
server_config(chain, key).map_err(|e| e.to_string())
}
/// An app's client settings: TLS 1.3, checking the relay against `roots`.
pub fn client_config(roots: RootCertStore) -> Result<Arc<ClientConfig>, rustls::Error> {
Ok(Arc::new(
ClientConfig::builder_with_provider(provider())
.with_protocol_versions(&[&rustls::version::TLS13])?
.with_root_certificates(roots)
.with_no_client_auth(),
))
}
+271
View File
@@ -0,0 +1,271 @@
//! The proof records: what the relay's DNS says at `_acme-challenge.<name>`.
//!
//! An app that wants a certificate for its name asks the relay, over its
//! own proven line, to publish the ACME DNS-01 value at
//! `_acme-challenge.<its name>.<domain>`. The record is held in memory for
//! minutes and answered by the DNS server; nothing is stored per user.
//!
//! The request carries no name. The name is the line's, proven at the
//! handshake, so an app can publish for its own name and for no other.
//!
//! ```text
//! GOAL: a certificate for a name can be proven by the app that holds the
//! name's key and by nobody else, and the relay never proves a name
//! on its own account.
//! SOURCE: WB-relay-5 (the proof records and the domain's DNS), RFC 8555
//! section 8.4 (the DNS-01 challenge), D-87.
//! INVARIANTS:
//! 1. `publish` takes the name from the caller's authenticated line;
//! no value can be placed under any other name.
//! 2. A value is exactly the 43 base64url characters of a SHA-256
//! digest; any other text is refused.
//! 3. Records expire: after `ttl` they are not answered and the sweep
//! frees them.
//! 4. Memory is bounded: at most `max_entries` names, `per_name` values
//! each, and a name's publishes are counted per hour.
//! SCENARIOS:
//! 1. A published value is answered until its ttl, then not.
//! 2. A fifth value for one name (limit 4) is refused; the first four
//! stand.
//! 3. A store at its entry limit refuses a new name and still serves
//! the old ones.
//! 4. A thirteenth publish within the hour is refused.
//! ```
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use crate::names::Name;
/// Why a publish was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PublishError {
/// The value is not a DNS-01 proof value.
#[error("not a proof value")]
BadValue,
/// The store is full, or this name publishes too often.
#[error("too many proof records")]
Limit,
}
struct Slot {
values: Vec<(String, Instant)>,
window_start: Instant,
publishes: u32,
}
/// The proof records, in memory.
pub struct TxtStore {
inner: Mutex<HashMap<Name, Slot>>,
ttl: Duration,
max_entries: usize,
per_name: usize,
per_hour: u32,
}
const HOUR: Duration = Duration::from_secs(3600);
/// Is this an ACME DNS-01 value: base64url of a SHA-256 digest, no padding?
pub fn is_proof_value(text: &str) -> bool {
text.len() == 43
&& text
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
impl TxtStore {
/// A store with these limits.
pub fn new(ttl: Duration, max_entries: usize, per_name: usize, per_hour: u32) -> Self {
TxtStore {
inner: Mutex::new(HashMap::new()),
ttl,
max_entries,
per_name: per_name.max(1),
per_hour,
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<Name, Slot>> {
// A panic while holding the lock cannot leave the map half-edited
// in a way that matters more than refusing to serve.
self.inner.lock().unwrap_or_else(|p| p.into_inner())
}
/// Publish `value` for `name` at `now`.
pub fn publish(&self, name: Name, value: &str, now: Instant) -> Result<(), PublishError> {
if !is_proof_value(value) {
return Err(PublishError::BadValue);
}
let mut map = self.lock();
if !map.contains_key(&name) && map.len() >= self.max_entries {
sweep_locked(&mut map, self.ttl, now);
if map.len() >= self.max_entries {
return Err(PublishError::Limit);
}
}
let slot = map.entry(name).or_insert_with(|| Slot {
values: Vec::new(),
window_start: now,
publishes: 0,
});
if now.saturating_duration_since(slot.window_start) >= HOUR {
slot.window_start = now;
slot.publishes = 0;
}
if slot.publishes >= self.per_hour {
return Err(PublishError::Limit);
}
slot.values
.retain(|(_, at)| now.saturating_duration_since(*at) < self.ttl);
if let Some(held) = slot.values.iter_mut().find(|(v, _)| v == value) {
held.1 = now; // the same value again only renews it
} else if slot.values.len() >= self.per_name {
return Err(PublishError::Limit);
} else {
slot.values.push((value.to_owned(), now));
}
slot.publishes += 1;
Ok(())
}
/// The live values for `name` at `now`.
pub fn get(&self, name: &Name, now: Instant) -> Vec<String> {
self.lock()
.get(name)
.map(|s| {
s.values
.iter()
.filter(|(_, at)| now.saturating_duration_since(*at) < self.ttl)
.map(|(v, _)| v.clone())
.collect()
})
.unwrap_or_default()
}
/// Drop every value of `name`. Its publish count stays for the hour.
pub fn clear(&self, name: &Name) {
if let Some(slot) = self.lock().get_mut(name) {
slot.values.clear();
}
}
/// Free everything expired. Called every half minute by the relay.
pub fn sweep(&self, now: Instant) {
sweep_locked(&mut self.lock(), self.ttl, now);
}
/// Names held (for tests and the stats line).
pub fn len(&self) -> usize {
self.lock().len()
}
/// True when nothing is held.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
fn sweep_locked(map: &mut HashMap<Name, Slot>, ttl: Duration, now: Instant) {
map.retain(|_, slot| {
slot.values
.retain(|(_, at)| now.saturating_duration_since(*at) < ttl);
!slot.values.is_empty() || now.saturating_duration_since(slot.window_start) < HOUR
});
}
#[cfg(test)]
mod tests {
use super::*;
fn value(c: char) -> String {
std::iter::repeat_n(c, 43).collect()
}
fn name(s: &str) -> Name {
Name::parse(s).unwrap()
}
#[test]
fn a_value_is_answered_until_its_ttl() {
let s = TxtStore::new(Duration::from_secs(60), 10, 4, 12);
let n = name("ledger-accrual-tally-mint");
let t0 = Instant::now();
s.publish(n, &value('a'), t0).unwrap();
assert_eq!(s.get(&n, t0 + Duration::from_secs(59)), vec![value('a')]);
assert!(s.get(&n, t0 + Duration::from_secs(60)).is_empty());
s.sweep(t0 + Duration::from_secs(61));
assert_eq!(s.len(), 1, "the publish count is kept for the hour");
s.sweep(t0 + HOUR + Duration::from_secs(1));
assert!(s.is_empty());
}
#[test]
fn only_proof_values_are_taken() {
let s = TxtStore::new(Duration::from_secs(60), 10, 4, 12);
let n = name("ledger-accrual-tally-mint");
let t0 = Instant::now();
for bad in [
"",
"short",
&"a".repeat(44),
&format!("{}=", "a".repeat(42)),
&format!("{}.", "a".repeat(42)),
] {
assert_eq!(
s.publish(n, bad, t0),
Err(PublishError::BadValue),
"{bad:?}"
);
}
assert!(s.get(&n, t0).is_empty());
}
#[test]
fn values_per_name_and_names_in_all_are_bounded() {
let s = TxtStore::new(Duration::from_secs(60), 2, 2, 100);
let (a, b, c) = (
name("ledger-accrual-tally-mint"),
name("ledger-accrual-tally-vault"),
name("ledger-accrual-tally-audit"),
);
let t0 = Instant::now();
s.publish(a, &value('a'), t0).unwrap();
s.publish(a, &value('b'), t0).unwrap();
assert_eq!(s.publish(a, &value('c'), t0), Err(PublishError::Limit));
s.publish(a, &value('a'), t0)
.expect("the same value renews");
s.publish(b, &value('a'), t0).unwrap();
assert_eq!(s.publish(c, &value('a'), t0), Err(PublishError::Limit));
assert_eq!(s.get(&a, t0).len(), 2);
assert_eq!(s.get(&b, t0).len(), 1);
// After a's values expire there is room again.
s.publish(c, &value('a'), t0 + Duration::from_secs(61))
.unwrap_err();
s.sweep(t0 + HOUR + Duration::from_secs(1));
s.publish(c, &value('a'), t0 + HOUR + Duration::from_secs(2))
.unwrap();
}
#[test]
fn publishes_are_counted_per_hour() {
let s = TxtStore::new(Duration::from_secs(5), 10, 4, 3);
let n = name("ledger-accrual-tally-mint");
let t0 = Instant::now();
for _ in 0..3 {
s.publish(n, &value('a'), t0).unwrap();
}
assert_eq!(s.publish(n, &value('a'), t0), Err(PublishError::Limit));
s.publish(n, &value('a'), t0 + HOUR).expect("a new hour");
}
#[test]
fn clear_removes_the_values() {
let s = TxtStore::new(Duration::from_secs(60), 10, 4, 12);
let n = name("ledger-accrual-tally-mint");
let t0 = Instant::now();
s.publish(n, &value('a'), t0).unwrap();
s.clear(&n);
assert!(s.get(&n, t0).is_empty());
}
}
+276
View File
@@ -0,0 +1,276 @@
//! Shared setup for the relay's tests: certificates, a relay on loopback,
//! a stand-in for the app, and a stand-in for an assistant. Everything
//! stays on 127.0.0.1.
#![allow(dead_code, missing_docs)]
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose};
use relay::authorities::AuthorityList;
use relay::client::{self, Incoming, Line, LineOptions};
use relay::config::{Config, NameServer};
use relay::names::Name;
use relay::proto::AppKey;
use relay::{Limits, Relay};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName};
use rustls::{RootCertStore, ServerConfig};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio_rustls::{TlsAcceptor, TlsConnector};
pub const DOMAIN: &str = "wanderbooks.link";
pub const RELAY_HOST: &str = "relay.wanderbooks.link";
pub const SECRET: &str = "k3j9x0q7m2z8c5v1b4n6a9s2d";
pub const PROOF_A: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ";
pub const PROOF_B: &str = "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrq-_01234";
pub struct Ca {
issuer: CertifiedIssuer<'static, KeyPair>,
}
impl Ca {
pub fn new(cn: &str) -> Self {
let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
params
.distinguished_name
.push(rcgen::DnType::CommonName, cn);
let issuer = CertifiedIssuer::self_signed(params, KeyPair::generate().unwrap()).unwrap();
Ca { issuer }
}
pub fn roots(&self) -> RootCertStore {
let mut roots = RootCertStore::empty();
roots.add(self.issuer.der().clone()).unwrap();
roots
}
pub fn leaf(&self, names: &[&str]) -> (Vec<CertificateDer<'static>>, PrivateKeyDer<'static>) {
let key = KeyPair::generate().unwrap();
let params =
CertificateParams::new(names.iter().map(|s| s.to_string()).collect::<Vec<_>>())
.unwrap();
let cert = params.signed_by(&key, &self.issuer).unwrap();
(
vec![cert.der().clone()],
PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.serialize_der())),
)
}
pub fn pem(&self) -> String {
self.issuer.pem()
}
}
/// A relay on loopback with its own CA, and an app CA for the app's
/// certificate (so the relay's certificate is not one an assistant trusts).
pub struct Env {
pub relay: Relay,
pub relay_ca: Ca,
pub app_ca: Ca,
pub dir: tempfile::TempDir,
}
pub fn quick_limits() -> Limits {
Limits {
// The tests claim many names, and make many lines, from one
// address: every per-address limit is out of the way unless a test
// is about it.
claims_per_window: 10_000,
claims_per_ip: 10_000,
claims_per_net: 10_000,
cert_publishes_per_window: 10_000,
cert_publishes_per_ip: 10_000,
cert_publishes_per_net: 10_000,
max_handshakes_per_ip: 10_000,
max_handshakes_per_net: 10_000,
max_pending_per_net: 10_000,
..Limits::default()
}
}
pub async fn start(limits: Limits) -> Env {
start_with(limits, AuthorityList::empty()).await
}
pub async fn start_with(limits: Limits, authorities: AuthorityList) -> Env {
let dir = tempfile::tempdir().unwrap();
let relay_ca = Ca::new("relay test ca");
let app_ca = Ca::new("app test ca");
let (chain, key) = relay_ca.leaf(&[RELAY_HOST]);
let tls = relay::tls::server_config(chain, key).unwrap();
let cfg = Config {
router_addr: "127.0.0.1:0".parse().unwrap(),
dns_addr: "127.0.0.1:0".parse().unwrap(),
registry_path: dir.path().join("registry.sqlite3"),
address_v4: vec!["198.51.100.7".parse().unwrap()],
nameservers: vec![NameServer {
name: "ns1.wanderbooks.link".into(),
v4: vec!["198.51.100.53".parse().unwrap()],
v6: vec![],
}],
limits,
..Config::default()
};
let relay = Relay::start(cfg, tls, authorities).await.unwrap();
Env {
relay,
relay_ca,
app_ca,
dir,
}
}
impl Env {
pub fn router(&self) -> SocketAddr {
self.relay.router_addr()
}
pub fn line_tls(&self) -> Arc<rustls::ClientConfig> {
relay::tls::client_config(self.relay_ca.roots()).unwrap()
}
pub async fn connect(
&self,
name: Name,
key: &AppKey,
claim: bool,
) -> Result<Line, client::ClientError> {
client::connect(
self.router(),
self.line_tls(),
RELAY_HOST,
name,
key,
claim,
LineOptions::default(),
)
.await
}
/// An app: claim (or reconnect) and serve callers with TLS from the
/// app's own certificate, echoing what they say, prefixed.
pub async fn app(&self, name: Name, key: &AppKey, claim: bool) -> App {
let line = self
.connect(name, key, claim)
.await
.expect("the line comes up");
App::serve(line, name, &self.app_ca)
}
pub fn assistant_tls(&self) -> TlsConnector {
TlsConnector::from(Arc::new(
rustls::ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(self.app_ca.roots())
.with_no_client_auth(),
))
}
/// An assistant: TCP to the router, TLS with this server name.
pub async fn assistant(
&self,
host: &str,
) -> std::io::Result<tokio_rustls::client::TlsStream<TcpStream>> {
let tcp = TcpStream::connect(self.router()).await?;
self.assistant_tls()
.connect(ServerName::try_from(host.to_owned()).unwrap(), tcp)
.await
}
}
pub fn host_of(name: &Name) -> String {
format!("{SECRET}.{name}.{DOMAIN}")
}
pub fn n(words: &str) -> Name {
Name::parse(words).unwrap()
}
/// The app's side once the line is up.
pub struct App {
pub callers: tokio::sync::mpsc::UnboundedReceiver<std::net::SocketAddr>,
pub line: relay::client::LineHandle,
pub task: tokio::task::JoinHandle<()>,
}
impl App {
fn serve(mut line: Line, name: Name, app_ca: &Ca) -> App {
let (chain, key) = app_ca.leaf(&[&format!("*.{name}.{DOMAIN}")]);
let mut cfg =
ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_protocol_versions(&[&rustls::version::TLS13])
.unwrap()
.with_no_client_auth()
.with_single_cert(chain, key)
.unwrap();
cfg.send_tls13_tickets = 0;
let acceptor = TlsAcceptor::from(Arc::new(cfg));
let (seen, callers) = tokio::sync::mpsc::unbounded_channel();
let handle = line.handle();
let task = tokio::spawn(async move {
while let Some(Incoming { caller, stream }) = line.accept().await {
let _ = seen.send(caller.source);
let acceptor = acceptor.clone();
tokio::spawn(async move {
let Ok(mut tls) = acceptor.accept(stream).await else {
return;
};
let mut buf = [0u8; 4096];
loop {
let Ok(n) = tls.read(&mut buf).await else {
return;
};
if n == 0 {
let _ = tls.shutdown().await;
return;
}
let mut out = b"echo:".to_vec();
out.extend_from_slice(&buf[..n]);
if tls.write_all(&out).await.is_err() || tls.flush().await.is_err() {
return;
}
}
});
}
});
App {
callers,
line: handle,
task,
}
}
}
pub async fn eventually<F: FnMut() -> bool>(what: &str, mut f: F) {
for _ in 0..200 {
if f() {
return;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!("never happened: {what}");
}
/// A real TLS 1.3 ClientHello for `host`, as bytes.
pub fn client_hello_bytes(host: &str) -> Vec<u8> {
let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(RootCertStore::empty())
.with_no_client_auth();
let name = ServerName::try_from(host.to_owned()).unwrap();
let mut conn = rustls::ClientConnection::new(Arc::new(cfg), name).unwrap();
let mut out = Vec::new();
conn.write_tls(&mut out).unwrap();
out
}
+234
View File
@@ -0,0 +1,234 @@
//! What an idle line costs the relay, measured.
//!
//! Section 7 of the plan lists this as unknown, and it sizes the host.
//! The bench runs the relay in this process and the apps in a child
//! process (so the relay's resident memory is the relay's alone), brings
//! up N lines, and reads the relay's `VmRSS` before and after. It then
//! drops every line and brings them all up again twice more (churn), and
//! checks that memory does not grow.
//!
//! It needs one descriptor per line in each process, so it is ignored in
//! a normal run:
//!
//! ```text
//! ulimit -n 65536
//! TMPDIR=/dev/shm RELAY_IDLE_LINES=20000 cargo test --release \
//! -p relay --test memory idle_line_memory -- --ignored --nocapture
//! ```
//!
//! `TMPDIR=/dev/shm` keeps the registry off the disk: every claim of a
//! name is fsynced (that is the point of the registry), and 20 000 of
//! them take minutes on a disk. Measured 2026-11-21 on this machine,
//! release build: 20 000 lines, 15.2 KiB of the relay's resident memory
//! per idle line, and 15.3 KiB after two rounds of churn (flat).
//! Measured again 2026-11-21 after the stream limits and per-prefix
//! limits of the security fix round: 15.4 KiB per idle line, 15.6 KiB
//! after two rounds of churn (an idle line holds no stream, so the
//! smaller stream limits do not move this figure).
//!
//! Linux only (it reads /proc).
#![allow(missing_docs)]
#![cfg(target_os = "linux")]
mod common;
use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
use std::sync::Arc;
use common::*;
use relay::Limits;
use relay::client::{self, LineOptions};
use relay::names::Name;
use relay::proto::AppKey;
use tokio::sync::Semaphore;
fn rss_kib() -> u64 {
let status = std::fs::read_to_string("/proc/self/status").unwrap();
status
.lines()
.find_map(|l| l.strip_prefix("VmRSS:"))
.and_then(|v| v.trim().trim_end_matches("kB").trim().parse().ok())
.expect("VmRSS")
}
fn lines_wanted() -> usize {
std::env::var("RELAY_IDLE_LINES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(2000)
}
/// The child: holds N lines, on request drops and remakes them.
/// Run only by `idle_line_memory`, which sets RELAY_HERD.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "a helper process for idle_line_memory"]
async fn herd_child() {
let Ok(spec) = std::env::var("RELAY_HERD") else {
return;
};
let mut parts = spec.split('|');
let addr: std::net::SocketAddr = parts.next().unwrap().parse().unwrap();
let count: usize = parts.next().unwrap().parse().unwrap();
let ca_path = parts.next().unwrap();
let pem = std::fs::read_to_string(ca_path).unwrap();
let mut roots = rustls::RootCertStore::empty();
for c in
<rustls::pki_types::CertificateDer as rustls::pki_types::pem::PemObject>::pem_slice_iter(
pem.as_bytes(),
)
{
roots.add(c.unwrap()).unwrap();
}
let tls = relay::tls::client_config(roots).unwrap();
let ids: Vec<(Name, Arc<AppKey>)> = (0..count)
.map(|_| (Name::random(), Arc::new(AppKey::generate().0)))
.collect();
let mut claim = true;
let mut round = 0;
let stdin = std::io::stdin();
loop {
let gate = Arc::new(Semaphore::new(64));
let mut tasks = Vec::new();
for (name, key) in &ids {
let (name, key, tls, gate) =
(*name, Arc::clone(key), Arc::clone(&tls), Arc::clone(&gate));
tasks.push(tokio::spawn(async move {
let _p = gate.acquire().await.unwrap();
client::connect(
addr,
tls,
RELAY_HOST,
name,
&key,
claim,
LineOptions::default(),
)
.await
.expect("a line")
}));
}
let mut lines = Vec::with_capacity(count);
for t in tasks {
lines.push(t.await.unwrap());
}
claim = false;
round += 1;
println!("READY {round}");
std::io::stdout().flush().unwrap();
let mut cmd = String::new();
if stdin.lock().read_line(&mut cmd).unwrap() == 0 || cmd.trim() == "stop" {
return;
}
drop(lines); // the lines close, then the loop brings them back
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "needs a descriptor per line: see the module comment"]
async fn idle_line_memory() {
let n = lines_wanted();
let env = start(Limits {
max_connections: 1_000_000,
max_connections_per_ip: 1_000_000,
max_pending_per_ip: 10_000,
max_pending_hellos: 10_000,
max_pending_per_net: 10_000,
max_handshakes: 1024,
max_handshakes_per_ip: 1024,
max_handshakes_per_net: 1024,
max_lines: n + 10,
line_idle_ms: 3_600_000,
claims_per_window: u32::try_from(n + 10).unwrap(),
claims_per_ip: u32::try_from(n + 10).unwrap(),
claims_per_net: u32::try_from(n + 10).unwrap(),
..quick_limits()
})
.await;
// Warm up: one line, so one-time allocations are not counted.
let (k, _) = AppKey::generate();
env.connect(Name::random(), &k, true)
.await
.unwrap()
.close()
.await;
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let before = rss_kib();
let ca = env.dir.path().join("ca.pem");
std::fs::write(&ca, env.relay_ca.pem()).unwrap();
let mut child = Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"herd_child",
"--ignored",
"--nocapture",
"--test-threads=1",
])
.env(
"RELAY_HERD",
format!("{}|{n}|{}", env.router(), ca.display()),
)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.unwrap();
let mut out = BufReader::new(child.stdout.take().unwrap());
let mut stdin = child.stdin.take().unwrap();
let started = std::time::Instant::now();
let mut held = Vec::new();
for round in 1..=3 {
let mut line = String::new();
loop {
line.clear();
assert!(
out.read_line(&mut line).unwrap() > 0,
"the child ended early"
);
if line.trim().ends_with(&format!("READY {round}")) {
break;
}
}
// Let the sockets settle and the allocator hand back what it can.
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
let up = env.relay.shared().lines.len();
assert_eq!(up, n, "every line is up");
let rss = rss_kib();
held.push(rss);
eprintln!(
"round {round}: {up} lines up, relay RSS {rss} KiB, {:.2} KiB per line over the {before} KiB baseline ({:?} so far)",
(rss.saturating_sub(before)) as f64 / n as f64,
started.elapsed()
);
writeln!(stdin, "{}", if round == 3 { "stop" } else { "again" }).unwrap();
stdin.flush().unwrap();
if round < 3 {
// The child drops its lines; wait for the relay to see them go.
eventually_async(|| env.relay.shared().lines.len() < n).await;
}
}
let _ = child.wait();
let per_line = held[0].saturating_sub(before) as f64 / n as f64;
eprintln!("idle line: {per_line:.2} KiB in the relay's resident memory (N = {n})");
// Churn leaves memory flat: the third round is within 10% of the
// first, over the baseline.
let grown = held[2].saturating_sub(held[0]);
assert!(
(grown as f64) < 0.10 * (held[0].saturating_sub(before) as f64) + 2048.0,
"memory grew {grown} KiB over two rounds of churn: {held:?}"
);
// And a ceiling, generous: a line must not cost 64 KiB.
assert!(per_line < 64.0, "{per_line} KiB per idle line");
}
async fn eventually_async<F: FnMut() -> bool>(mut f: F) {
for _ in 0..1200 {
if f() {
return;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
panic!("the lines never went away");
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+369
View File
@@ -0,0 +1,369 @@
# Claims: relay
The product rules of the relay on `wanderbooks.link` (plan P15, unit B2;
decisions D-80, D-82, D-85, D-87 in `plan/p15-app-and-relay.md`). No
authority states them: they are wanderbooks' own (`WB-relay-<n>`). The
relay is the crate `crates/relay`; it depends on none of the `ledger-*`
crates. A person runs the desktop app at home; web assistants can only call
servers on the public internet; the app dials out to the relay and holds a
line open, and the relay routes an assistant's TLS connection, by its server
name, down that line. The relay holds no key or certificate for any app and
cannot read the traffic.
Rules: none from bookspec.
---
## Product rules
**WB-relay-1** The router reads the server name in the first TLS message and forwards the encrypted bytes, and nothing else.
```text
GOAL: route an assistant's connection to the app that owns the name in
its first message, without terminating TLS for that name, and close
anything else the same way.
SOURCE: RFC 8446 section 4.1.2 and RFC 6066 section 3 (the ClientHello and
the server_name extension); D-80 in plan/p15-app-and-relay.md
(the relay cannot read traffic).
INVARIANTS:
1. The router reads only the first TLS record, to its server name, and
then copies bytes both ways; the only TLS the relay ends is the
line's, for its own host. It holds no certificate for any app.
2. An unknown name, an app that is not connected, an app over its stream
limit, a host that is not `<secret>.<four words>.<domain>`, and every
malformed first message are closed in the same way (a TLS
`unrecognized_name` alert, then close, or close with nothing).
3. The ClientHello parser never panics and never reads beyond what it
was given, whatever the bytes; a hello split over several records is
refused.
4. Bytes cross in both directions with one buffer per direction; a close
in one direction is passed on, and the other direction carries on
until it ends.
SCENARIOS:
1. An assistant connects with an app's name; TLS completes between the
assistant and the app with the app's own certificate, bytes go both
ways, and a relay holding no certificate the assistant trusts is
enough.
2. An unknown name and an offline app are closed with the same alert.
3. Random bytes, mutated hellos and every cut of a real hello are
refused without a panic.
```
*Enforced:* `route`, `read_hello`, `hello::server_name`, `hello::record_len`, `Zone::classify`, `splice::splice` (crate `relay`).
*Checked:* `relay` `tests/relay.rs` (`an_assistant_reaches_the_app_by_name_with_the_apps_own_certificate`, `the_relay_holds_no_certificate_the_assistant_would_accept`, `unknown_names_offline_apps_and_odd_hosts_are_closed_the_same_way`, `bytes_that_are_not_a_hello_are_closed`); unit tests in `src/hello.rs` (`random_bytes_never_panic`, `a_mutated_hello_never_panics`, `a_real_rustls_hello_gives_its_name`, `not_tls_and_cut_off_bytes_are_refused`) and `src/splice.rs` (`bytes_cross_both_ways_and_closes_are_passed_on`, `a_large_transfer_arrives_whole_in_small_buffers`).
**WB-relay-2** An app proves it holds the key for its name, for one TLS session only, every time it connects.
```text
GOAL: neither a stranger nor a recording of an old proof, nor a relay that
sat between two sessions, can take a name's line.
SOURCE: D-85 in plan/p15-app-and-relay.md (the key is pinned in the
relay's table); RFC 8032 (Ed25519); RFC 5705 and RFC 8446 section
7.5 (TLS exporters).
INVARIANTS:
1. The line is TLS 1.3. The relay sends a fresh 32-byte nonce; the app
answers with its name, its public key, whether it is claiming the
name, and an Ed25519 signature over a context string, this session's
TLS exporter value, the nonce, the claim flag and the name.
2. The signature is checked before any registry work, so a peer without
the key never reaches the registry.
3. A name's line is brought up only for the key the registry holds for
it (or the key that has just claimed it); a reconnect with the right
key replaces the old line.
4. A caller who has not shown the name's key learns nothing about which
names exist: a name nobody has claimed, a name held by another key,
and a blocked name are refused with one answer (`bad_proof`). Only
the holder of a blocked name's key is told `blocked`; a claim of a
held name, blocked or not, is `taken`.
5. Every handshake frame is at most 2 048 bytes, and the whole
handshake, TLS included, finishes within `handshake_timeout_ms`.
SCENARIOS:
1. A recorded hello from an accepted session, sent on a new session, is
refused; so is a hello signed over another session's exporter and one
signed over an old nonce.
2. A wrong key for an existing name is refused; the owner reconnects.
3. A hello with a name that is not four listed words, a frame that is
not JSON and a frame over the limit end the line without touching
the registry.
4. Another key's reconnect to a name that is claimed, one that is
unclaimed and one that is blocked get the same refusal.
```
*Enforced:* `decide`, `handshake`, `proto::proof_message`, `proto::verify`, `read_frame`, `write_frame`, `client::make_hello`.
*Checked:* `relay` `tests/relay.rs` (`a_replayed_or_relayed_proof_is_refused`, `a_name_cannot_be_claimed_twice_and_a_wrong_key_is_refused`, `a_stranger_cannot_tell_which_names_exist_or_are_blocked`, `malformed_hellos_are_refused_without_touching_the_registry`, `a_reconnect_with_the_right_key_replaces_the_old_line`, `a_line_handshake_that_never_finishes_is_dropped`); unit tests in `src/proto.rs` (`a_proof_holds_for_one_session_and_nothing_else`, `frames_are_bounded`).
**WB-relay-3** An app's name is four words from the curated finance and accounting list.
```text
GOAL: a recognisable public name that is never a word a customer would not
want in an address, and that no stranger can use to claim the
relay's own hosts or a challenge name.
SOURCE: D-82 in plan/p15-app-and-relay.md; the list is
crates/relay/words.txt.
INVARIANTS:
1. A name is four indices into the list: a name that exists is four
listed words, hyphen-joined in lower case, and parsing is exact.
2. The list is sorted, has no repeat, holds words of 3 to 11 lower-case
letters, and holds none of a set of unwelcome words (nor "executor",
"testament" or "probate"); it has 1 427 words, so a name is 41.9
bits, and the floor is 40 bits (1 024 words), which a test states.
Where two words sound alike (peer and pier) one is listed, and where
one is the inflection of another (accrue and accrued) the base form
is: a name read aloud is unambiguous.
3. A host is routed only as `<secret>.<name>.<domain>`, the secret being
25 to 63 lower-case letters or digits; the apex, the relay's host and
every other shape are not an app's. The app makes the secret from at
least 128 random bits: 25 or more random base 36 characters (25 of
them are 129.2 bits). The relay cannot check that the characters are
random, so it refuses a label too short to hold 128 bits, and the app
is the one that must not make it from less.
SCENARIOS:
1. `ledger-accrual-tally-mint` parses and prints as itself;
`ledger-accrual-tally`, an unlisted word, `relay` and `ns1` do not.
2. `<secret>.ledger-accrual-tally-mint.wanderbooks.link` is that app's;
the same without the secret, with a secret under 25 characters
(`aaaaaaaaaaaaaaaa`) or under another domain is not.
```
*Enforced:* `Name::parse`, `Name::random`, `words`, `Zone::classify`, `Zone::below`.
*Checked:* unit tests in `src/names.rs` (`the_list_is_sorted_unique_plain_and_welcome`, `a_name_is_four_listed_words_and_prints_as_itself`, `four_words_are_at_least_40_bits`, `no_word_is_an_inflection_or_a_homophone_of_another`, `a_host_is_routed_only_as_secret_dot_name_dot_domain`, `a_secret_label_under_25_characters_is_not_routed`, `below_names_the_labels_under_the_zone`).
**WB-relay-4** The registry is the one durable table: name, public key, created, blocked, first publish.
```text
GOAL: a name belongs to the first key that claims it and to no other,
across restarts, with nothing else about an app kept.
SOURCE: D-85 in plan/p15-app-and-relay.md.
INVARIANTS:
1. A name has at most one key; a later claim, with the same key or
another, never changes the row.
2. A claim is durable before it is acknowledged. Claiming a name does
not spend the certificate authority's budget: the claim is limited
by a safety ceiling on the registry (5 000 new names a day, counted
from the rows' creation times in the same transaction, so a restart
does not reset it) and, in memory, per address and per network: 5 a
day for one IPv4 address or IPv6 /64, 20 a day for one IPv4 /24 or
IPv6 /48 (an IPv4-mapped IPv6 address counts as its IPv4 address).
3. The certificate authority's issuance limit (50 new certificates a
week for the domain) is charged when a name first publishes a proof
record, once per name: the registry keeps the time of a name's first
publish and counts them in the window in one transaction, so a
restart does not reset the 50 a week, and a renewal (a name already
charged) is free. First publishes have per-prefix limits of their own
in memory, over the same window: 3 a week for one IPv4 address or
IPv6 /64, 10 a week for one IPv4 /24 or IPv6 /48.
4. Requests to the database go through a bounded queue; past it the
relay says busy.
5. The operator can block a name; a blocked name's line is refused, a
blocked name's live line is closed at its next publish and by a
sweep of the registry every 10 seconds (`block_check_ms`), so a block
written by the operator's command reaches the running relay within
about 10 seconds, and an open line does not outlast it.
SCENARIOS:
1. Twenty racing claims of one name: one wins.
2. A claim, a reopen, a lookup: the key is there; the window limit
counts rows made before the reopen.
3. Two names are claimed under a limit of two; a third is refused, and
a blocked name cannot connect.
4. Four names claim under a certificate budget of two: all four claim,
the first two publish, the third's first publish is refused, and the
first renews at no charge; a restart keeps the count.
5. The operator blocks a name whose line is up: the line closes, the
assistant can no longer reach it, and the name's owner is told
`blocked` when it reconnects.
```
*Enforced:* `Registry::claim`, `Registry::lookup`, `Registry::set_blocked`, `Registry::charge_publish`, `Registry::blocked_names`, `Registry::open`, `PrefixLimit::allow`, `publish`.
*Checked:* unit tests in `src/registry.rs` (`the_first_claim_wins_and_the_row_never_changes`, `racing_claims_have_one_winner`, `a_claim_outlives_a_restart_and_the_window_counts_old_rows`, `blocking_a_name_is_kept`, `the_certificate_budget_charges_a_name_once_and_survives_a_restart`, `the_blocked_names_are_listed_and_a_file_without_the_column_is_upgraded`); `relay` `tests/relay.rs` (`blocked_names_and_the_limit_on_new_names`, `one_address_cannot_claim_many_names`, `the_certificate_budget_is_spent_at_first_publish_not_at_claim`, `first_publishes_are_limited_per_address`, `blocking_a_name_closes_its_live_line`, `a_blocked_name_cannot_publish_and_its_line_is_closed`); unit tests in `src/gate.rs` (`fifty_addresses_in_one_slash_64_get_the_slash_64s_limit_not_fifty_times_it`, `one_slash_48_cannot_use_many_slash_64s_to_beat_the_limit`, `a_mapped_address_is_counted_with_its_ipv4_address`, `a_prefix_limit_resets_with_its_window_and_a_refusal_counts_nothing`).
**WB-relay-5** The relay is the domain's DNS and publishes an app's proof record for its own name only; certificate authorities are a list it serves.
```text
GOAL: an app can prove its name to a certificate authority and no other
name, the relay never proves a name on its own account, and the
authority an app asks is chosen by the relay's list at the time.
SOURCE: D-87 in plan/p15-app-and-relay.md; RFC 8555 sections 7.3.4 and 8.4
(external account binding, the DNS-01 challenge); RFC 4592
(wildcards); RFC 6891 (EDNS); RFC 8482 (ANY).
INVARIANTS:
1. A publish request carries no name: the name is the line's, proven at
the handshake. A value is exactly 43 base64url characters; a name
holds at most four values, for ten minutes each, and publishes at
most twelve times an hour; the store holds at most 100 000 names.
2. DNS answers every name under the zone with the relay's addresses
(the name servers with their own), including names beneath a label
that has a record of its own; TXT is answered only at
`_acme-challenge.<name>` with the live published values; a name
outside the zone is refused; recursion is never offered.
3. A UDP answer never exceeds the client's size (512 without EDNS, at
most 1 232), longer ones are truncated; UDP is rate limited per
address (IPv4 address or IPv6 /64) from a fixed table, 20 a second
with a burst of 40, and a sender over its rate is answered
truncated with no data (so a real resolver retries over TCP, and
nothing larger than the query is sent to a spoofed source); all UDP
answers together are limited to 5 000 a second, past which there is
no answer; a UDP "connection reset" from the receive is not an error
of the socket and is passed over at once; TCP is capped in
connections, per address, in queries and in time.
4. The list of authorities is served in its order, each with its
directory address, whether it needs an account binding, whether it
is usable now, and the binding when it has one; it is read again
when its file changes, and a bad file never replaces a good list.
5. The list file never carries a binding secret, and none is ever
served from it: a file with `binding_kid` or `binding_hmac_key` is
refused when read, in words. A binding comes only from a per-app
source (an implementation of `BindingSource` that asks the authority
for one per app); with none installed, as in `wanderbooks-relay`
today, an authority that needs a binding is listed, served without
one and marked not usable yet.
6. DNS answers CAA at the apex (a certificate authority finds it by
climbing from any name below, RFC 8659) with one `issue` record per
listed authority, `issue "<caa_domain>; validationmethods=dns-01"`
(RFC 8657), from each authority's `caa_domain` in the same list, so
swapping authorities is an edit to one file; with no authority
listed there is no CAA record.
SCENARIOS:
1. Two apps each publish; each name answers its own value and not the
other's; a bad value is refused; clearing removes only one's own.
2. A for `<secret>.<name>.<domain>` is the relay's address with and
without a TXT record published for that name.
3. The list is served as written, then the file is edited to put
another authority first and add a third, and the next request
returns that order, and the zone's CAA record follows, with no
change to the app.
4. An authority that needs a binding, with no per-app source, is served
without one and marked not usable; a file with a binding secret is
not loaded.
5. A hundred queries from one address in a burst: a few are answered,
the rest truncated; past the global ceiling, none.
```
*Enforced:* `serve_control`, `TxtStore::publish`, `TxtStore::get`, `DnsService::answer`, `serve_udp`, `serve_tcp`, `AuthorityList::for_app`, `AuthorityList::caa_issuers`, `AuthorityList::reload`, `DnsService::truncated`, `is_proof_value`.
*Checked:* `relay` `tests/relay.rs` (`a_proof_record_is_published_for_ones_own_name_and_no_other`, `publishing_needs_a_proven_line`, `the_authority_list_is_served_and_follows_the_file`, `no_shared_binding_secret_is_ever_served`, `dns_over_udp_over_the_rate_is_answered_truncated`, `dns_over_udp_has_a_global_ceiling`, `dns_over_tcp_is_capped_and_times_out`); unit tests in `src/dns.rs` (`every_name_under_the_zone_is_at_the_relay_even_beneath_a_label_with_a_record`, `the_proof_record_is_answered_for_its_own_name_until_it_expires`, `outside_the_zone_is_refused_and_odd_queries_are_answered_plainly`, `garbage_never_panics_and_is_mostly_ignored`, `caa_at_the_apex_permits_the_listed_authorities_by_dns_01_only`, `caa_is_made_from_the_list_and_follows_it`, `the_truncated_answer_is_the_question_with_the_tc_bit_and_nothing_more`), `src/txt.rs` (`a_value_is_answered_until_its_ttl`, `only_proof_values_are_taken`, `values_per_name_and_names_in_all_are_bounded`, `publishes_are_counted_per_hour`) and `src/authorities.rs` (`the_list_is_served_in_order_and_a_binding_comes_only_from_a_source`, `a_list_file_that_carries_a_binding_secret_is_refused_in_words`, `a_bad_list_is_refused`, `an_edit_changes_what_is_served_and_a_bad_edit_does_not`, `a_binding_source_is_asked_only_for_authorities_that_need_one`).
**WB-relay-6** The app is told the caller's real address by the relay, first, in a header no caller can forge.
```text
GOAL: the app sees the address the assistant connected from, so it can
decide on it, without trusting anything the caller sent (the Home
Assistant CVE-2023-41894 lesson: a connection that arrives through
the relay is not a local connection).
SOURCE: the PROXY protocol specification, version 2; D-80 in
plan/p15-app-and-relay.md.
INVARIANTS:
1. The relay writes a PROXY version 2 header from the socket's own peer
address as the first bytes of the stream, before any byte the caller
sent; a mapped IPv4 address is written as IPv4.
2. The header parses only in its exact forms (28 bytes for IPv4, 52 for
IPv6, no extensions); the app drops a stream whose header does not.
SCENARIOS:
1. The app sees the assistant's own address and port.
2. Headers for IPv4 and IPv6 round-trip; a cut, a wrong signature and a
wrong length are refused.
```
*Enforced:* `route`, `Caller::encode`, `Caller::read`.
*Checked:* `relay` `tests/relay.rs` (`an_assistant_reaches_the_app_by_name_with_the_apps_own_certificate`); unit test in `src/proto.rs` (`a_caller_header_round_trips_for_v4_and_v6_and_nothing_else_parses`).
**WB-relay-7** Every buffer, queue, table and time in the relay is bounded.
```text
GOAL: no peer, however many or however slow, makes the relay hold
unbounded bytes, tasks or map entries; idle lines are cheap; and
one address or one network cannot stop the relay for the others.
SOURCE: D-80 in plan/p15-app-and-relay.md (bounded in memory, sized for
hundreds of thousands of idle apps on one modest host).
INVARIANTS:
1. `#![forbid(unsafe_code)]`. Every limit is a field of `Limits` with a
default; nothing else decides a size or a time.
2. Addresses are counted as what a subscriber holds: an IPv4 address,
or an IPv6 /64 (host reach), and an IPv4 /24 or IPv6 /48 (net
reach). An IPv4-mapped IPv6 address (`::ffff:a.b.c.d`, as a
dual-stack listener reports an IPv4 caller) is made canonical first,
in every table: the connection gates, the handshake gates, the claim
and first-publish limits, the DNS rate tables.
3. A connection is counted against a global limit and the per-address
limits before any work; a hello not complete in `hello_timeout_ms` is
closed; a peer may have few unfinished hellos (32 per address, 256
per network, 4 096 in all). The server name is not known before the
hello is read, so a reserve of 512 hello places cannot be kept "for
the relay's own host name": it is kept for addresses that held a
proven line in the last 12 to 24 hours (a two-generation Bloom
filter of 2^23 bits, filled only by a line that passed its proof),
and is used only when the 4 096 are taken. A flood from addresses
that never proved a name cannot use it; an app that comes back from a
new address during a flood retries until the flood ends.
4. A line handshake holds a place in the pool of 1 024, and a place for
its address (4) and its network (64), from the moment the router
sees the relay's host name until the verdict, so one address cannot
hold the pool by finishing a hello and stalling. Per-address tables
are fixed in size and do not grow with the number of addresses.
5. Per app: `streams_per_app` (8) caller streams, `control_streams_per_app`
(2) control streams, and 4 more the line may count while a stream
just closed is forgotten; a line silent for `line_idle_ms` dropped;
across apps `max_lines`. Every stream may hold a 256 KiB receive
window, which the yamux crate fixes (its 0.14 has no way to start a
stream smaller, and refuses a connection window below the sum), so
the most one line can be made to hold is 14 streams of 256 KiB,
3.5 MiB (it was 52 streams, 13 MiB).
6. A spliced connection holds one buffer per direction, reads only when
the other side has taken the last write, and ends when a write of
`n` bytes is not done in `write_stall_ms` (5 s) plus `n` over
`min_stream_bytes_per_sec` (2 KiB a second), so a reader that takes
bytes slowly enough to keep a window full is cut, not outwaited; and
when it is idle for `stream_idle_ms` or reaches `stream_max_age_ms`.
7. An idle line costs about 15 KiB of the relay's memory (measured,
release build, 20 000 lines, after these limits: 15.4 KiB, and
15.6 KiB after two rounds of churn), and that figure does not grow
under churn.
SCENARIOS:
1. A silent peer and a peer that sends a byte every 100 ms are both
closed at the hello timeout.
2. A third caller for an app limited to two is closed; a place freed is
reusable.
3. A caller sends 256 MiB to an app that never reads: the relay takes a
few MiB at most, then closes the stream at the stall limit.
4. A line that never pings is dropped after its idle time and leaves
the routing table; one that pings stays.
5. 20 000 idle lines, brought down and up three times, hold flat.
6. Two handshakes that get the challenge and stall, from one address
under a limit of two: a third is refused at once, and a place freed
is reusable.
7. With the hello pool full, an address that held a line gets in by the
reserve and a stranger does not; the reserve is itself bounded.
8. Fifty addresses in one IPv6 /64 get one /64's share; a hundred /64s
in one /48 get one /48's; two IPv4 callers on a dual-stack listener
do not share a slot.
9. A reader taking 128 bytes a second behind a 1 KiB a second floor is
cut; one at 2 KiB a second is not.
```
The limits, with what they are for (all in `Limits`, all configurable):
| Limit | Default | Counted by |
|---|---|---|
| `max_pending_hellos` / `hello_reserve` | 4 096 / 512 | all / known line addresses only |
| `max_pending_per_ip` / `_per_net` | 32 / 256 | IPv4 address or /64 / IPv4 /24 or /48 |
| `max_handshakes` | 1 024 | all |
| `max_handshakes_per_ip` / `_per_net` | 4 / 64 | until the verdict |
| `max_connections_per_ip` | 20 000 | AI vendors share a few addresses |
| `streams_per_app` / `control_streams_per_app` | 8 / 2 (+4 slack) | per line |
| `write_stall_ms` / `min_stream_bytes_per_sec` | 5 000 / 2 048 | per write |
| `claims_per_window` / `claim_window_ms` | 5 000 / 24 h | all names (safety ceiling) |
| `claims_per_ip` / `claims_per_net` | 5 / 20 a day | new names per prefix |
| `cert_publishes_per_window` / `cert_window_ms` | 50 / 7 d | names' first publishes (the authority's limit) |
| `cert_publishes_per_ip` / `_per_net` | 3 / 10 a week | first publishes per prefix |
| `txt_publishes_per_hour` | 12 | per name |
| `block_check_ms` | 10 000 | one registry query |
| `dns_qps_per_ip` / `dns_qps_global` | 20 / 5 000 | UDP, truncated / silent past it |
*Residual:* the certificate budget and the pools are cut per prefix, which
makes them cost an attacker more, not impossible: an attacker with many
networks (a provider's /32 holds 65 536 IPv6 /48s) can still spend the
week's 50 first publishes, or fill the hello pool. The answers are the
reserve for known lines, renewals being free, a second authority in the
list when the first's limit is reached, and asking the authority to raise
the domain's limit.
*Enforced:* `Limits`, `IpGate::acquire`, `PrefixLimit::allow`, `KnownAddrs`, `RateTable::allow`, `Shared::admit`, `accept_loop`, `serve_line`, `mux::spawn`, `splice::splice`, `LineMap::insert`.
*Checked:* `relay` `tests/relay.rs` (`a_silent_or_dripping_peer_is_closed_at_the_hello_timeout`, `one_address_cannot_hold_many_unfinished_hellos`, `one_network_cannot_hold_many_unfinished_hellos`, `a_known_line_address_still_gets_a_hello_place_when_the_pool_is_full`, `one_address_cannot_hold_the_pool_of_line_handshakes`, `streams_per_app_are_capped`, `lines_are_capped`, `a_slow_reader_back_pressures_and_is_cut_off_at_the_stall_limit`, `a_silent_line_is_dropped_and_a_pinging_one_is_not`, `shutdown_closes_every_line`); `relay` `tests/memory.rs` (`idle_line_memory`, run by hand: ignored in a normal run); unit tests in `src/gate.rs` (`a_limit_of_two_admits_two_and_frees_on_drop`, `every_permit_gives_back_what_it_took`, `ipv6_counts_by_the_slash_64`, `a_net_gate_counts_a_slash_48_and_an_ipv4_slash_24`, `two_ipv4_callers_on_a_dual_stack_listener_do_not_share_a_slot`, `known_addresses_are_remembered_for_one_to_two_periods`, `a_rate_table_allows_a_burst_then_the_rate`), `src/mux.rs` (`a_line_holds_only_its_streams`, `a_silent_line_is_closed_after_its_idle_time`, `a_large_transfer_both_ways_completes`) and `src/splice.rs` (`a_peer_that_never_reads_stalls_the_splice_and_buffers_little`, `a_reader_under_the_floor_rate_is_cut_and_one_at_the_floor_is_not`, `a_silent_connection_is_closed_after_its_idle_time`, `a_busy_connection_still_ends_at_its_maximum_age`).
+1 -1
View File
@@ -63,7 +63,7 @@ check-shard shard:
# the workspace, since K-U12. None leaves the list, and `kernel-only`
# fails when a folder under crates/ is not in it, so a new crate joins it
# on the day it is added.
kernel_only_crates := "ledger-core ledger-cli ledger-host ledger-reader ledger-vault ledger-store ledger-config ledger-import ledger-package ledger-mcp ledger-gui"
kernel_only_crates := "ledger-core ledger-cli ledger-host ledger-reader ledger-vault ledger-store ledger-config ledger-import ledger-package ledger-mcp ledger-gui relay"
# Money arithmetic lives in the kernel and nowhere else (AGENTS.md, bar
# item 1). The compiler is asked (scripts/raw-decimal-arith.sh): a raw