fix(relay): one address or network cannot stop the relay for the others
A review found ways for one cheap attacker to stop the service. - Line handshakes were limited only by a global pool: one address could finish a hello, stall, and repeat. A handshake now holds a place for its address (4) and network (64) from the relay's host name to the verdict. - Claims were counted per full address and against the certificate authority's weekly 50: one IPv6 /64 could spend all 50 with throwaway keys. Addresses now count by IPv6 /64 and /48 and IPv4 address and /24; claiming a name is limited by a separate safety ceiling (5 000 a day) and by those prefix limits, and the authority's weekly budget is charged when a name first publishes a proof record (once per name, renewals free, durable in the registry), under per-prefix limits of its own. - IPv4 callers on a dual-stack listener (::ffff:a.b.c.d) shared one slot: every table now makes the address canonical first. - The pool of unfinished hellos also counts per /48 and /24, and a reserve is kept for addresses that held a proven line lately (the server name is not known before the hello, so it is for who calls, not what is asked). - A static account-binding secret was served to anyone with a name: the list file may no longer carry one (refused at load), a binding comes only from a per-app source, and an authority that needs one and has none is served without and marked not usable. - Blocking now reaches a live line: the next publish and a sweep every 10 s close it. - Unclaimed, held-by-another-key and blocked names answer a stranger the same. - A hostile app and caller could make a line hold 13 MiB: yamux fixes each stream's window at 256 KiB, so the stream limits are 8+2+4 (3.5 MiB), and the splice has a minimum rate in place of a per-write stall check. - DNS answers truncated over the per-address rate, has a global ceiling, answers CAA from the authority list (issue per authority, dns-01 only), and passes over a Windows UDP connection reset without sleeping. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
8988769015
commit
13adeac382
14 files changed
+1920
-294
No files matched your search
+160
-59
@@ -7,19 +7,33 @@
|
|||||||
//! or ZeroSSL, or adding one, is an edit to the list the relay reads, with
|
//! or ZeroSSL, or adding one, is an edit to the list the relay reads, with
|
||||||
//! no release of the app.
|
//! 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
|
//! ```toml
|
||||||
//! [[authority]]
|
//! [[authority]]
|
||||||
//! id = "letsencrypt"
|
//! id = "letsencrypt"
|
||||||
//! directory = "https://acme-v02.api.letsencrypt.org/directory"
|
//! directory = "https://acme-v02.api.letsencrypt.org/directory"
|
||||||
|
//! caa_domain = "letsencrypt.org"
|
||||||
//!
|
//!
|
||||||
//! [[authority]]
|
//! [[authority]]
|
||||||
//! id = "zerossl"
|
//! id = "zerossl"
|
||||||
//! directory = "https://acme.zerossl.com/v2/DV90"
|
//! directory = "https://acme.zerossl.com/v2/DV90"
|
||||||
|
//! caa_domain = "sectigo.com"
|
||||||
//! needs_binding = true
|
//! needs_binding = true
|
||||||
//! binding_kid = "…"
|
|
||||||
//! binding_hmac_key = "…"
|
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
|
//! 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
|
//! ```text
|
||||||
//! GOAL: the authority an app asks is chosen by the relay's list at the
|
//! 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
|
//! moment of the request, in the list's order, so an operator can
|
||||||
@@ -29,17 +43,23 @@
|
|||||||
//! INVARIANTS:
|
//! INVARIANTS:
|
||||||
//! 1. The list is served in the order written, with each authority's
|
//! 1. The list is served in the order written, with each authority's
|
||||||
//! directory address and whether it needs a binding.
|
//! directory address and whether it needs a binding.
|
||||||
//! 2. An authority that needs a binding is served only with one: a
|
//! 2. No binding secret is ever served from the file: a file that
|
||||||
//! list that names one without a credential is refused when read,
|
//! carries one is refused (a new file leaves the old list in force),
|
||||||
//! and the previous list stays 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.
|
//! 3. A bad file never replaces a good list.
|
||||||
//! 4. The list is bounded: at most 16 authorities.
|
//! 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:
|
//! SCENARIOS:
|
||||||
//! 1. Two authorities, the first plain and the second with a binding,
|
//! 1. Two authorities, the first plain and the second needing a binding,
|
||||||
//! are served in that order, the second with its credential.
|
//! 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
|
//! 2. The file is edited to put the second first: the next read serves
|
||||||
//! that order.
|
//! that order.
|
||||||
//! 3. The file is edited to garbage: the old list is still served.
|
//! 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::path::PathBuf;
|
||||||
@@ -65,8 +85,10 @@ struct File {
|
|||||||
struct Entry {
|
struct Entry {
|
||||||
id: String,
|
id: String,
|
||||||
directory: String,
|
directory: String,
|
||||||
|
caa_domain: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
needs_binding: bool,
|
needs_binding: bool,
|
||||||
|
// Never accepted: read only to be refused in words.
|
||||||
binding_kid: Option<String>,
|
binding_kid: Option<String>,
|
||||||
binding_hmac_key: Option<String>,
|
binding_hmac_key: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -85,9 +107,9 @@ pub enum ListError {
|
|||||||
Invalid(String),
|
Invalid(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where an app's binding credential comes from. The static list gives
|
/// Where an app's binding credential comes from: one per app, obtained
|
||||||
/// every app the credential written in the file; a deployment that
|
/// from the authority's own API by a deployment that implements this. The
|
||||||
/// obtains one per app from the authority's API implements this instead.
|
/// list file never carries one.
|
||||||
pub trait BindingSource: Send + Sync {
|
pub trait BindingSource: Send + Sync {
|
||||||
/// The credential for this app at this authority, if one is needed.
|
/// The credential for this app at this authority, if one is needed.
|
||||||
fn binding_for(&self, authority_id: &str, name: &Name) -> Option<Binding>;
|
fn binding_for(&self, authority_id: &str, name: &Name) -> Option<Binding>;
|
||||||
@@ -98,7 +120,7 @@ struct Listed {
|
|||||||
id: String,
|
id: String,
|
||||||
directory: String,
|
directory: String,
|
||||||
needs_binding: bool,
|
needs_binding: bool,
|
||||||
binding: Option<Binding>,
|
caa_domain: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The list the relay serves.
|
/// The list the relay serves.
|
||||||
@@ -115,6 +137,21 @@ fn is_loopback_http(url: &str) -> bool {
|
|||||||
.any(|p| url.starts_with(p))
|
.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> {
|
fn parse(text: &str) -> Result<Vec<Listed>, ListError> {
|
||||||
let file: File = toml::from_str(text)?;
|
let file: File = toml::from_str(text)?;
|
||||||
if file.authority.is_empty() || file.authority.len() > MAX_AUTHORITIES {
|
if file.authority.is_empty() || file.authority.len() > MAX_AUTHORITIES {
|
||||||
@@ -136,19 +173,19 @@ fn parse(text: &str) -> Result<Vec<Listed>, ListError> {
|
|||||||
e.id
|
e.id
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
let binding = match (e.binding_kid, e.binding_hmac_key) {
|
if e.binding_kid.is_some() || e.binding_hmac_key.is_some() {
|
||||||
(Some(kid), Some(hmac_key)) => Some(Binding { kid, hmac_key }),
|
|
||||||
(None, None) => None,
|
|
||||||
_ => {
|
|
||||||
return Err(ListError::Invalid(format!(
|
|
||||||
"{}: a binding needs both its kid and its key",
|
|
||||||
e.id
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if e.needs_binding && binding.is_none() {
|
|
||||||
return Err(ListError::Invalid(format!(
|
return Err(ListError::Invalid(format!(
|
||||||
"{} needs a binding and has none",
|
"{}: 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
|
e.id
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
@@ -156,7 +193,7 @@ fn parse(text: &str) -> Result<Vec<Listed>, ListError> {
|
|||||||
id: e.id,
|
id: e.id,
|
||||||
directory: e.directory,
|
directory: e.directory,
|
||||||
needs_binding: e.needs_binding,
|
needs_binding: e.needs_binding,
|
||||||
binding,
|
caa_domain: e.caa_domain,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Ok(out)
|
Ok(out)
|
||||||
@@ -196,7 +233,8 @@ impl AuthorityList {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Take bindings from `source` instead of the file's.
|
/// 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 {
|
pub fn with_binding_source(mut self, source: Arc<dyn BindingSource>) -> Self {
|
||||||
self.bindings = Some(source);
|
self.bindings = Some(source);
|
||||||
self
|
self
|
||||||
@@ -225,21 +263,37 @@ impl AuthorityList {
|
|||||||
pub fn for_app(&self, name: &Name) -> Vec<Authority> {
|
pub fn for_app(&self, name: &Name) -> Vec<Authority> {
|
||||||
let list = Arc::clone(&self.current.read().unwrap_or_else(|p| p.into_inner()));
|
let list = Arc::clone(&self.current.read().unwrap_or_else(|p| p.into_inner()));
|
||||||
list.iter()
|
list.iter()
|
||||||
.map(|a| Authority {
|
.map(|a| {
|
||||||
id: a.id.clone(),
|
let binding = if a.needs_binding {
|
||||||
directory: a.directory.clone(),
|
|
||||||
needs_binding: a.needs_binding,
|
|
||||||
binding: if a.needs_binding {
|
|
||||||
self.bindings
|
self.bindings
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|b| b.binding_for(&a.id, name))
|
.and_then(|b| b.binding_for(&a.id, name))
|
||||||
.or_else(|| a.binding.clone())
|
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
},
|
};
|
||||||
|
Authority {
|
||||||
|
id: a.id.clone(),
|
||||||
|
directory: a.directory.clone(),
|
||||||
|
needs_binding: a.needs_binding,
|
||||||
|
usable: !a.needs_binding || binding.is_some(),
|
||||||
|
binding,
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.collect()
|
.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)]
|
#[cfg(test)]
|
||||||
@@ -250,51 +304,92 @@ mod tests {
|
|||||||
[[authority]]
|
[[authority]]
|
||||||
id = "letsencrypt"
|
id = "letsencrypt"
|
||||||
directory = "https://acme-v02.api.letsencrypt.org/directory"
|
directory = "https://acme-v02.api.letsencrypt.org/directory"
|
||||||
|
caa_domain = "letsencrypt.org"
|
||||||
|
|
||||||
[[authority]]
|
[[authority]]
|
||||||
id = "zerossl"
|
id = "zerossl"
|
||||||
directory = "https://acme.zerossl.com/v2/DV90"
|
directory = "https://acme.zerossl.com/v2/DV90"
|
||||||
|
caa_domain = "sectigo.com"
|
||||||
needs_binding = true
|
needs_binding = true
|
||||||
binding_kid = "kid-1"
|
|
||||||
binding_hmac_key = "a2V5"
|
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
fn name() -> Name {
|
fn name() -> Name {
|
||||||
Name::parse("ledger-accrual-tally-mint").unwrap()
|
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]
|
#[test]
|
||||||
fn the_list_is_served_in_order_with_its_binding() {
|
fn the_list_is_served_in_order_and_a_binding_comes_only_from_a_source() {
|
||||||
let l = AuthorityList::from_toml(TWO).unwrap();
|
let l = AuthorityList::from_toml(TWO).unwrap();
|
||||||
let got = l.for_app(&name());
|
let got = l.for_app(&name());
|
||||||
assert_eq!(got.len(), 2);
|
assert_eq!(got.len(), 2);
|
||||||
assert_eq!(got[0].id, "letsencrypt");
|
assert_eq!(got[0].id, "letsencrypt");
|
||||||
assert!(!got[0].needs_binding && got[0].binding.is_none());
|
assert!(!got[0].needs_binding && got[0].binding.is_none() && got[0].usable);
|
||||||
assert_eq!(got[1].id, "zerossl");
|
assert_eq!(got[1].id, "zerossl");
|
||||||
assert!(got[1].needs_binding);
|
// 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!(
|
assert_eq!(
|
||||||
got[1].binding,
|
got[1].binding,
|
||||||
Some(Binding {
|
Some(Binding {
|
||||||
kid: "kid-1".into(),
|
kid: "zerossl-ledger-accrual-tally-mint".into(),
|
||||||
hmac_key: "a2V5".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]
|
#[test]
|
||||||
fn a_bad_list_is_refused() {
|
fn a_bad_list_is_refused() {
|
||||||
for bad in [
|
for bad in [
|
||||||
"",
|
"",
|
||||||
"[[authority]]\nid='a'\ndirectory='http://example.com/dir'\n",
|
"[[authority]]\nid='a'\ndirectory='http://example.com/dir'\ncaa_domain='x.example'\n",
|
||||||
"[[authority]]\nid='a'\ndirectory='https://x/d'\nneeds_binding=true\n",
|
// no caa_domain, and a caa_domain that is not a plain domain name
|
||||||
"[[authority]]\nid='a'\ndirectory='https://x/d'\nbinding_kid='k'\n",
|
"[[authority]]\nid='a'\ndirectory='https://x/d'\n",
|
||||||
"[[authority]]\nid='a'\ndirectory='https://x/d'\n[[authority]]\nid='a'\ndirectory='https://y/d'\n",
|
"[[authority]]\nid='a'\ndirectory='https://x/d'\ncaa_domain='x.example; accounturi=y'\n",
|
||||||
"[[authority]]\nid='a'\ndirectory='https://x/d'\nsurprise=1\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:?}");
|
assert!(AuthorityList::from_toml(bad).is_err(), "{bad:?}");
|
||||||
}
|
}
|
||||||
let many: String = (0..17)
|
let many: String = (0..17)
|
||||||
.map(|i| format!("[[authority]]\nid='a{i}'\ndirectory='https://x/d'\n"))
|
.map(|i| {
|
||||||
|
format!(
|
||||||
|
"[[authority]]\nid='a{i}'\ndirectory='https://x/d'\ncaa_domain='x.example'\n"
|
||||||
|
)
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
assert!(AuthorityList::from_toml(&many).is_err());
|
assert!(AuthorityList::from_toml(&many).is_err());
|
||||||
}
|
}
|
||||||
@@ -306,37 +401,43 @@ binding_hmac_key = "a2V5"
|
|||||||
std::fs::write(&path, TWO).unwrap();
|
std::fs::write(&path, TWO).unwrap();
|
||||||
let l = AuthorityList::from_file(path.clone()).unwrap();
|
let l = AuthorityList::from_file(path.clone()).unwrap();
|
||||||
assert_eq!(l.for_app(&name())[0].id, "letsencrypt");
|
assert_eq!(l.for_app(&name())[0].id, "letsencrypt");
|
||||||
let flipped = "[[authority]]\nid='zerossl'\ndirectory='https://acme.zerossl.com/v2/DV90'\nneeds_binding=true\nbinding_kid='k'\nbinding_hmac_key='a2V5'\n[[authority]]\nid='letsencrypt'\ndirectory='https://acme-v02.api.letsencrypt.org/directory'\n";
|
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();
|
std::fs::write(&path, flipped).unwrap();
|
||||||
// Same-second edits may not move the mtime: force it to look new.
|
// Same-second edits may not move the mtime: force it to look new.
|
||||||
*l.seen.lock().unwrap() = None;
|
*l.seen.lock().unwrap() = None;
|
||||||
assert!(l.reload().unwrap());
|
assert!(l.reload().unwrap());
|
||||||
assert_eq!(l.for_app(&name())[0].id, "zerossl");
|
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();
|
std::fs::write(&path, "not toml {{{").unwrap();
|
||||||
*l.seen.lock().unwrap() = None;
|
*l.seen.lock().unwrap() = None;
|
||||||
assert!(l.reload().is_err());
|
assert!(l.reload().is_err());
|
||||||
assert_eq!(l.for_app(&name())[0].id, "zerossl", "the good list stands");
|
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]
|
#[test]
|
||||||
fn a_binding_source_overrides_the_file() {
|
fn a_binding_source_is_asked_only_for_authorities_that_need_one() {
|
||||||
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(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let l = AuthorityList::from_toml(TWO)
|
let l = AuthorityList::from_toml(TWO)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.with_binding_source(Arc::new(PerApp));
|
.with_binding_source(Arc::new(PerApp));
|
||||||
let got = l.for_app(&name());
|
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!(
|
assert_eq!(
|
||||||
got[1].binding.as_ref().unwrap().kid,
|
AuthorityList::from_toml(text).unwrap().caa_issuers(),
|
||||||
"zerossl-ledger-accrual-tally-mint"
|
["x.example"]
|
||||||
);
|
);
|
||||||
assert!(got[0].binding.is_none());
|
assert!(AuthorityList::empty().caa_issuers().is_empty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,7 +74,7 @@ pub struct Incoming {
|
|||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
pub struct LineOptions {
|
pub struct LineOptions {
|
||||||
/// Streams at once on the line. At least the relay's `streams_per_app`
|
/// Streams at once on the line. At least the relay's `streams_per_app`
|
||||||
/// plus `control_streams_per_app` plus 16, or the relay's opens are
|
/// plus `control_streams_per_app` plus 4, or the relay's opens are
|
||||||
/// refused.
|
/// refused.
|
||||||
pub max_streams: usize,
|
pub max_streams: usize,
|
||||||
/// How long a caller stream may take to send its address header.
|
/// How long a caller stream may take to send its address header.
|
||||||
|
|||||||
+79
-14
@@ -35,8 +35,22 @@ pub struct Limits {
|
|||||||
pub max_connections: usize,
|
pub max_connections: usize,
|
||||||
/// Connections that have not yet sent a whole ClientHello.
|
/// Connections that have not yet sent a whole ClientHello.
|
||||||
pub max_pending_hellos: usize,
|
pub max_pending_hellos: usize,
|
||||||
/// Of those, from one address. Strict: this is the slow-loris limit.
|
/// Of those, from one address (an IPv4 address, an IPv6 /64). Strict:
|
||||||
|
/// this is the slow-loris limit.
|
||||||
pub max_pending_per_ip: u32,
|
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'
|
/// Connections from one address, all stages. Generous: the AI vendors'
|
||||||
/// callers share a few addresses between all their users.
|
/// callers share a few addresses between all their users.
|
||||||
pub max_connections_per_ip: u32,
|
pub max_connections_per_ip: u32,
|
||||||
@@ -44,6 +58,11 @@ pub struct Limits {
|
|||||||
pub hello_timeout_ms: u64,
|
pub hello_timeout_ms: u64,
|
||||||
/// Line handshakes (TLS and proof) in progress at once.
|
/// Line handshakes (TLS and proof) in progress at once.
|
||||||
pub max_handshakes: usize,
|
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.
|
/// How long a line's TLS handshake and proof may take in all.
|
||||||
pub handshake_timeout_ms: u64,
|
pub handshake_timeout_ms: u64,
|
||||||
/// How long to wait for the app to open a stream for a caller.
|
/// How long to wait for the app to open a stream for a caller.
|
||||||
@@ -56,9 +75,13 @@ pub struct Limits {
|
|||||||
pub copy_buffer: usize,
|
pub copy_buffer: usize,
|
||||||
/// A spliced connection with no byte either way this long is closed.
|
/// A spliced connection with no byte either way this long is closed.
|
||||||
pub stream_idle_ms: u64,
|
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.
|
/// A spliced connection's longest life.
|
||||||
pub stream_max_age_ms: u64,
|
pub stream_max_age_ms: u64,
|
||||||
/// A write that makes no progress this long ends the connection: a
|
/// The grace on every write, before the rate above is asked for: a
|
||||||
/// slow reader is closed, not buffered for.
|
/// slow reader is closed, not buffered for.
|
||||||
pub write_stall_ms: u64,
|
pub write_stall_ms: u64,
|
||||||
/// A line from which nothing has been read this long is dropped. The
|
/// A line from which nothing has been read this long is dropped. The
|
||||||
@@ -74,21 +97,46 @@ pub struct Limits {
|
|||||||
pub txt_per_name: usize,
|
pub txt_per_name: usize,
|
||||||
/// Publishes one name may make in an hour.
|
/// Publishes one name may make in an hour.
|
||||||
pub txt_publishes_per_hour: u32,
|
pub txt_publishes_per_hour: u32,
|
||||||
/// New names that may be claimed in one window, over all apps.
|
/// 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,
|
pub claims_per_window: u32,
|
||||||
/// The window for `claims_per_window`: a week, the certificate
|
/// The window for `claims_per_window`.
|
||||||
/// authority's new-certificate limit.
|
|
||||||
pub claim_window_ms: u64,
|
pub claim_window_ms: u64,
|
||||||
/// New names one address may claim in `claim_ip_window_ms`.
|
/// New names one address (an IPv4 address, an IPv6 /64) may claim in
|
||||||
|
/// `claim_ip_window_ms`.
|
||||||
pub claims_per_ip: u32,
|
pub claims_per_ip: u32,
|
||||||
/// The window for `claims_per_ip`.
|
/// 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,
|
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.
|
/// Registry requests queued at most; past this the relay says busy.
|
||||||
pub registry_queue: usize,
|
pub registry_queue: usize,
|
||||||
/// Slots in each fixed per-address table (a power of two).
|
/// Slots in each fixed per-address table (a power of two).
|
||||||
pub ip_slots: usize,
|
pub ip_slots: usize,
|
||||||
/// DNS queries per second one address may send, sustained.
|
/// 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,
|
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.
|
/// TCP DNS connections open at once.
|
||||||
pub dns_tcp_max: usize,
|
pub dns_tcp_max: usize,
|
||||||
/// TCP DNS connections from one address.
|
/// TCP DNS connections from one address.
|
||||||
@@ -104,30 +152,44 @@ impl Default for Limits {
|
|||||||
max_connections: 1_000_000,
|
max_connections: 1_000_000,
|
||||||
max_pending_hellos: 4_096,
|
max_pending_hellos: 4_096,
|
||||||
max_pending_per_ip: 32,
|
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,
|
max_connections_per_ip: 20_000,
|
||||||
hello_timeout_ms: 8_000,
|
hello_timeout_ms: 8_000,
|
||||||
max_handshakes: 1_024,
|
max_handshakes: 1_024,
|
||||||
|
max_handshakes_per_ip: 4,
|
||||||
|
max_handshakes_per_net: 64,
|
||||||
handshake_timeout_ms: 10_000,
|
handshake_timeout_ms: 10_000,
|
||||||
open_stream_timeout_ms: 5_000,
|
open_stream_timeout_ms: 5_000,
|
||||||
streams_per_app: 32,
|
streams_per_app: 8,
|
||||||
control_streams_per_app: 4,
|
control_streams_per_app: 2,
|
||||||
copy_buffer: 8 * 1024,
|
copy_buffer: 8 * 1024,
|
||||||
stream_idle_ms: 10 * 60_000,
|
stream_idle_ms: 10 * 60_000,
|
||||||
stream_max_age_ms: 6 * 3_600_000,
|
stream_max_age_ms: 6 * 3_600_000,
|
||||||
write_stall_ms: 30_000,
|
min_stream_bytes_per_sec: 2_048,
|
||||||
|
write_stall_ms: 5_000,
|
||||||
line_idle_ms: 180_000,
|
line_idle_ms: 180_000,
|
||||||
control_timeout_ms: 10_000,
|
control_timeout_ms: 10_000,
|
||||||
txt_ttl_ms: 10 * 60_000,
|
txt_ttl_ms: 10 * 60_000,
|
||||||
txt_max_entries: 100_000,
|
txt_max_entries: 100_000,
|
||||||
txt_per_name: 4,
|
txt_per_name: 4,
|
||||||
txt_publishes_per_hour: 12,
|
txt_publishes_per_hour: 12,
|
||||||
claims_per_window: 50,
|
claims_per_window: 5_000,
|
||||||
claim_window_ms: 7 * 24 * 3_600_000,
|
claim_window_ms: 24 * 3_600_000,
|
||||||
claims_per_ip: 5,
|
claims_per_ip: 5,
|
||||||
|
claims_per_net: 20,
|
||||||
claim_ip_window_ms: 24 * 3_600_000,
|
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,
|
registry_queue: 256,
|
||||||
ip_slots: 1 << 16,
|
ip_slots: 1 << 16,
|
||||||
dns_qps_per_ip: 20,
|
dns_qps_per_ip: 20,
|
||||||
|
dns_qps_global: 5_000,
|
||||||
dns_tcp_max: 512,
|
dns_tcp_max: 512,
|
||||||
dns_tcp_per_ip: 8,
|
dns_tcp_per_ip: 8,
|
||||||
dns_tcp_timeout_ms: 5_000,
|
dns_tcp_timeout_ms: 5_000,
|
||||||
@@ -158,6 +220,9 @@ durations! {
|
|||||||
txt_ttl => txt_ttl_ms,
|
txt_ttl => txt_ttl_ms,
|
||||||
claim_window => claim_window_ms,
|
claim_window => claim_window_ms,
|
||||||
claim_ip_window => claim_ip_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,
|
dns_tcp_timeout => dns_tcp_timeout_ms,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,7 +290,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn defaults_load_and_unknown_keys_are_refused() {
|
fn defaults_load_and_unknown_keys_are_refused() {
|
||||||
let c = Config::from_toml("").expect("empty is the defaults");
|
let c = Config::from_toml("").expect("empty is the defaults");
|
||||||
assert_eq!(c.limits.streams_per_app, 32);
|
assert_eq!(c.limits.streams_per_app, 8);
|
||||||
let c = Config::from_toml("[limits]\nstreams_per_app = 4\n").unwrap();
|
let c = Config::from_toml("[limits]\nstreams_per_app = 4\n").unwrap();
|
||||||
assert_eq!(c.limits.streams_per_app, 4);
|
assert_eq!(c.limits.streams_per_app, 4);
|
||||||
assert!(Config::from_toml("bogus = 1").is_err());
|
assert!(Config::from_toml("bogus = 1").is_err());
|
||||||
|
|||||||
+195
-9
@@ -1,12 +1,16 @@
|
|||||||
//! The domain's authoritative DNS server.
|
//! The domain's authoritative DNS server.
|
||||||
//!
|
//!
|
||||||
//! The relay answers for `wanderbooks.link` itself, over UDP and TCP.
|
//! The relay answers for `wanderbooks.link` itself, over UDP and TCP.
|
||||||
//! It answers two questions and refuses the rest:
|
//! It answers three questions and refuses the rest:
|
||||||
//!
|
//!
|
||||||
//! - any name under the domain is at the relay's address (A, AAAA), the
|
//! - any name under the domain is at the relay's address (A, AAAA), the
|
||||||
//! name servers at their own;
|
//! name servers at their own;
|
||||||
//! - `TXT _acme-challenge.<four-words>.<domain>` is the proof value that
|
//! - `TXT _acme-challenge.<four-words>.<domain>` is the proof value that
|
||||||
//! app just handed in, held in memory for minutes.
|
//! 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
|
//! 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)
|
//! catch-all that stops covering names under a label of its own (RFC 4592)
|
||||||
@@ -32,7 +36,15 @@
|
|||||||
//! 5. The server holds no per-query state: the UDP loop answers inline
|
//! 5. The server holds no per-query state: the UDP loop answers inline
|
||||||
//! from fixed tables, and TCP is capped in connections, in queries
|
//! from fixed tables, and TCP is capped in connections, in queries
|
||||||
//! per connection and in time.
|
//! per connection and in time.
|
||||||
//! 6. Per address, UDP queries are rate limited from a fixed table.
|
//! 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:
|
//! SCENARIOS:
|
||||||
//! 1. A for `x.<secret>.<name>.<domain>` is the relay's address, with
|
//! 1. A for `x.<secret>.<name>.<domain>` is the relay's address, with
|
||||||
//! and without a TXT record published for that name.
|
//! and without a TXT record published for that name.
|
||||||
@@ -40,7 +52,10 @@
|
|||||||
//! returns nothing after the value expires.
|
//! returns nothing after the value expires.
|
||||||
//! 3. A for `example.com` is REFUSED; ANY is answered with no data.
|
//! 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
|
//! 4. A hundred queries in a burst from one address: the excess is
|
||||||
//! dropped.
|
//! 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::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||||
@@ -48,6 +63,7 @@ use std::sync::Arc;
|
|||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
use hickory_proto::op::{Edns, Message, MessageType, OpCode, ResponseCode};
|
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::rdata::{A, AAAA, NS, SOA, TXT};
|
||||||
use hickory_proto::rr::{DNSClass, Name as DnsName, RData, Record, RecordType};
|
use hickory_proto::rr::{DNSClass, Name as DnsName, RData, Record, RecordType};
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
@@ -55,8 +71,9 @@ use tokio::net::{TcpListener, UdpSocket};
|
|||||||
use tokio::sync::Semaphore;
|
use tokio::sync::Semaphore;
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
|
use crate::authorities::AuthorityList;
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::gate::{IpGate, RateTable};
|
use crate::gate::{IpGate, RateTable, TokenBucket};
|
||||||
use crate::names::{Name, Zone};
|
use crate::names::{Name, Zone};
|
||||||
use crate::txt::TxtStore;
|
use crate::txt::TxtStore;
|
||||||
|
|
||||||
@@ -77,11 +94,18 @@ pub struct DnsService {
|
|||||||
v6: Vec<Ipv6Addr>,
|
v6: Vec<Ipv6Addr>,
|
||||||
nameservers: Vec<(String, DnsName, Vec<IpAddr>)>,
|
nameservers: Vec<(String, DnsName, Vec<IpAddr>)>,
|
||||||
txt: Arc<TxtStore>,
|
txt: Arc<TxtStore>,
|
||||||
|
authorities: Arc<AuthorityList>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DnsService {
|
impl DnsService {
|
||||||
/// A service for the configured domain.
|
/// A service for the configured domain. `authorities` is the list the
|
||||||
pub fn new(zone: Zone, cfg: &Config, txt: Arc<TxtStore>) -> Result<Self, String> {
|
/// 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 =
|
let domain =
|
||||||
DnsName::from_ascii(format!("{}.", zone.domain())).map_err(|e| e.to_string())?;
|
DnsName::from_ascii(format!("{}.", zone.domain())).map_err(|e| e.to_string())?;
|
||||||
let mut nameservers = Vec::new();
|
let mut nameservers = Vec::new();
|
||||||
@@ -107,9 +131,56 @@ impl DnsService {
|
|||||||
v6: cfg.address_v6.clone(),
|
v6: cfg.address_v6.clone(),
|
||||||
nameservers,
|
nameservers,
|
||||||
txt,
|
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 {
|
fn soa(&self) -> Record {
|
||||||
let mname = self
|
let mname = self
|
||||||
.nameservers
|
.nameservers
|
||||||
@@ -231,6 +302,7 @@ impl DnsService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
RecordType::CAA if apex => resp.answers = self.caa(),
|
||||||
RecordType::TXT => {
|
RecordType::TXT => {
|
||||||
if let ["_acme-challenge", name] = labels.as_slice()
|
if let ["_acme-challenge", name] = labels.as_slice()
|
||||||
&& let Ok(name) = Name::parse(&name.to_ascii_lowercase())
|
&& let Ok(name) = Name::parse(&name.to_ascii_lowercase())
|
||||||
@@ -270,21 +342,35 @@ impl DnsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Serve UDP until cancelled. Answers are made inline, with no task per
|
/// Serve UDP until cancelled. Answers are made inline, with no task per
|
||||||
/// query, and a sender over its rate gets no answer.
|
/// 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(
|
pub async fn serve_udp(
|
||||||
socket: Arc<UdpSocket>,
|
socket: Arc<UdpSocket>,
|
||||||
svc: Arc<DnsService>,
|
svc: Arc<DnsService>,
|
||||||
qps: u32,
|
qps: u32,
|
||||||
|
global_qps: u32,
|
||||||
slots: usize,
|
slots: usize,
|
||||||
cancel: CancellationToken,
|
cancel: CancellationToken,
|
||||||
) {
|
) {
|
||||||
let mut rate = RateTable::new(slots, qps, qps.saturating_mul(2).max(1));
|
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];
|
let mut buf = vec![0u8; QUERY_MAX + 1];
|
||||||
loop {
|
loop {
|
||||||
let (n, from) = tokio::select! {
|
let (n, from) = tokio::select! {
|
||||||
() = cancel.cancelled() => return,
|
() = cancel.cancelled() => return,
|
||||||
r = socket.recv_from(&mut buf) => match r {
|
r = socket.recv_from(&mut buf) => match r {
|
||||||
Ok(x) => x,
|
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(_) => {
|
Err(_) => {
|
||||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||||
continue;
|
continue;
|
||||||
@@ -292,7 +378,13 @@ pub async fn serve_udp(
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
|
if !global.allow(now) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if !rate.allow(from.ip(), now) {
|
if !rate.allow(from.ip(), now) {
|
||||||
|
if let Some(out) = svc.truncated(&buf[..n]) {
|
||||||
|
let _ = socket.try_send_to(&out, from);
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if let Some(out) = svc.answer(&buf[..n], true, now) {
|
if let Some(out) = svc.answer(&buf[..n], true, now) {
|
||||||
@@ -412,7 +504,14 @@ mod tests {
|
|||||||
};
|
};
|
||||||
let txt = Arc::new(TxtStore::new(Duration::from_secs(60), 100, 4, 100));
|
let txt = Arc::new(TxtStore::new(Duration::from_secs(60), 100, 4, 100));
|
||||||
let zone = Zone::new(&cfg.domain, &cfg.relay_host);
|
let zone = Zone::new(&cfg.domain, &cfg.relay_host);
|
||||||
(DnsService::new(zone, &cfg, Arc::clone(&txt)).unwrap(), txt)
|
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 {
|
fn ask(svc: &DnsService, name: &str, ty: RecordType, udp: bool) -> Message {
|
||||||
@@ -620,4 +719,91 @@ mod tests {
|
|||||||
assert!(bytes.len() <= 512);
|
assert!(bytes.len() <= 512);
|
||||||
assert!(!m.metadata.truncation);
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+369
-41
@@ -6,9 +6,19 @@
|
|||||||
//! may share a slot, which makes the limit slightly stricter for both,
|
//! may share a slot, which makes the limit slightly stricter for both,
|
||||||
//! never looser. The memory is the same however many addresses call.
|
//! 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
|
//! ```text
|
||||||
//! GOAL: limit what one address can hold open or ask for, in memory that
|
//! GOAL: limit what one address, and one network, can hold open or ask
|
||||||
//! does not depend on how many addresses there are.
|
//! for, in memory that does not depend on how many addresses there
|
||||||
|
//! are.
|
||||||
//! SOURCE: WB-relay-7 (bounds).
|
//! SOURCE: WB-relay-7 (bounds).
|
||||||
//! INVARIANTS:
|
//! INVARIANTS:
|
||||||
//! 1. The table never allocates after it is made.
|
//! 1. The table never allocates after it is made.
|
||||||
@@ -16,16 +26,59 @@
|
|||||||
//! permit is dropped every slot reads zero.
|
//! permit is dropped every slot reads zero.
|
||||||
//! 3. An address is refused once its slot holds `limit` permits, and
|
//! 3. An address is refused once its slot holds `limit` permits, and
|
||||||
//! never admitted past it.
|
//! 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:
|
//! SCENARIOS:
|
||||||
//! 1. A limit of 2: two permits for one address, the third is refused;
|
//! 1. A limit of 2: two permits for one address, the third is refused;
|
||||||
//! dropping one lets a new one in.
|
//! dropping one lets a new one in.
|
||||||
//! 2. IPv6 addresses count by /64.
|
//! 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::hash::{BuildHasher, RandomState};
|
||||||
use std::net::IpAddr;
|
use std::net::IpAddr;
|
||||||
use std::sync::Arc;
|
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
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.
|
/// A fixed table of per-address counters.
|
||||||
pub struct IpGate {
|
pub struct IpGate {
|
||||||
@@ -33,6 +86,7 @@ pub struct IpGate {
|
|||||||
mask: usize,
|
mask: usize,
|
||||||
state: RandomState,
|
state: RandomState,
|
||||||
limit: u32,
|
limit: u32,
|
||||||
|
reach: Reach,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One held place in an [`IpGate`]; dropping it frees the place.
|
/// One held place in an [`IpGate`]; dropping it frees the place.
|
||||||
@@ -43,29 +97,30 @@ pub struct IpPermit {
|
|||||||
|
|
||||||
impl IpGate {
|
impl IpGate {
|
||||||
/// A table of `slots` (rounded up to a power of two), each address
|
/// A table of `slots` (rounded up to a power of two), each address
|
||||||
/// allowed `limit` permits at once.
|
/// (an IPv4 address, an IPv6 /64) allowed `limit` permits at once.
|
||||||
pub fn new(slots: usize, limit: u32) -> Arc<Self> {
|
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();
|
let n = slots.max(2).next_power_of_two();
|
||||||
Arc::new(IpGate {
|
Arc::new(IpGate {
|
||||||
slots: (0..n).map(|_| AtomicU32::new(0)).collect(),
|
slots: (0..n).map(|_| AtomicU32::new(0)).collect(),
|
||||||
mask: n - 1,
|
mask: n - 1,
|
||||||
state: RandomState::new(),
|
state: RandomState::new(),
|
||||||
limit,
|
limit,
|
||||||
|
reach,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn slot(&self, ip: IpAddr) -> usize {
|
fn slot(&self, ip: IpAddr) -> usize {
|
||||||
let key = match ip {
|
|
||||||
IpAddr::V4(v4) => u128::from(u32::from(v4)),
|
|
||||||
// An IPv6 subscriber has a /64 at least: count them together.
|
|
||||||
IpAddr::V6(v6) => {
|
|
||||||
u128::from(u64::from_be_bytes(
|
|
||||||
v6.octets()[..8].try_into().unwrap_or([0; 8]),
|
|
||||||
)) | (1 << 100)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// Truncating a hash to a table index is the point.
|
// Truncating a hash to a table index is the point.
|
||||||
(self.state.hash_one(key) as usize) & self.mask
|
(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.
|
/// Take a place for `ip`, or `None` when it already holds its limit.
|
||||||
@@ -104,52 +159,198 @@ impl Drop for IpPermit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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
|
/// A fixed table of token buckets, one per address slot, for a loop that
|
||||||
/// owns it (the UDP DNS loop). Memory is fixed.
|
/// owns it (the UDP DNS loop). Memory is fixed.
|
||||||
pub struct RateTable {
|
pub struct RateTable {
|
||||||
slots: Vec<(std::time::Instant, f64)>,
|
slots: Vec<TokenBucket>,
|
||||||
mask: usize,
|
mask: usize,
|
||||||
state: RandomState,
|
state: RandomState,
|
||||||
rate: f64,
|
|
||||||
burst: f64,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RateTable {
|
impl RateTable {
|
||||||
/// `rate` queries per second sustained, `burst` at once.
|
/// `rate` queries per second sustained, `burst` at once.
|
||||||
pub fn new(slots: usize, rate: u32, burst: u32) -> Self {
|
pub fn new(slots: usize, rate: u32, burst: u32) -> Self {
|
||||||
let n = slots.max(2).next_power_of_two();
|
let n = slots.max(2).next_power_of_two();
|
||||||
let now = std::time::Instant::now();
|
|
||||||
RateTable {
|
RateTable {
|
||||||
slots: vec![(now, f64::from(burst)); n],
|
slots: vec![TokenBucket::new(rate, burst, Instant::now()); n],
|
||||||
mask: n - 1,
|
mask: n - 1,
|
||||||
state: RandomState::new(),
|
state: RandomState::new(),
|
||||||
rate: f64::from(rate),
|
|
||||||
burst: f64::from(burst),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spend one token for `ip` at `now`; false when it has none.
|
/// Spend one token for `ip` at `now`; false when it has none.
|
||||||
pub fn allow(&mut self, ip: IpAddr, now: std::time::Instant) -> bool {
|
pub fn allow(&mut self, ip: IpAddr, now: Instant) -> bool {
|
||||||
let key = match ip {
|
let slot = (self.state.hash_one(prefix_key(ip, Reach::Host)) as usize) & self.mask;
|
||||||
IpAddr::V4(v4) => u128::from(u32::from(v4)),
|
self.slots[slot].allow(now)
|
||||||
IpAddr::V6(v6) => {
|
}
|
||||||
u128::from(u64::from_be_bytes(
|
}
|
||||||
v6.octets()[..8].try_into().unwrap_or([0; 8]),
|
|
||||||
)) | (1 << 100)
|
/// 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
|
||||||
let slot = (self.state.hash_one(key) as usize) & self.mask;
|
/// slot chosen by a hash with a key picked at start; two prefixes sharing
|
||||||
let (last, tokens) = &mut self.slots[slot];
|
/// a slot only make the limit stricter for both.
|
||||||
let gained = now.saturating_duration_since(*last).as_secs_f64() * self.rate;
|
pub struct PrefixLimit {
|
||||||
*tokens = (*tokens + gained).min(self.burst);
|
inner: Mutex<PrefixTables>,
|
||||||
*last = now;
|
state: RandomState,
|
||||||
if *tokens >= 1.0 {
|
mask: usize,
|
||||||
*tokens -= 1.0;
|
base: Instant,
|
||||||
true
|
host: u32,
|
||||||
} else {
|
net: u32,
|
||||||
false
|
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)]
|
#[cfg(test)]
|
||||||
@@ -203,4 +404,131 @@ mod tests {
|
|||||||
assert!(!t.allow(ip, t0));
|
assert!(!t.allow(ip, t0));
|
||||||
assert!(t.allow(ip, t0 + std::time::Duration::from_millis(150)));
|
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");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -61,6 +61,10 @@ async fn main() -> ExitCode {
|
|||||||
Ok(t) => t,
|
Ok(t) => t,
|
||||||
Err(e) => return fail(&e),
|
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 {
|
let authorities = match &cfg.authorities_path {
|
||||||
Some(p) => match AuthorityList::from_file(p.clone()) {
|
Some(p) => match AuthorityList::from_file(p.clone()) {
|
||||||
Ok(l) => l,
|
Ok(l) => l,
|
||||||
|
|||||||
+13
-5
@@ -18,7 +18,13 @@
|
|||||||
//! side, is ended (that is yamux's rule), so the relay keeps its
|
//! side, is ended (that is yamux's rule), so the relay keeps its
|
||||||
//! own per-line permits below the limit.
|
//! own per-line permits below the limit.
|
||||||
//! 2. Each stream's receive window is 256 KiB and a line's windows sum
|
//! 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.
|
//! 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.
|
//! 3. A line from which nothing was read for `idle` is closed.
|
||||||
//! 4. Dropping every handle, or `close`, ends the driver.
|
//! 4. Dropping every handle, or `close`, ends the driver.
|
||||||
//! SCENARIOS:
|
//! SCENARIOS:
|
||||||
@@ -79,10 +85,12 @@ pub struct MuxLimits {
|
|||||||
fn yamux_config(max_streams: usize) -> Config {
|
fn yamux_config(max_streams: usize) -> Config {
|
||||||
let mut cfg = Config::default();
|
let mut cfg = Config::default();
|
||||||
cfg.set_max_num_streams(max_streams);
|
cfg.set_max_num_streams(max_streams);
|
||||||
// 256 KiB is yamux's initial window per stream. Capping the sum at
|
// 256 KiB is yamux's initial window per stream, and the crate fixes
|
||||||
// 256 KiB times the stream limit stops the auto-tuning from growing
|
// it (`DEFAULT_CREDIT`; the connection's cap must be at least that
|
||||||
// any window: this is the most a line can ever hold in receive
|
// times the stream limit, or it panics). Capping the sum at exactly
|
||||||
// buffers.
|
// 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.set_max_connection_receive_window(Some(max_streams * yamux::DEFAULT_CREDIT as usize));
|
||||||
cfg
|
cfg
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,11 +84,16 @@ pub struct Hello {
|
|||||||
pub enum Refusal {
|
pub enum Refusal {
|
||||||
/// The name is already held by another key.
|
/// The name is already held by another key.
|
||||||
Taken,
|
Taken,
|
||||||
/// A reconnect for a name nobody has claimed.
|
/// 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,
|
UnknownName,
|
||||||
/// The proof did not verify, or the key is not the name's.
|
/// 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,
|
BadProof,
|
||||||
/// The name is blocked by the operator.
|
/// The name is blocked by the operator, said only to the holder of its
|
||||||
|
/// key.
|
||||||
Blocked,
|
Blocked,
|
||||||
/// The relay is busy; try again later.
|
/// The relay is busy; try again later.
|
||||||
Busy,
|
Busy,
|
||||||
@@ -140,10 +145,21 @@ pub struct Authority {
|
|||||||
pub directory: String,
|
pub directory: String,
|
||||||
/// True when the authority requires an external account binding.
|
/// True when the authority requires an external account binding.
|
||||||
pub needs_binding: bool,
|
pub needs_binding: bool,
|
||||||
/// The binding credential for this app, when one is needed.
|
/// 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>,
|
pub binding: Option<Binding>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn yes() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
/// An external account binding credential (RFC 8555 section 7.3.4).
|
/// An external account binding credential (RFC 8555 section 7.3.4).
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
|
|||||||
+248
-10
@@ -1,9 +1,12 @@
|
|||||||
//! The registry: the one small durable table (D-85).
|
//! The registry: the one small durable table (D-85).
|
||||||
//!
|
//!
|
||||||
//! It holds, per name, the app's public key, when the name was claimed
|
//! It holds, per name, the app's public key, when the name was claimed,
|
||||||
//! and whether the operator has blocked it. Nothing else about an app is
|
//! whether the operator has blocked it, and when it first published a
|
||||||
//! kept anywhere: not an address, not a label, not a log of connections.
|
//! proof record (the one moment a name costs the certificate authority's
|
||||||
//! A claim, and the limit on new names, are one transaction.
|
//! 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,
|
//! 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.
|
//! so a slow disk makes the relay say "busy" and never makes it hold more.
|
||||||
@@ -21,11 +24,18 @@
|
|||||||
//! the rows' own creation times, so a restart does not reset it.
|
//! 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
|
//! 4. The queue to the database thread is bounded: past it a request
|
||||||
//! is refused as busy, not held.
|
//! 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:
|
//! SCENARIOS:
|
||||||
//! 1. Two claims of one name with different keys: one wins, the other
|
//! 1. Two claims of one name with different keys: one wins, the other
|
||||||
//! sees `Exists`.
|
//! sees `Exists`.
|
||||||
//! 2. A claim, a restart (reopen), a lookup: the key is still there.
|
//! 2. A claim, a restart (reopen), a lookup: the key is still there.
|
||||||
//! 3. The window limit counts rows made before a reopen.
|
//! 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::path::Path;
|
||||||
@@ -43,6 +53,22 @@ pub struct Entry {
|
|||||||
pub public_key: [u8; 32],
|
pub public_key: [u8; 32],
|
||||||
/// True when the operator has blocked the name.
|
/// True when the operator has blocked the name.
|
||||||
pub blocked: bool,
|
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.
|
/// How a claim ended.
|
||||||
@@ -84,6 +110,14 @@ enum Cmd {
|
|||||||
},
|
},
|
||||||
SetBlocked(String, bool, Reply<bool>),
|
SetBlocked(String, bool, Reply<bool>),
|
||||||
Count(Reply<u64>),
|
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.
|
/// A handle to the registry. Clones share one database thread.
|
||||||
@@ -115,11 +149,30 @@ impl Registry {
|
|||||||
name TEXT PRIMARY KEY,
|
name TEXT PRIMARY KEY,
|
||||||
public_key BLOB NOT NULL CHECK (length(public_key) = 32),
|
public_key BLOB NOT NULL CHECK (length(public_key) = 32),
|
||||||
created INTEGER NOT NULL,
|
created INTEGER NOT NULL,
|
||||||
blocked INTEGER NOT NULL DEFAULT 0
|
blocked INTEGER NOT NULL DEFAULT 0,
|
||||||
|
first_publish INTEGER
|
||||||
) WITHOUT ROWID;
|
) WITHOUT ROWID;
|
||||||
CREATE INDEX IF NOT EXISTS apps_created ON apps (created);",
|
CREATE INDEX IF NOT EXISTS apps_created ON apps (created);",
|
||||||
)
|
)
|
||||||
.map_err(db)?;
|
.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));
|
let (tx, mut rx) = mpsc::channel::<Cmd>(queue.max(1));
|
||||||
std::thread::Builder::new()
|
std::thread::Builder::new()
|
||||||
.name("relay-registry".into())
|
.name("relay-registry".into())
|
||||||
@@ -176,27 +229,54 @@ impl Registry {
|
|||||||
pub async fn count(&self) -> Result<u64, RegistryError> {
|
pub async fn count(&self) -> Result<u64, RegistryError> {
|
||||||
self.ask(Cmd::Count).await
|
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) -> Option<Entry> {
|
fn entry_of(key: Vec<u8>, blocked: i64, first_publish: Option<i64>) -> Option<Entry> {
|
||||||
Some(Entry {
|
Some(Entry {
|
||||||
public_key: key.try_into().ok()?,
|
public_key: key.try_into().ok()?,
|
||||||
blocked: blocked != 0,
|
blocked: blocked != 0,
|
||||||
|
published: first_publish.is_some(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lookup(conn: &Connection, name: &str) -> Result<Option<Entry>, RegistryError> {
|
fn lookup(conn: &Connection, name: &str) -> Result<Option<Entry>, RegistryError> {
|
||||||
let row: Option<(Vec<u8>, i64)> = conn
|
let row: Option<(Vec<u8>, i64, Option<i64>)> = conn
|
||||||
.query_row(
|
.query_row(
|
||||||
"SELECT public_key, blocked FROM apps WHERE name = ?1",
|
"SELECT public_key, blocked, first_publish FROM apps WHERE name = ?1",
|
||||||
params![name],
|
params![name],
|
||||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||||
)
|
)
|
||||||
.optional()
|
.optional()
|
||||||
.map_err(db)?;
|
.map_err(db)?;
|
||||||
match row {
|
match row {
|
||||||
None => Ok(None),
|
None => Ok(None),
|
||||||
Some((key, blocked)) => entry_of(key, blocked)
|
Some((key, blocked, first)) => entry_of(key, blocked, first)
|
||||||
.map(Some)
|
.map(Some)
|
||||||
.ok_or_else(|| RegistryError::Db("a stored key is not 32 bytes".into())),
|
.ok_or_else(|| RegistryError::Db("a stored key is not 32 bytes".into())),
|
||||||
}
|
}
|
||||||
@@ -234,6 +314,71 @@ fn serve(conn: &Connection, cmd: Cmd) {
|
|||||||
} => {
|
} => {
|
||||||
let _ = reply.send(claim(conn, &name, key, now, window_secs, max_new));
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,6 +447,7 @@ mod tests {
|
|||||||
let held = Entry {
|
let held = Entry {
|
||||||
public_key: [1; 32],
|
public_key: [1; 32],
|
||||||
blocked: false,
|
blocked: false,
|
||||||
|
published: false,
|
||||||
};
|
};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
reg.claim(&n, [2; 32], DAY, 10).await.unwrap(),
|
reg.claim(&n, [2; 32], DAY, 10).await.unwrap(),
|
||||||
@@ -392,4 +538,96 @@ mod tests {
|
|||||||
assert!(reg.set_blocked(&n, true).await.unwrap());
|
assert!(reg.set_blocked(&n, true).await.unwrap());
|
||||||
assert!(reg.lookup(&n).await.unwrap().unwrap().blocked);
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+281
-112
@@ -23,11 +23,26 @@
|
|||||||
//! proof, and removed when it ends; the table holds one entry per
|
//! proof, and removed when it ends; the table holds one entry per
|
||||||
//! connected app and no more than `max_lines`.
|
//! connected app and no more than `max_lines`.
|
||||||
//! 5. Every connection is counted against a global limit and a
|
//! 5. Every connection is counted against a global limit and a
|
||||||
//! per-address limit before any work is done for it, and a hello
|
//! per-address and per-network limit (an IPv4 address and /24, an
|
||||||
//! that is not complete in `hello_timeout` is closed.
|
//! 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
|
//! 6. Per app: at most `streams_per_app` caller streams and
|
||||||
//! `control_streams_per_app` control streams, each with its own
|
//! `control_streams_per_app` control streams, each with its own
|
||||||
//! timeouts; nothing queues without a bound.
|
//! 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:
|
//! SCENARIOS:
|
||||||
//! 1. An assistant connects with the app's name as server name; the app
|
//! 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
|
//! sees the caller's address, then the assistant's ClientHello, and
|
||||||
@@ -38,6 +53,10 @@
|
|||||||
//! closed at the hello timeout.
|
//! closed at the hello timeout.
|
||||||
//! 4. A client holding the right key but a recorded old proof is
|
//! 4. A client holding the right key but a recorded old proof is
|
||||||
//! refused.
|
//! 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::collections::HashMap;
|
||||||
@@ -61,7 +80,7 @@ use crate::authorities::AuthorityList;
|
|||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::dns::{DnsService, TcpLimits};
|
use crate::dns::{DnsService, TcpLimits};
|
||||||
use crate::front::{Activity, Front};
|
use crate::front::{Activity, Front};
|
||||||
use crate::gate::IpGate;
|
use crate::gate::{IpGate, IpPermit, KnownAddrs, PrefixLimit};
|
||||||
use crate::hello::{self, HelloError};
|
use crate::hello::{self, HelloError};
|
||||||
use crate::mux::{self, Mux, MuxLimits};
|
use crate::mux::{self, Mux, MuxLimits};
|
||||||
use crate::names::{HostKind, Name, Zone};
|
use crate::names::{HostKind, Name, Zone};
|
||||||
@@ -69,7 +88,7 @@ use crate::proto::{
|
|||||||
self, Caller, Challenge, EXPORTER_LABEL, Hello, Refusal, Request, Response, VERSION, Verdict,
|
self, Caller, Challenge, EXPORTER_LABEL, Hello, Refusal, Request, Response, VERSION, Verdict,
|
||||||
read_frame, write_frame,
|
read_frame, write_frame,
|
||||||
};
|
};
|
||||||
use crate::registry::{Claimed, Registry};
|
use crate::registry::{Charged, Claimed, Registry};
|
||||||
use crate::splice::{self, SpliceLimits};
|
use crate::splice::{self, SpliceLimits};
|
||||||
use crate::txt::{PublishError, TxtStore};
|
use crate::txt::{PublishError, TxtStore};
|
||||||
|
|
||||||
@@ -100,6 +119,10 @@ pub struct Metrics {
|
|||||||
pub refused_other: AtomicU64,
|
pub refused_other: AtomicU64,
|
||||||
/// Names claimed for the first time.
|
/// Names claimed for the first time.
|
||||||
pub claims: AtomicU64,
|
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.
|
/// Control requests served.
|
||||||
pub control: AtomicU64,
|
pub control: AtomicU64,
|
||||||
/// Lines up now.
|
/// Lines up now.
|
||||||
@@ -195,6 +218,17 @@ impl LineMap {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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) {
|
fn close_all(&self) {
|
||||||
for s in &self.shards {
|
for s in &self.shards {
|
||||||
for h in Self::lock(s).values() {
|
for h in Self::lock(s).values() {
|
||||||
@@ -204,44 +238,6 @@ impl LineMap {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Per-address claim limit: a fixed table of (window start, count).
|
|
||||||
struct ClaimIps {
|
|
||||||
slots: Mutex<Vec<(Instant, u32)>>,
|
|
||||||
mask: usize,
|
|
||||||
state: RandomState,
|
|
||||||
limit: u32,
|
|
||||||
window: Duration,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ClaimIps {
|
|
||||||
fn new(slots: usize, limit: u32, window: Duration) -> Self {
|
|
||||||
let n = slots.max(2).next_power_of_two();
|
|
||||||
ClaimIps {
|
|
||||||
slots: Mutex::new(vec![(Instant::now(), 0); n]),
|
|
||||||
mask: n - 1,
|
|
||||||
state: RandomState::new(),
|
|
||||||
limit,
|
|
||||||
window,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn allow(&self, ip: std::net::IpAddr, now: Instant) -> bool {
|
|
||||||
// Truncating the hash to a slot index is the point.
|
|
||||||
let slot = (self.state.hash_one(ip) as usize) & self.mask;
|
|
||||||
let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
|
|
||||||
let (start, count) = &mut slots[slot];
|
|
||||||
if now.saturating_duration_since(*start) >= self.window {
|
|
||||||
*start = now;
|
|
||||||
*count = 0;
|
|
||||||
}
|
|
||||||
if *count >= self.limit {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
*count += 1;
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Everything the tasks share.
|
/// Everything the tasks share.
|
||||||
pub struct Shared {
|
pub struct Shared {
|
||||||
/// The configuration.
|
/// The configuration.
|
||||||
@@ -260,10 +256,53 @@ pub struct Shared {
|
|||||||
pub metrics: Metrics,
|
pub metrics: Metrics,
|
||||||
conn_permits: Arc<Semaphore>,
|
conn_permits: Arc<Semaphore>,
|
||||||
hello_permits: Arc<Semaphore>,
|
hello_permits: Arc<Semaphore>,
|
||||||
|
hello_reserve: Arc<Semaphore>,
|
||||||
handshake_permits: Arc<Semaphore>,
|
handshake_permits: Arc<Semaphore>,
|
||||||
conn_gate: Arc<IpGate>,
|
conn_gate: Arc<IpGate>,
|
||||||
pending_gate: Arc<IpGate>,
|
pending_gate: Arc<IpGate>,
|
||||||
claim_ips: ClaimIps,
|
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.
|
/// A TLS fatal alert, `unrecognized_name`: the same for every refusal.
|
||||||
@@ -300,19 +339,18 @@ async fn read_hello(tcp: &mut TcpStream) -> Result<(Vec<u8>, String), HelloError
|
|||||||
Ok((rec, host))
|
Ok((rec, host))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle(
|
async fn handle(ctx: Arc<Shared>, mut tcp: TcpStream, peer: SocketAddr, admission: Admission) {
|
||||||
ctx: Arc<Shared>,
|
let Admission {
|
||||||
mut tcp: TcpStream,
|
conn,
|
||||||
peer: SocketAddr,
|
conn_ip,
|
||||||
conn: OwnedSemaphorePermit,
|
pending_ip,
|
||||||
conn_ip: crate::gate::IpPermit,
|
pending_net,
|
||||||
pending_ip: crate::gate::IpPermit,
|
hello,
|
||||||
hello_permit: OwnedSemaphorePermit,
|
} = admission;
|
||||||
) {
|
|
||||||
let _held = (conn, conn_ip);
|
let _held = (conn, conn_ip);
|
||||||
let _ = tcp.set_nodelay(true);
|
let _ = tcp.set_nodelay(true);
|
||||||
let first = timeout(ctx.cfg.limits.hello_timeout(), read_hello(&mut tcp)).await;
|
let first = timeout(ctx.cfg.limits.hello_timeout(), read_hello(&mut tcp)).await;
|
||||||
drop((pending_ip, hello_permit));
|
drop((pending_ip, pending_net, hello));
|
||||||
let (record, host) = match first {
|
let (record, host) = match first {
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
Metrics::bump(&ctx.metrics.hello_timeouts);
|
Metrics::bump(&ctx.metrics.hello_timeouts);
|
||||||
@@ -384,6 +422,7 @@ async fn route(
|
|||||||
buffer: l.copy_buffer,
|
buffer: l.copy_buffer,
|
||||||
idle: l.stream_idle(),
|
idle: l.stream_idle(),
|
||||||
stall: l.write_stall(),
|
stall: l.write_stall(),
|
||||||
|
min_rate: l.min_stream_bytes_per_sec,
|
||||||
max_age: l.stream_max_age(),
|
max_age: l.stream_max_age(),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -394,29 +433,44 @@ type LineTls = tokio_rustls::server::TlsStream<Front<TcpStream>>;
|
|||||||
|
|
||||||
async fn serve_line(ctx: Arc<Shared>, tcp: TcpStream, record: Vec<u8>, peer: SocketAddr) {
|
async fn serve_line(ctx: Arc<Shared>, tcp: TcpStream, record: Vec<u8>, peer: SocketAddr) {
|
||||||
let l = &ctx.cfg.limits;
|
let l = &ctx.cfg.limits;
|
||||||
let Ok(handshake_permit) = Arc::clone(&ctx.handshake_permits).try_acquire_owned() else {
|
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);
|
Metrics::bump(&ctx.metrics.shed);
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
let handshaking = (pool, per_ip, per_net);
|
||||||
Metrics::bump(&ctx.metrics.line_attempts);
|
Metrics::bump(&ctx.metrics.line_attempts);
|
||||||
let activity = Activity::new();
|
let activity = Activity::new();
|
||||||
let front = Front::new(record, tcp, Some(Arc::clone(&activity)));
|
let front = Front::new(record, tcp, Some(Arc::clone(&activity)));
|
||||||
let up = timeout(l.handshake_timeout(), handshake(&ctx, front, peer)).await;
|
let up = timeout(l.handshake_timeout(), handshake(&ctx, front, ip)).await;
|
||||||
drop(handshake_permit);
|
drop(handshaking);
|
||||||
let Ok(Ok((tls, name))) = up else { return };
|
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 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 control = Arc::new(Semaphore::new(l.control_streams_per_app as usize));
|
||||||
let limits = MuxLimits {
|
let limits = MuxLimits {
|
||||||
// The permits, and sixteen over: a stream the app has closed may
|
// 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
|
// 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
|
// back, and yamux ends a line that is asked for a stream over its
|
||||||
// count.
|
// count. Every stream may hold a 256 KiB receive window, so the
|
||||||
max_streams: (l.streams_per_app + l.control_streams_per_app + 16) as usize,
|
// few are few.
|
||||||
|
max_streams: (l.streams_per_app + l.control_streams_per_app + STREAM_SLACK) as usize,
|
||||||
idle: l.line_idle(),
|
idle: l.line_idle(),
|
||||||
};
|
};
|
||||||
let ctx2 = Arc::clone(&ctx);
|
let ctx2 = Arc::clone(&ctx);
|
||||||
let (mux, task) = mux::spawn(
|
let kick2 = kick.clone();
|
||||||
|
let (mux, mut task) = mux::spawn(
|
||||||
tls.compat(),
|
tls.compat(),
|
||||||
yamux::Mode::Server,
|
yamux::Mode::Server,
|
||||||
limits,
|
limits,
|
||||||
@@ -424,8 +478,9 @@ async fn serve_line(ctx: Arc<Shared>, tcp: TcpStream, record: Vec<u8>, peer: Soc
|
|||||||
move |stream| {
|
move |stream| {
|
||||||
if let Ok(permit) = Arc::clone(&control).try_acquire_owned() {
|
if let Ok(permit) = Arc::clone(&control).try_acquire_owned() {
|
||||||
let ctx = Arc::clone(&ctx2);
|
let ctx = Arc::clone(&ctx2);
|
||||||
|
let kick = kick2.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
serve_control(ctx, name, stream).await;
|
serve_control(ctx, name, ip, kick, stream).await;
|
||||||
drop(permit);
|
drop(permit);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -443,16 +498,26 @@ async fn serve_line(ctx: Arc<Shared>, tcp: TcpStream, record: Vec<u8>, peer: Soc
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ctx.metrics.lines_up.fetch_add(1, Ordering::Relaxed);
|
ctx.metrics.lines_up.fetch_add(1, Ordering::Relaxed);
|
||||||
let _ = task.await;
|
tokio::select! {
|
||||||
|
_ = &mut task => {}
|
||||||
|
() = kick.cancelled() => {
|
||||||
|
mux.close();
|
||||||
|
let _ = task.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
ctx.lines.remove_if(&name, id);
|
ctx.lines.remove_if(&name, id);
|
||||||
ctx.metrics.lines_up.fetch_sub(1, Ordering::Relaxed);
|
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.
|
/// TLS, the challenge, the proof, the verdict.
|
||||||
async fn handshake(
|
async fn handshake(
|
||||||
ctx: &Arc<Shared>,
|
ctx: &Arc<Shared>,
|
||||||
front: Front<TcpStream>,
|
front: Front<TcpStream>,
|
||||||
peer: SocketAddr,
|
ip: std::net::IpAddr,
|
||||||
) -> Result<(LineTls, Name), ()> {
|
) -> Result<(LineTls, Name), ()> {
|
||||||
let mut tls = ctx.acceptor.accept(front).await.map_err(|_| ())?;
|
let mut tls = ctx.acceptor.accept(front).await.map_err(|_| ())?;
|
||||||
let mut exporter = [0u8; 32];
|
let mut exporter = [0u8; 32];
|
||||||
@@ -471,7 +536,7 @@ async fn handshake(
|
|||||||
.await
|
.await
|
||||||
.map_err(|_| ())?;
|
.map_err(|_| ())?;
|
||||||
let hello: Hello = read_frame(&mut tls).await.map_err(|_| ())?;
|
let hello: Hello = read_frame(&mut tls).await.map_err(|_| ())?;
|
||||||
let (verdict, name) = decide(ctx, &hello, &exporter, &nonce, peer.ip()).await;
|
let (verdict, name) = decide(ctx, &hello, &exporter, &nonce, ip).await;
|
||||||
write_frame(&mut tls, &verdict).await.map_err(|_| ())?;
|
write_frame(&mut tls, &verdict).await.map_err(|_| ())?;
|
||||||
match name {
|
match name {
|
||||||
Some(n) if verdict.ok => Ok((tls, n)),
|
Some(n) if verdict.ok => Ok((tls, n)),
|
||||||
@@ -529,10 +594,9 @@ async fn decide(
|
|||||||
return refused(Refusal::Busy);
|
return refused(Refusal::Busy);
|
||||||
}
|
}
|
||||||
Ok(Some(e)) => {
|
Ok(Some(e)) => {
|
||||||
if e.blocked {
|
// The key first: only the holder of the name's key is told it
|
||||||
Metrics::bump(&ctx.metrics.refused_other);
|
// is blocked. Anyone else gets what a wrong key gets, whether
|
||||||
return refused(Refusal::Blocked);
|
// the name is blocked or not.
|
||||||
}
|
|
||||||
if e.public_key != key {
|
if e.public_key != key {
|
||||||
Metrics::bump(&ctx.metrics.refused_proof);
|
Metrics::bump(&ctx.metrics.refused_proof);
|
||||||
return refused(if hello.claim {
|
return refused(if hello.claim {
|
||||||
@@ -541,11 +605,17 @@ async fn decide(
|
|||||||
Refusal::BadProof
|
Refusal::BadProof
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if e.blocked {
|
||||||
|
Metrics::bump(&ctx.metrics.refused_other);
|
||||||
|
return refused(Refusal::Blocked);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
if !hello.claim {
|
if !hello.claim {
|
||||||
Metrics::bump(&ctx.metrics.refused_other);
|
// The same answer as a wrong key: a caller with a key of
|
||||||
return refused(Refusal::UnknownName);
|
// 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()) {
|
if !ctx.claim_ips.allow(ip, Instant::now()) {
|
||||||
Metrics::bump(&ctx.metrics.refused_other);
|
Metrics::bump(&ctx.metrics.refused_other);
|
||||||
@@ -592,7 +662,13 @@ async fn decide(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// One request from an app on its own line. The name is the line's.
|
/// One request from an app on its own line. The name is the line's.
|
||||||
async fn serve_control(ctx: Arc<Shared>, name: Name, mut stream: mux::Stream) {
|
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 _ = timeout(ctx.cfg.limits.control_timeout(), async {
|
||||||
let request: Request = read_frame(&mut stream).await.ok()?;
|
let request: Request = read_frame(&mut stream).await.ok()?;
|
||||||
Metrics::bump(&ctx.metrics.control);
|
Metrics::bump(&ctx.metrics.control);
|
||||||
@@ -601,22 +677,7 @@ async fn serve_control(ctx: Arc<Shared>, name: Name, mut stream: mux::Stream) {
|
|||||||
ok: true,
|
ok: true,
|
||||||
..Response::default()
|
..Response::default()
|
||||||
},
|
},
|
||||||
Request::PublishTxt { value } => match ctx.txt.publish(name, &value, Instant::now()) {
|
Request::PublishTxt { value } => publish(&ctx, name, ip, &kick, &value).await,
|
||||||
Ok(()) => Response {
|
|
||||||
ok: true,
|
|
||||||
..Response::default()
|
|
||||||
},
|
|
||||||
Err(PublishError::BadValue) => Response {
|
|
||||||
ok: false,
|
|
||||||
error: Some("bad_value".into()),
|
|
||||||
..Response::default()
|
|
||||||
},
|
|
||||||
Err(PublishError::Limit) => Response {
|
|
||||||
ok: false,
|
|
||||||
error: Some("limit".into()),
|
|
||||||
..Response::default()
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Request::ClearTxt => {
|
Request::ClearTxt => {
|
||||||
ctx.txt.clear(&name);
|
ctx.txt.clear(&name);
|
||||||
Response {
|
Response {
|
||||||
@@ -637,6 +698,67 @@ async fn serve_control(ctx: Arc<Shared>, name: Name, mut stream: mux::Stream) {
|
|||||||
.await;
|
.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) {
|
async fn accept_loop(ctx: Arc<Shared>, listener: TcpListener, cancel: CancellationToken) {
|
||||||
loop {
|
loop {
|
||||||
let (tcp, peer) = tokio::select! {
|
let (tcp, peer) = tokio::select! {
|
||||||
@@ -650,26 +772,15 @@ async fn accept_loop(ctx: Arc<Shared>, listener: TcpListener, cancel: Cancellati
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let ip = peer.ip();
|
// An IPv4 caller on a dual-stack listener is `::ffff:a.b.c.d`:
|
||||||
let (Ok(conn), Some(conn_ip), Some(pending_ip), Ok(hello)) = (
|
// made canonical, it is its IPv4 address in every table.
|
||||||
Arc::clone(&ctx.conn_permits).try_acquire_owned(),
|
let ip = peer.ip().to_canonical();
|
||||||
ctx.conn_gate.acquire(ip),
|
let Some(admission) = ctx.admit(ip) else {
|
||||||
ctx.pending_gate.acquire(ip),
|
|
||||||
Arc::clone(&ctx.hello_permits).try_acquire_owned(),
|
|
||||||
) else {
|
|
||||||
Metrics::bump(&ctx.metrics.shed);
|
Metrics::bump(&ctx.metrics.shed);
|
||||||
continue; // closed by drop, before any work
|
continue; // closed by drop, before any work
|
||||||
};
|
};
|
||||||
Metrics::bump(&ctx.metrics.accepted);
|
Metrics::bump(&ctx.metrics.accepted);
|
||||||
tokio::spawn(handle(
|
tokio::spawn(handle(Arc::clone(&ctx), tcp, peer, admission));
|
||||||
Arc::clone(&ctx),
|
|
||||||
tcp,
|
|
||||||
peer,
|
|
||||||
conn,
|
|
||||||
conn_ip,
|
|
||||||
pending_ip,
|
|
||||||
hello,
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -700,32 +811,68 @@ impl Relay {
|
|||||||
l.txt_per_name,
|
l.txt_per_name,
|
||||||
l.txt_publishes_per_hour,
|
l.txt_publishes_per_hour,
|
||||||
));
|
));
|
||||||
|
let authorities = Arc::new(authorities);
|
||||||
let dns = Arc::new(
|
let dns = Arc::new(
|
||||||
DnsService::new(zone.clone(), &cfg, Arc::clone(&txt)).map_err(io::Error::other)?,
|
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_listener = TcpListener::bind(cfg.router_addr).await?;
|
||||||
let router = router_listener.local_addr()?;
|
let router = router_listener.local_addr()?;
|
||||||
let udp = UdpSocket::bind(cfg.dns_addr).await?;
|
// TCP DNS on the same port number when it was asked for 0: a UDP
|
||||||
let dns_udp = udp.local_addr()?;
|
// port that is free is not always free for TCP, so ask again.
|
||||||
// TCP DNS on the same port number when it was asked for 0.
|
let mut attempt = 0;
|
||||||
let tcp_addr = SocketAddr::new(cfg.dns_addr.ip(), dns_udp.port());
|
let (udp, dns_udp, dns_tcp_listener, dns_tcp) = loop {
|
||||||
let dns_tcp_listener = TcpListener::bind(tcp_addr).await?;
|
attempt += 1;
|
||||||
let dns_tcp = dns_tcp_listener.local_addr()?;
|
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 {
|
let shared = Arc::new(Shared {
|
||||||
zone,
|
zone,
|
||||||
lines: LineMap::new(l.max_lines),
|
lines: LineMap::new(l.max_lines),
|
||||||
registry,
|
registry,
|
||||||
txt: Arc::clone(&txt),
|
txt: Arc::clone(&txt),
|
||||||
authorities: Arc::new(authorities),
|
authorities,
|
||||||
acceptor: TlsAcceptor::from(tls),
|
acceptor: TlsAcceptor::from(tls),
|
||||||
metrics: Metrics::default(),
|
metrics: Metrics::default(),
|
||||||
conn_permits: Arc::new(Semaphore::new(l.max_connections)),
|
conn_permits: Arc::new(Semaphore::new(l.max_connections)),
|
||||||
hello_permits: Arc::new(Semaphore::new(l.max_pending_hellos)),
|
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)),
|
handshake_permits: Arc::new(Semaphore::new(l.max_handshakes)),
|
||||||
conn_gate: IpGate::new(l.ip_slots, l.max_connections_per_ip),
|
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_gate: IpGate::new(l.ip_slots, l.max_pending_per_ip),
|
||||||
claim_ips: ClaimIps::new(4096, l.claims_per_ip, l.claim_ip_window()),
|
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,
|
cfg,
|
||||||
});
|
});
|
||||||
let cancel = CancellationToken::new();
|
let cancel = CancellationToken::new();
|
||||||
@@ -739,6 +886,7 @@ impl Relay {
|
|||||||
Arc::new(udp),
|
Arc::new(udp),
|
||||||
Arc::clone(&dns),
|
Arc::clone(&dns),
|
||||||
l.dns_qps_per_ip,
|
l.dns_qps_per_ip,
|
||||||
|
l.dns_qps_global,
|
||||||
l.ip_slots,
|
l.ip_slots,
|
||||||
cancel.clone(),
|
cancel.clone(),
|
||||||
)),
|
)),
|
||||||
@@ -769,6 +917,27 @@ impl Relay {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
// 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 {
|
Ok(Relay {
|
||||||
shared,
|
shared,
|
||||||
router,
|
router,
|
||||||
|
|||||||
@@ -14,8 +14,11 @@
|
|||||||
//! SOURCE: WB-relay-1 (the router and its splice), WB-relay-7 (bounds).
|
//! SOURCE: WB-relay-1 (the router and its splice), WB-relay-7 (bounds).
|
||||||
//! INVARIANTS:
|
//! INVARIANTS:
|
||||||
//! 1. At most `buffer` bytes are held per direction.
|
//! 1. At most `buffer` bytes are held per direction.
|
||||||
//! 2. A write that makes no progress for `stall` ends the connection:
|
//! 2. A write of `n` bytes that is not finished within `stall` plus `n`
|
||||||
//! a slow reader is closed, never buffered for.
|
//! 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
|
//! 3. A connection with no byte either way for `idle`, or alive for
|
||||||
//! `max_age`, is closed.
|
//! `max_age`, is closed.
|
||||||
//! 4. A close in one direction (EOF) is passed on as a close of the
|
//! 4. A close in one direction (EOF) is passed on as a close of the
|
||||||
@@ -24,7 +27,9 @@
|
|||||||
//! SCENARIOS:
|
//! SCENARIOS:
|
||||||
//! 1. Bytes written at either end arrive at the other, in order, and a
|
//! 1. Bytes written at either end arrive at the other, in order, and a
|
||||||
//! close at one end reaches the other.
|
//! close at one end reaches the other.
|
||||||
//! 2. A peer that never reads: the splice ends after `stall`.
|
//! 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`.
|
//! 3. A peer that says nothing: the splice ends after `idle`.
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
@@ -42,8 +47,11 @@ pub struct SpliceLimits {
|
|||||||
pub buffer: usize,
|
pub buffer: usize,
|
||||||
/// No byte either way for this long ends it.
|
/// No byte either way for this long ends it.
|
||||||
pub idle: Duration,
|
pub idle: Duration,
|
||||||
/// A write stuck this long ends it.
|
/// The grace on every write: a write has at least this long.
|
||||||
pub stall: Duration,
|
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.
|
/// Its longest life.
|
||||||
pub max_age: Duration,
|
pub max_age: Duration,
|
||||||
}
|
}
|
||||||
@@ -86,11 +94,18 @@ impl Stamp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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>(
|
async fn pump<R, W>(
|
||||||
from: &mut R,
|
from: &mut R,
|
||||||
to: &mut W,
|
to: &mut W,
|
||||||
buffer: usize,
|
buffer: usize,
|
||||||
stall: Duration,
|
stall: Duration,
|
||||||
|
min_rate: u32,
|
||||||
last: &Stamp,
|
last: &Stamp,
|
||||||
) -> Result<(), End>
|
) -> Result<(), End>
|
||||||
where
|
where
|
||||||
@@ -110,7 +125,7 @@ where
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
last.touch();
|
last.touch();
|
||||||
match timeout(stall, async {
|
match timeout(write_deadline(stall, min_rate, n), async {
|
||||||
to.write_all(&buf[..n]).await?;
|
to.write_all(&buf[..n]).await?;
|
||||||
to.flush().await
|
to.flush().await
|
||||||
})
|
})
|
||||||
@@ -136,8 +151,22 @@ where
|
|||||||
// The first failure ends both; a clean close in one direction
|
// The first failure ends both; a clean close in one direction
|
||||||
// lets the other carry on.
|
// lets the other carry on.
|
||||||
match tokio::try_join!(
|
match tokio::try_join!(
|
||||||
pump(&mut ar, &mut bw, limits.buffer, limits.stall, &last),
|
pump(
|
||||||
pump(&mut br, &mut aw, limits.buffer, limits.stall, &last),
|
&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,
|
Ok(((), ())) => End::Done,
|
||||||
Err(e) => e,
|
Err(e) => e,
|
||||||
@@ -168,6 +197,7 @@ mod tests {
|
|||||||
buffer: 1024,
|
buffer: 1024,
|
||||||
idle: Duration::from_secs(30),
|
idle: Duration::from_secs(30),
|
||||||
stall: Duration::from_secs(30),
|
stall: Duration::from_secs(30),
|
||||||
|
min_rate: 1024,
|
||||||
max_age: Duration::from_secs(60),
|
max_age: Duration::from_secs(60),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -264,4 +294,55 @@ mod tests {
|
|||||||
}
|
}
|
||||||
assert_eq!(task.await.unwrap(), End::MaxAge);
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -76,9 +76,18 @@ pub struct Env {
|
|||||||
|
|
||||||
pub fn quick_limits() -> Limits {
|
pub fn quick_limits() -> Limits {
|
||||||
Limits {
|
Limits {
|
||||||
// The tests claim many names from one address.
|
// 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_window: 10_000,
|
||||||
claims_per_ip: 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()
|
..Limits::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
//! ```text
|
//! ```text
|
||||||
//! ulimit -n 65536
|
//! ulimit -n 65536
|
||||||
//! TMPDIR=/dev/shm RELAY_IDLE_LINES=20000 cargo test --release \
|
//! TMPDIR=/dev/shm RELAY_IDLE_LINES=20000 cargo test --release \
|
||||||
//! -p wanderbooks-relay --test memory idle_line_memory -- --ignored --nocapture
|
//! -p relay --test memory idle_line_memory -- --ignored --nocapture
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! `TMPDIR=/dev/shm` keeps the registry off the disk: every claim of a
|
//! `TMPDIR=/dev/shm` keeps the registry off the disk: every claim of a
|
||||||
@@ -21,6 +21,10 @@
|
|||||||
//! them take minutes on a disk. Measured 2026-11-21 on this machine,
|
//! 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
|
//! 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).
|
//! 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).
|
//! Linux only (it reads /proc).
|
||||||
#![allow(missing_docs)]
|
#![allow(missing_docs)]
|
||||||
@@ -130,11 +134,15 @@ async fn idle_line_memory() {
|
|||||||
max_connections_per_ip: 1_000_000,
|
max_connections_per_ip: 1_000_000,
|
||||||
max_pending_per_ip: 10_000,
|
max_pending_per_ip: 10_000,
|
||||||
max_pending_hellos: 10_000,
|
max_pending_hellos: 10_000,
|
||||||
|
max_pending_per_net: 10_000,
|
||||||
max_handshakes: 1024,
|
max_handshakes: 1024,
|
||||||
|
max_handshakes_per_ip: 1024,
|
||||||
|
max_handshakes_per_net: 1024,
|
||||||
max_lines: n + 10,
|
max_lines: n + 10,
|
||||||
line_idle_ms: 3_600_000,
|
line_idle_ms: 3_600_000,
|
||||||
claims_per_window: u32::try_from(n + 10).unwrap(),
|
claims_per_window: u32::try_from(n + 10).unwrap(),
|
||||||
claims_per_ip: 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()
|
..quick_limits()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
|||||||
+443
-30
@@ -194,9 +194,10 @@ async fn a_name_cannot_be_claimed_twice_and_a_wrong_key_is_refused() {
|
|||||||
refusal(env.connect(n(NAME), &b, false).await),
|
refusal(env.connect(n(NAME), &b, false).await),
|
||||||
Refusal::BadProof
|
Refusal::BadProof
|
||||||
);
|
);
|
||||||
|
// A name nobody has claimed is refused as a wrong key is.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
refusal(env.connect(n(OTHER), &a, false).await),
|
refusal(env.connect(n(OTHER), &a, false).await),
|
||||||
Refusal::UnknownName
|
Refusal::BadProof
|
||||||
);
|
);
|
||||||
// The owner still gets back in, without claiming again.
|
// The owner still gets back in, without claiming again.
|
||||||
let again = env.connect(n(NAME), &a, false).await.unwrap();
|
let again = env.connect(n(NAME), &a, false).await.unwrap();
|
||||||
@@ -314,7 +315,8 @@ async fn blocked_names_and_the_limit_on_new_names() {
|
|||||||
let limits = Limits {
|
let limits = Limits {
|
||||||
claims_per_window: 2,
|
claims_per_window: 2,
|
||||||
claims_per_ip: 100,
|
claims_per_ip: 100,
|
||||||
..Limits::default()
|
claims_per_net: 100,
|
||||||
|
..quick_limits()
|
||||||
};
|
};
|
||||||
let env = start(limits).await;
|
let env = start(limits).await;
|
||||||
let (k1, _) = AppKey::generate();
|
let (k1, _) = AppKey::generate();
|
||||||
@@ -350,7 +352,7 @@ async fn one_address_cannot_claim_many_names() {
|
|||||||
let limits = Limits {
|
let limits = Limits {
|
||||||
claims_per_window: 1000,
|
claims_per_window: 1000,
|
||||||
claims_per_ip: 2,
|
claims_per_ip: 2,
|
||||||
..Limits::default()
|
..quick_limits()
|
||||||
};
|
};
|
||||||
let env = start(limits).await;
|
let env = start(limits).await;
|
||||||
let mut outcomes = Vec::new();
|
let mut outcomes = Vec::new();
|
||||||
@@ -497,7 +499,7 @@ async fn publishing_needs_a_proven_line() {
|
|||||||
drop(s);
|
drop(s);
|
||||||
// And a refused hello gives no line to publish on.
|
// And a refused hello gives no line to publish on.
|
||||||
let r = env.connect(n(NAME), &key, false).await;
|
let r = env.connect(n(NAME), &key, false).await;
|
||||||
assert!(matches!(r, Err(ClientError::Refused(Refusal::UnknownName))));
|
assert!(matches!(r, Err(ClientError::Refused(Refusal::BadProof))));
|
||||||
let dns_addr = env.relay.dns_udp_addr();
|
let dns_addr = env.relay.dns_udp_addr();
|
||||||
let q = format!("_acme-challenge.{NAME}.{DOMAIN}.");
|
let q = format!("_acme-challenge.{NAME}.{DOMAIN}.");
|
||||||
assert!(txt_values(&dns(dns_addr, &q, RecordType::TXT).await).is_empty());
|
assert!(txt_values(&dns(dns_addr, &q, RecordType::TXT).await).is_empty());
|
||||||
@@ -510,24 +512,39 @@ const LIST: &str = r#"
|
|||||||
[[authority]]
|
[[authority]]
|
||||||
id = "letsencrypt"
|
id = "letsencrypt"
|
||||||
directory = "http://127.0.0.1:14000/dir"
|
directory = "http://127.0.0.1:14000/dir"
|
||||||
|
caa_domain = "letsencrypt.org"
|
||||||
|
|
||||||
[[authority]]
|
[[authority]]
|
||||||
id = "zerossl"
|
id = "zerossl"
|
||||||
directory = "http://127.0.0.1:14001/dir"
|
directory = "http://127.0.0.1:14001/dir"
|
||||||
|
caa_domain = "sectigo.com"
|
||||||
needs_binding = true
|
needs_binding = true
|
||||||
binding_kid = "kid-1"
|
|
||||||
binding_hmac_key = "a2V5"
|
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
/// WB-relay-5 scenario: the list is served in its order, with bindings,
|
/// A per-app binding source, standing in for an authority's own API.
|
||||||
/// and an edit to the file changes what the next request gets, with no
|
struct PerApp(&'static str);
|
||||||
/// change to the app.
|
|
||||||
|
impl relay::authorities::BindingSource for PerApp {
|
||||||
|
fn binding_for(&self, id: &str, name: &relay::names::Name) -> Option<proto::Binding> {
|
||||||
|
Some(proto::Binding {
|
||||||
|
kid: format!("{}-{id}-{name}", self.0),
|
||||||
|
hmac_key: "a2V5".into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-5 scenario: the list is served in its order, a binding comes
|
||||||
|
/// only from a per-app source (never from the file), the zone's CAA record
|
||||||
|
/// follows the list, and an edit to the file changes what the next request
|
||||||
|
/// gets, with no change to the app.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn the_authority_list_is_served_and_follows_the_file() {
|
async fn the_authority_list_is_served_and_follows_the_file() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let path = dir.path().join("authorities.toml");
|
let path = dir.path().join("authorities.toml");
|
||||||
std::fs::write(&path, LIST).unwrap();
|
std::fs::write(&path, LIST).unwrap();
|
||||||
let list = relay::authorities::AuthorityList::from_file(path.clone()).unwrap();
|
let list = relay::authorities::AuthorityList::from_file(path.clone())
|
||||||
|
.unwrap()
|
||||||
|
.with_binding_source(std::sync::Arc::new(PerApp("one")));
|
||||||
let env = start_with(quick_limits(), list).await;
|
let env = start_with(quick_limits(), list).await;
|
||||||
let (key, _) = AppKey::generate();
|
let (key, _) = AppKey::generate();
|
||||||
let line = env.connect(n(NAME), &key, true).await.unwrap();
|
let line = env.connect(n(NAME), &key, true).await.unwrap();
|
||||||
@@ -535,30 +552,43 @@ async fn the_authority_list_is_served_and_follows_the_file() {
|
|||||||
let got = line.authorities().await.unwrap();
|
let got = line.authorities().await.unwrap();
|
||||||
let ids: Vec<_> = got.iter().map(|a| a.id.as_str()).collect();
|
let ids: Vec<_> = got.iter().map(|a| a.id.as_str()).collect();
|
||||||
assert_eq!(ids, ["letsencrypt", "zerossl"]);
|
assert_eq!(ids, ["letsencrypt", "zerossl"]);
|
||||||
assert!(!got[0].needs_binding && got[0].binding.is_none());
|
assert!(!got[0].needs_binding && got[0].binding.is_none() && got[0].usable);
|
||||||
assert!(got[1].needs_binding);
|
assert!(got[1].needs_binding && got[1].usable);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
got[1].binding.as_ref().map(|b| b.kid.as_str()),
|
got[1].binding.as_ref().map(|b| b.kid.as_str()),
|
||||||
Some("kid-1")
|
Some(format!("one-zerossl-{NAME}").as_str())
|
||||||
);
|
);
|
||||||
assert_eq!(got[0].directory, "http://127.0.0.1:14000/dir");
|
assert_eq!(got[0].directory, "http://127.0.0.1:14000/dir");
|
||||||
|
|
||||||
|
// The zone's CAA record is made from the same list.
|
||||||
|
let caa =
|
||||||
|
|m: &Message| -> Vec<String> { m.answers.iter().map(|r| r.data.to_string()).collect() };
|
||||||
|
let apex = format!("{DOMAIN}.");
|
||||||
|
assert_eq!(
|
||||||
|
caa(&dns(env.relay.dns_udp_addr(), &apex, RecordType::CAA).await),
|
||||||
|
[
|
||||||
|
r#"0 issue "letsencrypt.org; validationmethods=dns-01""#,
|
||||||
|
r#"0 issue "sectigo.com; validationmethods=dns-01""#
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
// Swap the authorities: ZeroSSL first, a third added.
|
// Swap the authorities: ZeroSSL first, a third added.
|
||||||
let swapped = r#"
|
let swapped = r#"
|
||||||
[[authority]]
|
[[authority]]
|
||||||
id = "zerossl"
|
id = "zerossl"
|
||||||
directory = "http://127.0.0.1:14001/dir"
|
directory = "http://127.0.0.1:14001/dir"
|
||||||
|
caa_domain = "sectigo.com"
|
||||||
needs_binding = true
|
needs_binding = true
|
||||||
binding_kid = "kid-2"
|
|
||||||
binding_hmac_key = "a2V5"
|
|
||||||
|
|
||||||
[[authority]]
|
[[authority]]
|
||||||
id = "gts"
|
id = "gts"
|
||||||
directory = "http://127.0.0.1:14002/dir"
|
directory = "http://127.0.0.1:14002/dir"
|
||||||
|
caa_domain = "pki.goog"
|
||||||
|
|
||||||
[[authority]]
|
[[authority]]
|
||||||
id = "letsencrypt"
|
id = "letsencrypt"
|
||||||
directory = "http://127.0.0.1:14000/dir"
|
directory = "http://127.0.0.1:14000/dir"
|
||||||
|
caa_domain = "letsencrypt.org"
|
||||||
"#;
|
"#;
|
||||||
std::fs::write(&path, swapped).unwrap();
|
std::fs::write(&path, swapped).unwrap();
|
||||||
// The relay rereads on its half-minute tick; here, call it.
|
// The relay rereads on its half-minute tick; here, call it.
|
||||||
@@ -567,12 +597,34 @@ directory = "http://127.0.0.1:14000/dir"
|
|||||||
let ids: Vec<_> = got.iter().map(|a| a.id.as_str()).collect();
|
let ids: Vec<_> = got.iter().map(|a| a.id.as_str()).collect();
|
||||||
assert_eq!(ids, ["zerossl", "gts", "letsencrypt"]);
|
assert_eq!(ids, ["zerossl", "gts", "letsencrypt"]);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
got[0].binding.as_ref().map(|b| b.kid.as_str()),
|
caa(&dns(env.relay.dns_udp_addr(), &apex, RecordType::CAA).await).len(),
|
||||||
Some("kid-2")
|
3
|
||||||
);
|
);
|
||||||
env.relay.shutdown().await;
|
env.relay.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// WB-relay-5: with no per-app binding source an authority that needs a
|
||||||
|
/// binding is listed, served without one, and marked not usable; and a
|
||||||
|
/// list file that carries a binding secret is not loaded at all.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn no_shared_binding_secret_is_ever_served() {
|
||||||
|
let list = relay::authorities::AuthorityList::from_toml(LIST).unwrap();
|
||||||
|
let env = start_with(quick_limits(), list).await;
|
||||||
|
let (key, _) = AppKey::generate();
|
||||||
|
let line = env.connect(n(NAME), &key, true).await.unwrap();
|
||||||
|
let got = line.authorities().await.unwrap();
|
||||||
|
assert_eq!(got.len(), 2);
|
||||||
|
assert!(got[1].needs_binding && got[1].binding.is_none() && !got[1].usable);
|
||||||
|
assert!(got[0].usable);
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
|
||||||
|
let with_secret = format!("{LIST}binding_kid = 'kid'\nbinding_hmac_key = 'a2V5'\n");
|
||||||
|
let err = relay::authorities::AuthorityList::from_toml(&with_secret)
|
||||||
|
.err()
|
||||||
|
.expect("refused at load");
|
||||||
|
assert!(err.to_string().contains("binding secret"), "{err}");
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ bounds
|
// ------------------------------------------------------------------ bounds
|
||||||
|
|
||||||
/// WB-relay-7: a half-open ClientHello, a silent peer and a slow drip all
|
/// WB-relay-7: a half-open ClientHello, a silent peer and a slow drip all
|
||||||
@@ -822,15 +874,8 @@ async fn a_slow_reader_back_pressures_and_is_cut_off_at_the_stall_limit() {
|
|||||||
env.relay.shutdown().await;
|
env.relay.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// WB-relay-7: DNS over UDP is rate limited per address from a fixed table.
|
/// Send `count` identical queries and collect every reply.
|
||||||
#[tokio::test]
|
async fn dns_flood(addr: std::net::SocketAddr, count: usize) -> Vec<Message> {
|
||||||
async fn dns_over_udp_is_rate_limited_per_address() {
|
|
||||||
let env = start(Limits {
|
|
||||||
dns_qps_per_ip: 5,
|
|
||||||
..quick_limits()
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
let addr = env.relay.dns_udp_addr();
|
|
||||||
let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||||
let mut q = Message::query();
|
let mut q = Message::query();
|
||||||
q.queries.push(Query::query(
|
q.queries.push(Query::query(
|
||||||
@@ -838,18 +883,66 @@ async fn dns_over_udp_is_rate_limited_per_address() {
|
|||||||
RecordType::A,
|
RecordType::A,
|
||||||
));
|
));
|
||||||
let wire = q.to_vec().unwrap();
|
let wire = q.to_vec().unwrap();
|
||||||
for _ in 0..200 {
|
for _ in 0..count {
|
||||||
sock.send_to(&wire, addr).await.unwrap();
|
sock.send_to(&wire, addr).await.unwrap();
|
||||||
}
|
}
|
||||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||||
let mut answered = 0;
|
let mut replies = Vec::new();
|
||||||
let mut buf = [0u8; 2048];
|
let mut buf = [0u8; 2048];
|
||||||
while let Ok(Ok(_)) =
|
while let Ok(Ok((n, _))) =
|
||||||
tokio::time::timeout(Duration::from_millis(100), sock.recv_from(&mut buf)).await
|
tokio::time::timeout(Duration::from_millis(100), sock.recv_from(&mut buf)).await
|
||||||
{
|
{
|
||||||
answered += 1;
|
replies.push(Message::from_vec(&buf[..n]).unwrap());
|
||||||
}
|
}
|
||||||
|
replies
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-7: DNS over UDP is rate limited per address from a fixed
|
||||||
|
/// table, and a sender over its rate is answered "truncated" (a real
|
||||||
|
/// resolver then asks over TCP), not left without an answer.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn dns_over_udp_over_the_rate_is_answered_truncated() {
|
||||||
|
let env = start(Limits {
|
||||||
|
dns_qps_per_ip: 5,
|
||||||
|
..quick_limits()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let replies = dns_flood(env.relay.dns_udp_addr(), 200).await;
|
||||||
|
let answered = replies.iter().filter(|m| !m.answers.is_empty()).count();
|
||||||
|
let truncated = replies.iter().filter(|m| m.metadata.truncation).count();
|
||||||
assert!((5..=30).contains(&answered), "{answered} of 200 answered");
|
assert!((5..=30).contains(&answered), "{answered} of 200 answered");
|
||||||
|
assert_eq!(
|
||||||
|
answered + truncated,
|
||||||
|
replies.len(),
|
||||||
|
"every reply is one or the other"
|
||||||
|
);
|
||||||
|
assert!(truncated >= 150, "{truncated} truncated replies of 200");
|
||||||
|
assert!(
|
||||||
|
replies
|
||||||
|
.iter()
|
||||||
|
.filter(|m| m.metadata.truncation)
|
||||||
|
.all(|m| m.answers.is_empty() && m.queries.len() == 1)
|
||||||
|
);
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-7: all UDP answers together are limited; past the ceiling a
|
||||||
|
/// query gets nothing at all (the truncated reply is for one noisy sender,
|
||||||
|
/// not a way to be reflected off at any rate).
|
||||||
|
#[tokio::test]
|
||||||
|
async fn dns_over_udp_has_a_global_ceiling() {
|
||||||
|
let env = start(Limits {
|
||||||
|
dns_qps_per_ip: 10_000,
|
||||||
|
dns_qps_global: 10,
|
||||||
|
..quick_limits()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let replies = dns_flood(env.relay.dns_udp_addr(), 300).await;
|
||||||
|
assert!(
|
||||||
|
(10..=60).contains(&replies.len()),
|
||||||
|
"{} of 300 queries were answered past a ceiling of 10 a second",
|
||||||
|
replies.len()
|
||||||
|
);
|
||||||
env.relay.shutdown().await;
|
env.relay.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -880,6 +973,326 @@ async fn dns_over_tcp_is_capped_and_times_out() {
|
|||||||
env.relay.shutdown().await;
|
env.relay.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn refusal_of(r: Result<client::Line, ClientError>) -> Refusal {
|
||||||
|
match r {
|
||||||
|
Err(ClientError::Refused(why)) => why,
|
||||||
|
Err(other) => panic!("not a refusal: {other}"),
|
||||||
|
Ok(_) => panic!("the line came up"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-7: one address cannot fill the pool of line handshakes by
|
||||||
|
/// finishing the hello and stalling, over and over. The hello's own
|
||||||
|
/// per-address place is given back after the hello; the handshake has a
|
||||||
|
/// per-address place of its own, held to the verdict.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn one_address_cannot_hold_the_pool_of_line_handshakes() {
|
||||||
|
let env = start(Limits {
|
||||||
|
max_handshakes_per_ip: 2,
|
||||||
|
handshake_timeout_ms: 20_000,
|
||||||
|
..quick_limits()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
// Two handshakes that get the challenge and then say nothing.
|
||||||
|
let mut stalled = Vec::new();
|
||||||
|
for _ in 0..2 {
|
||||||
|
let mut s = client::tls_connect(env.router(), env.line_tls(), RELAY_HOST)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let _ch: Challenge = read_frame(&mut s).await.unwrap();
|
||||||
|
stalled.push(s);
|
||||||
|
}
|
||||||
|
// The pool (1 024) is nearly empty, but this address has its two.
|
||||||
|
assert!(
|
||||||
|
client::tls_connect(env.router(), env.line_tls(), RELAY_HOST)
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"a third handshake from one address was taken"
|
||||||
|
);
|
||||||
|
let (key, _) = AppKey::generate();
|
||||||
|
assert!(env.connect(n(NAME), &key, true).await.is_err());
|
||||||
|
assert_eq!(count(&env.relay.shared().metrics.shed), 2);
|
||||||
|
// A place freed is reusable: the owner gets in.
|
||||||
|
drop(stalled.pop());
|
||||||
|
let mut up = false;
|
||||||
|
for _ in 0..80 {
|
||||||
|
if env.connect(n(NAME), &key, true).await.is_ok() {
|
||||||
|
up = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||||
|
}
|
||||||
|
assert!(up, "the place was never given back");
|
||||||
|
drop(stalled);
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-7: the same, per network: an IPv4 /24 (here, loopback's) or an
|
||||||
|
/// IPv6 /48 holds only so many unfinished hellos, however its addresses
|
||||||
|
/// are spread.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn one_network_cannot_hold_many_unfinished_hellos() {
|
||||||
|
let env = start(Limits {
|
||||||
|
max_pending_per_ip: 100,
|
||||||
|
max_pending_per_net: 2,
|
||||||
|
hello_timeout_ms: 20_000,
|
||||||
|
..quick_limits()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let _a = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
let _b = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
eventually("two pending", || {
|
||||||
|
count(&env.relay.shared().metrics.accepted) == 2
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let mut c = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
let mut buf = [0u8; 4];
|
||||||
|
let r = tokio::time::timeout(Duration::from_secs(2), c.read(&mut buf))
|
||||||
|
.await
|
||||||
|
.expect("closed at once, not at the timeout");
|
||||||
|
assert!(matches!(r, Ok(0) | Err(_)));
|
||||||
|
assert_eq!(count(&env.relay.shared().metrics.shed), 1);
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-7: with the pool of unfinished hellos full, an address that
|
||||||
|
/// held a proven line lately still gets through, from a small reserve; a
|
||||||
|
/// stranger does not. (The server name is not known before the hello is
|
||||||
|
/// read, so the reserve is for who is calling.)
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_known_line_address_still_gets_a_hello_place_when_the_pool_is_full() {
|
||||||
|
let limits = Limits {
|
||||||
|
max_pending_hellos: 2,
|
||||||
|
hello_reserve: 2,
|
||||||
|
hello_timeout_ms: 20_000,
|
||||||
|
..quick_limits()
|
||||||
|
};
|
||||||
|
// A stranger: the pool is two, and there is no reserve for it.
|
||||||
|
let env = start(limits.clone()).await;
|
||||||
|
let _a = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
let _b = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
eventually("the pool is full", || {
|
||||||
|
count(&env.relay.shared().metrics.accepted) == 2
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let mut c = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
let mut buf = [0u8; 4];
|
||||||
|
let r = tokio::time::timeout(Duration::from_secs(2), c.read(&mut buf))
|
||||||
|
.await
|
||||||
|
.expect("closed at once");
|
||||||
|
assert!(matches!(r, Ok(0) | Err(_)));
|
||||||
|
assert_eq!(count(&env.relay.shared().metrics.shed), 1);
|
||||||
|
assert!(
|
||||||
|
env.connect(relay::names::Name::random(), &AppKey::generate().0, true)
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"a stranger used the reserve"
|
||||||
|
);
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
|
||||||
|
// A known address: it held a line before the flood.
|
||||||
|
let env = start(limits).await;
|
||||||
|
let (key, _) = AppKey::generate();
|
||||||
|
let line = env.connect(n(NAME), &key, true).await.unwrap();
|
||||||
|
line.close().await;
|
||||||
|
let _a = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
let _b = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
eventually("the pool is full", || {
|
||||||
|
count(&env.relay.shared().metrics.accepted) == 3
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let again = env.connect(n(NAME), &key, false).await;
|
||||||
|
assert!(
|
||||||
|
again.is_ok(),
|
||||||
|
"the owner could not reconnect through the flood"
|
||||||
|
);
|
||||||
|
// The reserve is small too: two more silent peers use it up.
|
||||||
|
let _c = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
let _d = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
eventually("the reserve is used", || {
|
||||||
|
count(&env.relay.shared().metrics.accepted) == 6
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let mut e = TcpStream::connect(env.router()).await.unwrap();
|
||||||
|
let r = tokio::time::timeout(Duration::from_secs(2), e.read(&mut buf))
|
||||||
|
.await
|
||||||
|
.expect("closed at once");
|
||||||
|
assert!(matches!(r, Ok(0) | Err(_)));
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-4 / WB-relay-5: claiming a name does not spend the certificate
|
||||||
|
/// authority's weekly budget; a name's first publish does, once, and a
|
||||||
|
/// renewal is free.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_certificate_budget_is_spent_at_first_publish_not_at_claim() {
|
||||||
|
let env = start(Limits {
|
||||||
|
cert_publishes_per_window: 2,
|
||||||
|
..quick_limits()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
for _ in 0..4 {
|
||||||
|
let (k, _) = AppKey::generate();
|
||||||
|
lines.push(
|
||||||
|
env.connect(relay::names::Name::random(), &k, true)
|
||||||
|
.await
|
||||||
|
.expect("claims are not limited by the certificate budget"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(count(&env.relay.shared().metrics.claims), 4);
|
||||||
|
assert!(lines[0].publish_txt(PROOF_A).await.unwrap().ok);
|
||||||
|
assert!(lines[1].publish_txt(PROOF_A).await.unwrap().ok);
|
||||||
|
let third = lines[2].publish_txt(PROOF_A).await.unwrap();
|
||||||
|
assert!(
|
||||||
|
!third.ok && third.error.as_deref() == Some("limit"),
|
||||||
|
"{third:?}"
|
||||||
|
);
|
||||||
|
// A renewal for a name that has been charged is not a new name.
|
||||||
|
assert!(lines[0].publish_txt(PROOF_B).await.unwrap().ok);
|
||||||
|
assert!(lines[1].publish_txt(PROOF_B).await.unwrap().ok);
|
||||||
|
assert_eq!(count(&env.relay.shared().metrics.cert_charges), 2);
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same first publishes are limited per address: one address cannot
|
||||||
|
/// spend the budget on names of its own however it came by them.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn first_publishes_are_limited_per_address() {
|
||||||
|
let env = start(Limits {
|
||||||
|
cert_publishes_per_ip: 1,
|
||||||
|
..quick_limits()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let (ka, _) = AppKey::generate();
|
||||||
|
let (kb, _) = AppKey::generate();
|
||||||
|
let a = env.connect(n(NAME), &ka, true).await.unwrap();
|
||||||
|
let b = env.connect(n(OTHER), &kb, true).await.unwrap();
|
||||||
|
assert!(a.publish_txt(PROOF_A).await.unwrap().ok);
|
||||||
|
let r = b.publish_txt(PROOF_A).await.unwrap();
|
||||||
|
assert!(!r.ok && r.error.as_deref() == Some("limit"), "{r:?}");
|
||||||
|
assert!(
|
||||||
|
a.publish_txt(PROOF_B).await.unwrap().ok,
|
||||||
|
"a renewal is free"
|
||||||
|
);
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-4: blocking a name closes its live line, within the check
|
||||||
|
/// interval, and the line does not come back.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn blocking_a_name_closes_its_live_line() {
|
||||||
|
let env = start(Limits {
|
||||||
|
block_check_ms: 200,
|
||||||
|
..quick_limits()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let (key, _) = AppKey::generate();
|
||||||
|
let (other_key, _) = AppKey::generate();
|
||||||
|
let app = env.app(n(NAME), &key, true).await;
|
||||||
|
let bystander = env.connect(n(OTHER), &other_key, true).await.unwrap();
|
||||||
|
assert!(env.assistant(&host_of(&n(NAME))).await.is_ok());
|
||||||
|
assert_eq!(env.relay.shared().lines.len(), 2);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
env.relay
|
||||||
|
.shared()
|
||||||
|
.registry
|
||||||
|
.set_blocked(&n(NAME), true)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
);
|
||||||
|
eventually("the blocked line is closed", || app.line.is_closed()).await;
|
||||||
|
eventually("and gone from the table", || {
|
||||||
|
env.relay.shared().lines.get(&n(NAME)).is_none()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(env.assistant(&host_of(&n(NAME))).await.is_err());
|
||||||
|
assert_eq!(
|
||||||
|
refusal_of(env.connect(n(NAME), &key, false).await),
|
||||||
|
Refusal::Blocked
|
||||||
|
);
|
||||||
|
// Only that name's line went.
|
||||||
|
assert!(!bystander.is_closed());
|
||||||
|
assert!(count(&env.relay.shared().metrics.blocked_closed) >= 1);
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-4: the next publish of a blocked name closes its line, without
|
||||||
|
/// waiting for the sweep (here set an hour apart), and publishes nothing.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_blocked_name_cannot_publish_and_its_line_is_closed() {
|
||||||
|
let env = start(Limits {
|
||||||
|
block_check_ms: 3_600_000,
|
||||||
|
..quick_limits()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let (key, _) = AppKey::generate();
|
||||||
|
let line = env.connect(n(NAME), &key, true).await.unwrap();
|
||||||
|
assert!(line.publish_txt(PROOF_A).await.unwrap().ok);
|
||||||
|
env.relay
|
||||||
|
.shared()
|
||||||
|
.registry
|
||||||
|
.set_blocked(&n(NAME), true)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
// The sweep is an hour away; the line is still up.
|
||||||
|
assert!(!line.is_closed());
|
||||||
|
let r = line.publish_txt(PROOF_B).await;
|
||||||
|
assert!(
|
||||||
|
!matches!(&r, Ok(r) if r.ok),
|
||||||
|
"a blocked name published: {r:?}"
|
||||||
|
);
|
||||||
|
eventually("the line is closed", || line.is_closed()).await;
|
||||||
|
let q = format!("_acme-challenge.{NAME}.{DOMAIN}.");
|
||||||
|
let values = txt_values(&dns(env.relay.dns_udp_addr(), &q, RecordType::TXT).await);
|
||||||
|
assert!(!values.contains(&PROOF_B.to_string()), "{values:?}");
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-relay-2: a caller who has not shown the name's key cannot tell a
|
||||||
|
/// name nobody has claimed from one held by another key, or a blocked one.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_stranger_cannot_tell_which_names_exist_or_are_blocked() {
|
||||||
|
let env = start(quick_limits()).await;
|
||||||
|
let (owner, _) = AppKey::generate();
|
||||||
|
let (owner2, _) = AppKey::generate();
|
||||||
|
let (stranger, _) = AppKey::generate();
|
||||||
|
let blocked = n("ledger-accrual-tally-audit");
|
||||||
|
env.connect(n(NAME), &owner, true).await.unwrap();
|
||||||
|
env.connect(blocked, &owner2, true).await.unwrap();
|
||||||
|
env.relay
|
||||||
|
.shared()
|
||||||
|
.registry
|
||||||
|
.set_blocked(&blocked, true)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let unclaimed = n(OTHER);
|
||||||
|
// Reconnecting: held, blocked and unclaimed all answer the same.
|
||||||
|
for name in [n(NAME), blocked, unclaimed] {
|
||||||
|
assert_eq!(
|
||||||
|
refusal_of(env.connect(name, &stranger, false).await),
|
||||||
|
Refusal::BadProof,
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Claiming: held and blocked answer alike (a claim has to learn if the
|
||||||
|
// name is free, and a blocked name is not).
|
||||||
|
for name in [n(NAME), blocked] {
|
||||||
|
assert_eq!(
|
||||||
|
refusal_of(env.connect(name, &stranger, true).await),
|
||||||
|
Refusal::Taken,
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// The holder of the key is told the truth.
|
||||||
|
assert_eq!(
|
||||||
|
refusal_of(env.connect(blocked, &owner2, false).await),
|
||||||
|
Refusal::Blocked
|
||||||
|
);
|
||||||
|
env.relay.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
/// Shutting down closes the lines.
|
/// Shutting down closes the lines.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn shutdown_closes_every_line() {
|
async fn shutdown_closes_every_line() {
|
||||||
|
|||||||
Reference in new issue
Block a user