use std::{
io,
sync::atomic::{AtomicUsize, Ordering},
time::Instant,
};
use futures_lite::io::AsyncWriteExt as _;
use crate::{
Address, CatchAll, Certainty, Finding, FindingCode, MailboxStatus, Outcome, SmtpPolicy,
Timeouts, TlsPolicy,
dns::Resolution,
runtime::{BoxIo, Connector, Timer, TlsConnector, timeout},
};
mod reply;
use reply::{advertises, classify, read as read_response, transaction_failure, unknown};
const MAX_DESTINATIONS: usize = 16;
const CATCH_ALL_LOCAL_BYTES: usize = 37;
static NEXT_DESTINATION: AtomicUsize = AtomicUsize::new(0);
pub(crate) struct Observation {
pub(crate) status: MailboxStatus,
pub(crate) findings: Vec<Finding>,
}
pub(crate) struct Capabilities<'a> {
pub(crate) connector: &'a dyn Connector,
pub(crate) timer: &'a dyn Timer,
pub(crate) tls: Option<&'a dyn TlsConnector>,
}
pub(crate) struct Probe<'a> {
pub(crate) routes: &'a Resolution,
pub(crate) address: &'a Address,
pub(crate) identity: &'a str,
pub(crate) policy: SmtpPolicy,
pub(crate) timeouts: Timeouts,
}
pub(crate) async fn probe(capabilities: Capabilities<'_>, probe: Probe<'_>) -> Observation {
let mut inconclusive = None;
for (exchange, address_ip) in destinations(probe.routes) {
let destination = std::net::SocketAddr::new(address_ip, 25);
let deadline = Instant::now()
.checked_add(probe.timeouts.connect())
.unwrap_or_else(Instant::now);
let Ok(Ok(stream)) = timeout(
capabilities.timer,
probe.timeouts.connect(),
capabilities.connector.connect(destination, deadline),
)
.await
else {
continue;
};
if let Ok(observation) = conversation(stream, &capabilities, &probe, exchange).await {
if observation.status == MailboxStatus::Unknown {
inconclusive = Some(observation);
} else {
return observation;
}
}
}
inconclusive.unwrap_or_else(|| {
unknown(
FindingCode::SmtpTemporaryFailure,
"no safe mail exchanger completed the SMTP probe",
)
})
}
fn destinations(routes: &Resolution) -> Vec<(&str, std::net::IpAddr)> {
let turn = NEXT_DESTINATION.fetch_add(1, Ordering::Relaxed);
let mut exchanges = routes.exchanges().iter().collect::<Vec<_>>();
let mut group_start = 0;
while group_start < exchanges.len() {
let preference = exchanges[group_start].preference();
let group_end = exchanges[group_start..]
.iter()
.position(|exchange| exchange.preference() != preference)
.map_or(exchanges.len(), |offset| group_start + offset);
let group = &mut exchanges[group_start..group_end];
let group_length = group.len();
group.rotate_left(turn % group_length);
group_start = group_end;
}
let mut destinations = Vec::with_capacity(MAX_DESTINATIONS);
for exchange in &exchanges {
let addresses = exchange.addresses();
if addresses.is_empty() {
continue;
}
let start = turn % addresses.len();
for offset in 0..addresses.len() {
let address = addresses[(start + offset) % addresses.len()];
if crate::network::is_public(address)
&& !destinations.contains(&(exchange.host(), address))
{
destinations.push((exchange.host(), address));
if destinations.len() == MAX_DESTINATIONS {
return destinations;
}
}
}
}
destinations
}
async fn conversation(
mut stream: BoxIo,
capabilities: &Capabilities<'_>,
probe: &Probe<'_>,
exchange: &str,
) -> io::Result<Observation> {
let timer = capabilities.timer;
let command_timeout = probe.timeouts.command();
let address = probe.address;
let identity = probe.identity;
let greeting = read_response(stream.as_mut(), timer, command_timeout).await?;
if greeting.code / 100 != 2 {
return Ok(transaction_failure(greeting));
}
command(
stream.as_mut(),
timer,
command_timeout,
format!("EHLO {identity}\r\n"),
)
.await?;
let ehlo = read_response(stream.as_mut(), timer, command_timeout).await?;
let mut extensions = if ehlo.code / 100 == 2 {
ehlo.message
} else {
if !helo_fallback(ehlo.code) {
return Ok(transaction_failure(ehlo));
}
command(
stream.as_mut(),
timer,
command_timeout,
format!("HELO {identity}\r\n"),
)
.await?;
let helo = read_response(stream.as_mut(), timer, command_timeout).await?;
if helo.code / 100 != 2 {
return Ok(transaction_failure(helo));
}
String::new()
};
if advertises(&extensions, "STARTTLS")
&& let Some(tls) = capabilities.tls
{
command(stream.as_mut(), timer, command_timeout, "STARTTLS\r\n").await?;
let starttls = read_response(stream.as_mut(), timer, command_timeout).await?;
if starttls.code != 220 {
return Ok(unknown(
FindingCode::SmtpTemporaryFailure,
"the server did not permit the STARTTLS upgrade",
));
}
stream = match timeout(timer, command_timeout, tls.upgrade(exchange, stream)).await {
Ok(Ok(upgraded)) => upgraded,
Ok(Err(_)) | Err(_) => {
return Ok(unknown(
FindingCode::SmtpTemporaryFailure,
"authenticated STARTTLS negotiation failed",
));
}
};
command(
stream.as_mut(),
timer,
command_timeout,
format!("EHLO {identity}\r\n"),
)
.await?;
let ehlo = read_response(stream.as_mut(), timer, command_timeout).await?;
if ehlo.code / 100 != 2 {
return Ok(unknown(
FindingCode::SmtpTemporaryFailure,
"the server rejected EHLO after STARTTLS",
));
}
extensions = ehlo.message;
} else if probe.policy.tls() == TlsPolicy::Required {
return Ok(unknown(
FindingCode::SmtpPolicyBlocked,
"policy requires STARTTLS before recipient probing",
));
}
let smtp_utf8 = if address.requires_smtputf8() {
if !advertises(&extensions, "SMTPUTF8") {
return Ok(unknown(
FindingCode::SmtpRequiresSmtpUtf8,
"the server does not advertise required SMTPUTF8 support",
));
}
" SMTPUTF8"
} else {
""
};
command(
stream.as_mut(),
timer,
command_timeout,
format!("MAIL FROM:<>{smtp_utf8}\r\n"),
)
.await?;
let mail = read_response(stream.as_mut(), timer, command_timeout).await?;
if mail.code / 100 != 2 {
return Ok(transaction_failure(mail));
}
command(
stream.as_mut(),
timer,
command_timeout,
format!(
"RCPT TO:<{}@{}>\r\n",
address.local(),
address.domain().ascii()
),
)
.await?;
let recipient = read_response(stream.as_mut(), timer, command_timeout).await?;
let mut observation = classify(recipient);
let reset = reset_transaction(stream.as_mut(), timer, command_timeout).await;
if observation.status == MailboxStatus::Accepted
&& probe.policy.catch_all() == CatchAll::OneProbe
{
let catch_all = if reset.is_ok_and(|accepted| accepted) {
catch_all_probe(
stream.as_mut(),
timer,
command_timeout,
address.domain().ascii(),
)
.await
.unwrap_or_else(|_| {
Finding::new(
FindingCode::SmtpCatchAllUnknown,
Outcome::Unknown,
Certainty::Strong,
"the generated recipient probe could not be completed",
)
})
} else {
Finding::new(
FindingCode::SmtpCatchAllUnknown,
Outcome::Unknown,
Certainty::Strong,
"the server did not reset the primary SMTP transaction",
)
};
observation.findings.push(catch_all);
}
let _ = command(stream.as_mut(), timer, command_timeout, "QUIT\r\n").await;
Ok(observation)
}
const fn helo_fallback(code: u16) -> bool {
matches!(code, 500 | 502)
}
async fn reset_transaction(
stream: &mut dyn crate::runtime::Io,
timer: &dyn Timer,
duration: std::time::Duration,
) -> io::Result<bool> {
command(stream, timer, duration, "RSET\r\n").await?;
Ok(read_response(stream, timer, duration).await?.code / 100 == 2)
}
async fn catch_all_probe(
stream: &mut dyn crate::runtime::Io,
timer: &dyn Timer,
duration: std::time::Duration,
domain: &str,
) -> io::Result<Finding> {
if !catch_all_recipient_fits(domain) {
return Ok(Finding::new(
FindingCode::SmtpCatchAllUnknown,
Outcome::Unknown,
Certainty::Strong,
"the domain leaves no room for the generated recipient",
));
}
command(stream, timer, duration, "MAIL FROM:<>\r\n").await?;
if read_response(stream, timer, duration).await?.code / 100 != 2 {
return Ok(Finding::new(
FindingCode::SmtpCatchAllUnknown,
Outcome::Unknown,
Certainty::Strong,
"the catch-all probe could not start a mail transaction",
));
}
let mut random = [0_u8; 16];
getrandom::fill(&mut random)
.map_err(|_| io::Error::other("secure randomness is unavailable"))?;
let mut label = String::with_capacity(37);
label.push_str("pata-");
for byte in random {
use std::fmt::Write as _;
write!(label, "{byte:02x}").expect("writing to a string cannot fail");
}
command(
stream,
timer,
duration,
format!("RCPT TO:<{label}@{domain}>\r\n"),
)
.await?;
let response = read_response(stream, timer, duration).await?;
match (response.code, response.esc) {
(200..=299, _) => Ok(Finding::new(
FindingCode::SmtpCatchAll,
Outcome::Warning,
Certainty::Strong,
"the domain accepted a generated recipient probe",
)),
(500..=599, [5, 1, 1]) => Ok(Finding::new(
FindingCode::SmtpCatchAllRejected,
Outcome::Pass,
Certainty::Strong,
"the server reported that the generated mailbox does not exist",
)),
_ => Ok(Finding::new(
FindingCode::SmtpCatchAllUnknown,
Outcome::Unknown,
Certainty::Strong,
"the generated recipient probe was inconclusive",
)),
}
}
fn catch_all_recipient_fits(domain: &str) -> bool {
CATCH_ALL_LOCAL_BYTES + 1 + domain.len() <= Address::MAX_OCTETS
}
async fn command(
stream: &mut dyn crate::runtime::Io,
timer: &dyn Timer,
duration: std::time::Duration,
command: impl AsRef<[u8]>,
) -> io::Result<()> {
timeout(timer, duration, stream.write_all(command.as_ref())).await??;
timeout(timer, duration, stream.flush()).await??;
Ok(())
}
#[cfg(test)]
mod tests {
use crate::dns::{MailExchange, Resolution, ResolutionKind};
use super::{MAX_DESTINATIONS, catch_all_recipient_fits, destinations, helo_fallback};
#[test]
fn helo_fallback_requires_an_unsupported_ehlo_command() {
assert!(helo_fallback(500));
assert!(helo_fallback(502));
assert!(!helo_fallback(451));
assert!(!helo_fallback(550));
}
#[test]
fn lower_mx_preference_exhausts_its_addresses_first() {
let primary = MailExchange::new(
10,
"mx-1.example",
(1..=16)
.map(|last| std::net::IpAddr::from([1, 1, 1, last]))
.collect(),
)
.unwrap();
let backup = MailExchange::new(
20,
"mx-2.example",
vec![std::net::IpAddr::from([8, 8, 8, 8])],
)
.unwrap();
let routes = Resolution::new(ResolutionKind::Mx, vec![primary, backup], None);
let selected = destinations(&routes);
assert_eq!(selected.len(), MAX_DESTINATIONS);
assert!(selected.iter().all(|(host, _)| *host == "mx-1.example"));
}
#[test]
fn catch_all_probe_respects_the_mailbox_length_limit() {
assert!(catch_all_recipient_fits("example.com"));
assert!(!catch_all_recipient_fits(&"a".repeat(253)));
}
#[test]
fn private_and_documentation_destinations_are_blocked() {
assert!(!crate::network::is_public("127.0.0.1".parse().unwrap()));
assert!(!crate::network::is_public("0.1.2.3".parse().unwrap()));
assert!(!crate::network::is_public("192.0.2.1".parse().unwrap()));
assert!(!crate::network::is_public("192.0.0.8".parse().unwrap()));
assert!(!crate::network::is_public("192.88.99.1".parse().unwrap()));
assert!(!crate::network::is_public("100.64.0.1".parse().unwrap()));
assert!(!crate::network::is_public("198.18.0.1".parse().unwrap()));
assert!(!crate::network::is_public("2001:db8::1".parse().unwrap()));
assert!(!crate::network::is_public("2001:2::1".parse().unwrap()));
assert!(!crate::network::is_public(
"2002:0a00:1::1".parse().unwrap()
));
assert!(!crate::network::is_public("4000::1".parse().unwrap()));
assert!(!crate::network::is_public("fec0::1".parse().unwrap()));
assert!(!crate::network::is_public("::1.2.3.4".parse().unwrap()));
assert!(crate::network::is_public("1.1.1.1".parse().unwrap()));
}
}