Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ color-eyre = "0.6"
# probes
hickory-resolver = "0.26"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
# only to read the certificate error out of a failed reqwest request
rustls = { version = "0.23", default-features = false }
# cli + serialization
clap = { version = "4", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ complete:
rate, graded into a signal quality.
3. **L3 Gateway** — resolves the default route and sends a short ICMP burst to the router, measuring RTT, packet loss and jitter, and flagging VPN/tunnel interfaces and sub-1500 MTU.
4. **Uplink** — when, and only when, something upstream is already broken, a bounded ICMP TTL sweep turns the single edge between your gateway and the internet back into hops. Where the replies stop decides whether the break is on your own line (modem/ONU, WAN cable) or inside your ISP's network — and names the last address that answered, so you have something to quote.
5. **WAN** — real TCP handshakes to three independent anycast operators (Cloudflare, Google, Quad9) over IPv4 and IPv6, which exposes asymmetric blackholing without needing raw ICMP and separates "the internet is unreachable" from "this network blocks that address". It then repeats the handshake against the quickest one to measure loss and jitter on the uplink itself.
5. **WAN** — real TCP handshakes to three independent anycast operators (Cloudflare, Google, Quad9) over IPv4 and IPv6, which exposes asymmetric blackholing without needing raw ICMP and separates "the internet is unreachable" from "this network blocks that address". It then repeats the handshake against the quickest one to measure loss and jitter on the uplink itself. One real HTTPS request checks that the handshakes carry traffic; when it is refused because the certificate isn't valid yet, the verdict blames this machine's clock instead of the network.
6. **DNS** — benchmarks the system resolver against Cloudflare and Google to
separate "DNS is down" from "your resolver is just slow".
7. **Captive portal** — a plain-HTTP hotspot check that catches login-page
Expand Down
22 changes: 22 additions & 0 deletions src/diagnose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,11 @@ fn explain_warn(path: &Path, id: HopId) -> Verdict {
// diagram cannot show you, so the verdict has to say it in words.
// Ahead of both arms below: "the path carries nothing" outranks "the
// path is lossy" and "the path is filtered".
HopId::Wan if path.get(id).and_then(|h| h.fault) == Some(Fault::ClockBehind) => (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the comment block above (lines 482–486, "Every hop is green and nothing works… Ahead of both arms below") described the HandshakeOnly arm. The new ClockBehind arm is inserted between it and that arm, so the comment now sits on the wrong one. Move the new arm above the comment, or give it its own line.

Also, in the IPv6-only case (wan.rs, (false, true)) the verdict becomes "Your clock is behind" and the fix is only NTP. The IPv4 blackhole shows up only as a "separately, …" clause in the summary. That's a defensible call, and the earlier commit said it wanted to keep that finding. The headline and fix will still read as fully resolved once the clock is corrected.

"Your clock is behind",
format!("{summary}. Every HTTPS site will refuse to connect until the date and time are right."),
Some("Turn on automatic date and time (NTP) and run again. Devices without a battery-backed clock, like a Raspberry Pi, lose the time on every power cut.".to_string()),
),
HopId::Wan if path.get(id).and_then(|h| h.fault) == Some(Fault::HandshakeOnly) => (
"Something is answering for the internet",
"Every connection completes, but no real request does. A device on the path is replying to handshakes without carrying the traffic — an interception appliance, a misbehaving proxy, or a portal you haven't signed in to.".to_string(),
Expand Down Expand Up @@ -963,6 +968,23 @@ mod tests {
assert!(v.fix.as_deref().unwrap().contains("sign-in page"));
}

#[test]
fn a_clock_behind_is_blamed_on_the_clock_not_the_network() {
let mut wan = hop(HopId::Wan, Layer::Internet, Status::Warn);
wan.fault = Some(Fault::ClockBehind);
let p = Path {
hops: vec![
hop(HopId::Host, Layer::Link, Status::Ok),
hop(HopId::Link, Layer::Link, Status::Ok),
hop(HopId::Gateway, Layer::Network, Status::Ok),
wan,
],
};
let v = diagnose(&p);
assert!(v.headline.contains("clock"), "{}", v.headline);
assert!(v.fix.as_deref().unwrap().contains("NTP"));
}

/// The verdict this whole hop exists to replace. "Your ISP / uplink is
/// down — check the modem lights" is the part the reader already knew;
/// once the sweep has located the break, the verdict has to use it.
Expand Down
5 changes: 5 additions & 0 deletions src/model/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ pub enum Fault {
/// Every TCP handshake completes, but no real request does — something on
/// the path answers connections without carrying them.
HandshakeOnly,
/// The HTTPS certificate is not yet valid by this machine's clock: the
/// clock is behind, so every TLS connection fails.
ClockBehind,
/// The system resolver returned no answer.
ResolverDead,
/// The system resolver answers, but not truthfully — it synthesises
Expand Down Expand Up @@ -121,6 +124,7 @@ impl Fault {
Fault::NoInternet => "no_internet",
Fault::TargetBlocked => "target_blocked",
Fault::HandshakeOnly => "handshake_only",
Fault::ClockBehind => "clock_behind",
Fault::ResolverDead => "resolver_dead",
Fault::ResolverHijacked => "resolver_hijacked",
Fault::PortalIntercept => "portal_intercept",
Expand Down Expand Up @@ -467,6 +471,7 @@ mod tests {
Fault::NoInternet,
Fault::TargetBlocked,
Fault::HandshakeOnly,
Fault::ClockBehind,
Fault::ResolverDead,
Fault::ResolverHijacked,
Fault::PortalIntercept,
Expand Down
149 changes: 130 additions & 19 deletions src/probe/wan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ struct Egress {
/// works". A middlebox can complete a handshake to anything; it cannot
/// produce Cloudflare's certificate.
verified: bool,
/// How far behind this machine's clock is, when a certificate was refused as not yet valid.
clock_lag: Option<u64>,
}

/// One family's results: which targets answered, and how fast.
Expand Down Expand Up @@ -201,10 +203,7 @@ pub async fn probe() -> Hop {
}
}

hop.evidence = Some(evidence(
v4.reached.len() + v6.reached.len(),
egress.verified,
));
hop.evidence = Some(evidence(v4.reached.len() + v6.reached.len(), &egress));

match (v4.any_up(), v6.any_up()) {
(true, dual_stack) => {
Expand All @@ -218,15 +217,22 @@ pub async fn probe() -> Hop {
let quality = apply_quality(&mut hop, &q, JITTER_WARN_MS);
let blocked = blocked_targets(&v4, &v6);
let handshake_only = handshake_only(&v4, &v6, &egress);
hop.status = quality.max(block_status(&blocked)).max(if handshake_only {
Status::Warn
} else {
Status::Ok
});
let clock_behind = egress.clock_lag.is_some();
hop.status =
quality
.max(block_status(&blocked))
.max(if handshake_only || clock_behind {
Status::Warn
} else {
Status::Ok
});
// Whichever finding is the more serious owns the code; a path that
// answers handshakes but carries nothing is worse news than one
// operator being filtered.
if handshake_only {
if clock_behind {
hop.fault = Some(Fault::ClockBehind);
hop.summary = Some(clock_summary(egress.clock_lag.unwrap_or_default()));
} else if handshake_only {
hop.fault = Some(Fault::HandshakeOnly);
hop.summary = Some(
"Every handshake completes but no real request does — something is answering connections on the path without carrying them".into(),
Expand All @@ -247,10 +253,17 @@ pub async fn probe() -> Hop {
(false, true) => {
hop.status = Status::Warn;
hop.latency_ms = v6.best().and_then(|(_, _, p)| p.ms());
hop.summary = Some(format!(
let blackholed = format!(
"IPv6-only reachable — all {} IPv4 targets are blackholed",
V4.len()
));
);
hop.summary = Some(match egress.clock_lag {
Some(lag) => {
hop.fault = Some(Fault::ClockBehind);
format!("{}; separately, {blackholed}", clock_summary(lag))
}
None => blackholed,
});
}
(false, false) => {
// Every operator, on every family, independently silent. That is
Expand Down Expand Up @@ -318,9 +331,10 @@ fn handshake_only(v4: &Family, v6: &Family, egress: &Egress) -> bool {
/// One complete request through the uplink: the check that makes a green hop
/// mean something, and the only place a public address can come from.
async fn verify_egress() -> Egress {
let unverified = Egress {
let mut unverified = Egress {
public_ip: None,
verified: false,
clock_lag: None,
};
let Ok(client) = reqwest::Client::builder().build() else {
return unverified;
Expand All @@ -337,8 +351,16 @@ async fn verify_egress() -> Egress {
if left < MIN_TRACE {
break;
}
let Ok(resp) = client.get(url).timeout(left).send().await else {
continue;
let resp = match client.get(url).timeout(left).send().await {
Ok(resp) => resp,
Err(e) => {
unverified.clock_lag = clock_lag(&e);
// The by-name retry would be judged by the same clock.
if unverified.clock_lag.is_some() {
break;
}
continue;
}
};
if !resp.status().is_success() {
continue;
Expand All @@ -352,12 +374,59 @@ async fn verify_egress() -> Egress {
return Egress {
public_ip: Some(ip),
verified: true,
clock_lag: None,
};
}
}
unverified
}

/// A certificate only this far ahead of the clock is more likely freshly minted by an interceptor.
const MIN_CLOCK_LAG: u64 = 3_600;

/// How far behind the clock is, when a request was refused for a certificate not yet valid.
fn clock_lag(err: &(dyn std::error::Error + 'static)) -> Option<u64> {
use rustls::{CertificateError, Error as TlsError};
let mut cur = Some(err);
while let Some(e) = cur {
if let Some(TlsError::InvalidCertificate(CertificateError::NotValidYetContext {
time,
not_before,
})) = e.downcast_ref::<TlsError>()
{
let lag = not_before.as_secs().saturating_sub(time.as_secs());
return (lag >= MIN_CLOCK_LAG).then_some(lag);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A real not-yet-valid refusal with a lag under one day (a clock a few hours behind, e.g. a wrong timezone, against a certificate issued recently) is dropped here. clock_lag returns None, so clock_behind is false and handshake_only can fire instead. The verdict is then "Something is answering for the internet… an interception appliance", and needs_uplink_sweep also spends the TTL sweep. That blames the network for a clock fault, which is the misdiagnosis this PR set out to remove. The 24h floor does guard against an interceptor minting certificates, but it trades one wrong verdict for another. Consider keeping a smaller floor, such as an hour. Or return an "unknown cause" result for sub-day lag, so it is not graded as HandshakeOnly.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lowered the floor to one hour (an RTC kept in local time is hours off), with a test at 9h. A certificate a few minutes ahead still goes to handshake_only.

}
// io::Error::source() skips the error it wraps, and hyper nests rustls two io::Errors deep.
cur = match e
.downcast_ref::<std::io::Error>()
.and_then(|io| io.get_ref())
{
Some(inner) => Some(inner as &(dyn std::error::Error + 'static)),
None => e.source(),
};
}
None
}

fn clock_summary(lag: u64) -> String {
format!(
"The internet answers, but its HTTPS certificate isn't valid for another {} by this machine's clock ({})",
if lag >= 86_400 {
format!("{} days", lag.div_ceil(86_400))
} else {
format!("{} hours", lag.div_ceil(3_600))
},
crate::history::utc(now_secs())
)
}

fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}

/// Pull the `ip=` line out of a `cdn-cgi/trace` response.
fn parse_trace(body: &str) -> Option<IpAddr> {
body.lines()
Expand Down Expand Up @@ -402,12 +471,14 @@ fn block_status(blocked: &[&str]) -> Status {
/// HTTPS request" was guaranteed to contradict the cause printed beside it
/// whenever `HandshakeOnly` fired — in exactly the case the evidence matters
/// most.
fn evidence(addresses: usize, verified: bool) -> String {
fn evidence(addresses: usize, egress: &Egress) -> String {
format!(
"{addresses} handshakes to :{PORT} across {} independent networks, and one HTTPS request that {}",
operator_count(),
if verified {
if egress.verified {
"completed"
} else if egress.clock_lag.is_some() {
"was refused: certificate not yet valid"
} else {
"did not complete"
}
Expand Down Expand Up @@ -667,9 +738,49 @@ mod tests {
Egress {
public_ip: None,
verified,
clock_lag: None,
}
}

#[test]
fn a_not_yet_valid_certificate_is_found_inside_the_io_error() {
use rustls::pki_types::UnixTime;
use rustls::{CertificateError, Error as TlsError};
let wrap = |c| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
TlsError::InvalidCertificate(c),
)
};
let at = |s: u64| UnixTime::since_unix_epoch(Duration::from_secs(s));
let ahead = |lag: u64| CertificateError::NotValidYetContext {
time: at(1_000_000_000),
not_before: at(1_000_000_000 + lag),
};
// The shape hyper actually returns: io::Error(Other) around io::Error(InvalidData) around rustls.
let nested = std::io::Error::other(wrap(ahead(3 * 86_400)));
assert_eq!(clock_lag(&nested), Some(3 * 86_400));
// An RTC kept in local time is hours off, not days.
assert_eq!(clock_lag(&wrap(ahead(9 * 3_600))), Some(9 * 3_600));
// Minutes ahead is an interceptor minting certificates, not our clock.
assert_eq!(clock_lag(&wrap(ahead(600))), None);
assert_eq!(clock_lag(&wrap(CertificateError::NotValidYet)), None);
// Expired could be a real stale certificate on an interception box, not our clock.
assert_eq!(clock_lag(&wrap(CertificateError::Expired)), None);
assert_eq!(clock_lag(&wrap(CertificateError::UnknownIssuer)), None);
assert_eq!(clock_lag(&std::io::Error::other("timed out")), None);
}

#[test]
fn a_refused_certificate_is_said_so_in_the_evidence() {
let e = Egress {
public_ip: None,
verified: false,
clock_lag: Some(86_400),
};
assert!(evidence(5, &e).contains("not yet valid"));
}

fn all_up() -> Family {
family(&[
("Cloudflare", Some(12)),
Expand Down Expand Up @@ -756,13 +867,13 @@ mod tests {
let v6 = family(&[("Cloudflare v6", None), ("Google v6", None)]);
assert!(handshake_only(&all_up(), &v6, &egress(false)));

let unverified = evidence(5, false);
let unverified = evidence(5, &egress(false));
assert!(unverified.contains("did not complete"), "got: {unverified}");
assert!(
!unverified.contains("verified"),
"must not read as a completed request: {unverified}"
);
assert!(evidence(5, true).contains("completed"));
assert!(evidence(5, &egress(true)).contains("completed"));
}

#[test]
Expand Down
Loading