pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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()));
    }
}