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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
mod macros;
mod query;
mod record;
mod terms;

use crate::{
    config::Config,
    eval::query::{Query, QueryParams, QueryState, Resolver, Sender},
    record::{Macro, Mechanism},
    resolve::Lookup,
    trace::{Trace, Tracepoint},
};
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
    net::IpAddr,
};

/// A trait for entities that evaluate to an `SpfResult`.
trait Evaluate {
    fn evaluate(&self, query: &mut Query, resolver: &Resolver) -> SpfResult;
}

/// The result of an SPF evaluation.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum SpfResult {
    /// The *none* authorisation result.
    None,
    /// The *neutral* authorisation result.
    Neutral,
    /// The *pass* authorisation result.
    Pass,
    // This variant’s `ExplanationString` argument is not optional due to §6.2:
    // ‘If no "exp" modifier is present, then either a default explanation
    // string or an empty explanation string MUST be returned to the calling
    // application.’
    /// The *fail* authorisation result, containing an explanation of the
    /// failure.
    Fail(ExplanationString),
    /// The *softfail* authorisation result.
    Softfail,
    /// The *temperror* error result.
    Temperror,
    /// The *permerror* error result.
    Permerror,
}

impl Display for SpfResult {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::None => write!(f, "none"),
            Self::Neutral => write!(f, "neutral"),
            Self::Pass => write!(f, "pass"),
            Self::Fail(explanation) => {
                if explanation.as_ref().is_empty() {
                    write!(f, "fail")
                } else {
                    write!(f, "fail ({})", explanation)
                }
            }
            Self::Softfail => write!(f, "softfail"),
            Self::Temperror => write!(f, "temperror"),
            Self::Permerror => write!(f, "permerror"),
        }
    }
}

/// An explanation of why a query evaluated to a [`Fail`] result.
///
/// If the explanation string is used in an SMTP response, clients must make
/// sure the contained `String` is limited to ASCII, according to section 6.2 of
/// RFC 7208.
///
/// [`Fail`]: enum.SpfResult.html#variant.Fail
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum ExplanationString {
    // `ExplanationString` is an enum with two variants in order to allow
    // clients to distinguish the two possible origins of the explanation. This
    // distinction is implied in §8.4: ‘The check_host() function will return
    // either a default explanation string or one from the domain that published
    // the SPF records […]. If the information does not originate with the
    // checking software’ …
    /// An explanation computed locally from configuration.
    Default(String),
    /// An explanation obtained remotely from the DNS.
    Dns(String),
}

impl Default for ExplanationString {
    fn default() -> Self {
        Self::Default(Default::default())
    }
}

impl Display for ExplanationString {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.as_ref().fmt(f)
    }
}

impl AsRef<str> for ExplanationString {
    fn as_ref(&self) -> &str {
        match self {
            Self::Default(s) | Self::Dns(s) => s,
        }
    }
}

impl From<ExplanationString> for String {
    fn from(explanation_string: ExplanationString) -> Self {
        match explanation_string {
            ExplanationString::Default(s) | ExplanationString::Dns(s) => s,
        }
    }
}

/// A trait for entities that may evaluate to a `MatchResult`.
trait EvaluateMatch {
    fn evaluate_match(&self, query: &mut Query, resolver: &Resolver) -> EvalResult<MatchResult>;
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum MatchResult {
    Match,
    NoMatch,
}

type EvalResult<T> = Result<T, EvalError>;

/// Errors that may occur during query evaluation.
#[derive(Debug)]
pub enum EvalError {
    /// The query timed out.
    Timeout,
    /// A DNS error occurred, with source attached if available. The error
    /// source may come from the `Lookup` implementation and is therefore of an
    /// arbitrary error type.
    Dns(Option<Box<dyn Error + Send + Sync>>),
    /// The lookup limit was exceeded.
    LookupLimitExceeded,
    /// The per-mechanism lookup limit was exceeded.
    PerMechanismLookupLimitExceeded,
    /// The void lookup limit was exceeded.
    VoidLookupLimitExceeded,
    /// A recursive query that failed with a `Temperror` is being propagated.
    RecursiveTemperror,
    /// A recursive query that failed with a `Permerror` is being propagated.
    RecursivePermerror,
    /// An *include* mechanism targeted a domain with no SPF record.
    IncludeNoRecord,
    /// A target domain name was in an invalid format.
    InvalidName(String),
    /// A domain specification contained an invalid macro.
    InvalidMacroInDomainSpec(Macro),
}

impl EvalError {
    fn to_spf_result(&self) -> SpfResult {
        match self {
            Self::Timeout | Self::Dns(_) | Self::RecursiveTemperror => SpfResult::Temperror,
            Self::LookupLimitExceeded
            | Self::PerMechanismLookupLimitExceeded
            | Self::VoidLookupLimitExceeded
            | Self::RecursivePermerror
            | Self::IncludeNoRecord
            // §4.8: ‘The result of evaluating check_host() with a syntactically
            // invalid domain is undefined. […] Some implementations choose to
            // treat such errors as not-match and therefore ignore such names,
            // while others return a "permerror" exception.’ This implementation
            // does in fact treat such errors as not-match, see the `Evaluate`
            // implementation in `crate::eval::record`. This variant maps to
            // `Permerror` specifically for use in `Redirect::evaluate`.
            | Self::InvalidName(_)
            | Self::InvalidMacroInDomainSpec(_) => SpfResult::Permerror,
        }
    }

    fn to_error_cause(&self) -> Option<ErrorCause> {
        use ErrorCause::*;
        match self {
            Self::Timeout => Some(Timeout),
            Self::Dns(_) => Some(Dns),
            Self::LookupLimitExceeded | Self::PerMechanismLookupLimitExceeded => Some(LookupLimitExceeded),
            Self::VoidLookupLimitExceeded => Some(VoidLookupLimitExceeded),
            Self::IncludeNoRecord => Some(NoSpfRecord),
            Self::InvalidName(_) | Self::InvalidMacroInDomainSpec(_) => Some(InvalidTargetDomain),
            // Recursive errors are not mapped.
            Self::RecursiveTemperror | Self::RecursivePermerror => None,
        }
    }
}

impl Error for EvalError {}

impl Display for EvalError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Timeout => write!(f, "timed out"),
            Self::Dns(error) => {
                write!(f, "DNS error")?;
                if let Some(error) = error {
                    write!(f, ": {}", error)?;
                }
                Ok(())
            }
            Self::LookupLimitExceeded => write!(f, "lookup limit exceeded"),
            Self::PerMechanismLookupLimitExceeded => write!(f, "per-mechanism lookup limit exceeded"),
            Self::VoidLookupLimitExceeded => write!(f, "void lookup limit exceeded"),
            Self::RecursiveTemperror => write!(f, "recursive query evaluated to \"temperror\" result"),
            Self::RecursivePermerror => write!(f, "recursive query evaluated to \"permerror\" result"),
            Self::IncludeNoRecord => write!(f, "no SPF record for include"),
            Self::InvalidName(name) => write!(f, "invalid target domain name \"{}\"", name),
            Self::InvalidMacroInDomainSpec(macro_) => write!(f, "invalid macro \"{}\" in domain spec", macro_),
        }
    }
}

/// A trait for entities that may evaluate to a string.
trait EvaluateToString {
    fn evaluate_to_string(&self, query: &mut Query, resolver: &Resolver) -> EvalResult<String>;
}

/// The result of evaluating an SPF query.
#[derive(Debug)]
pub struct QueryResult {
    /// The result of the SPF query.
    pub result: SpfResult,
    /// Details about the cause that produced the result, if available.
    pub cause: Option<SpfResultCause>,
    /// A trace of events that occurred during evaluation, if available.
    pub trace: Option<Trace>,
}

/// The cause that led to an SPF result.
///
/// This enumeration is intended to support reporting information with the
/// `mechanism` and `problem` keys described in section 9.1 of RFC 7208.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum SpfResultCause {
    /// The mechanism that matched in case of an authorisation result.
    Match(Mechanism),
    /// An indication of the error cause in case of an error result.
    Error(ErrorCause),
}

impl From<Mechanism> for SpfResultCause {
    fn from(mechanism: Mechanism) -> Self {
        Self::Match(mechanism)
    }
}

impl From<ErrorCause> for SpfResultCause {
    fn from(error_cause: ErrorCause) -> Self {
        Self::Error(error_cause)
    }
}

/// Causes of an SPF query error result.
///
/// These error causes provide a broad categorisation of an SPF error result
/// that may be shown to users. The `Display` representations are in ASCII and
/// contain no double quotes, such that they are directly suited for SMTP
/// messages, email headers, or similar. More detailed information about error
/// causes can be accessed in the trace.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ErrorCause {
    /// The query timed out.
    Timeout,
    /// A DNS error occurred.
    Dns,
    /// The lookup limit was exceeded.
    LookupLimitExceeded,
    /// The void lookup limit was exceeded.
    VoidLookupLimitExceeded,
    /// A recursive query found no SPF record at a target domain.
    NoSpfRecord,
    /// Multiple SPF records were found at a target domain.
    MultipleSpfRecords,
    /// An SPF record could not be parsed.
    InvalidSpfRecordSyntax,
    /// An SPF record contained an invalid target domain name.
    InvalidTargetDomain,
}

impl Display for ErrorCause {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        // These error messages are kept in a terse, alphabetic-ASCII-only style
        // suitable for SMTP messages or email headers.
        match self {
            Self::Timeout => write!(f, "DNS lookup timed out"),
            Self::Dns => write!(f, "DNS lookup failed"),
            Self::LookupLimitExceeded => write!(f, "lookup limit exceeded"),
            Self::VoidLookupLimitExceeded => write!(f, "void lookup limit exceeded"),
            Self::NoSpfRecord => write!(f, "no SPF record found at target domain"),
            Self::MultipleSpfRecords => write!(f, "more than one SPF record found"),
            Self::InvalidSpfRecordSyntax => write!(f, "invalid SPF record found"),
            Self::InvalidTargetDomain => write!(f, "invalid target domain name"),
        }
    }
}

/// Performs an SPF query and evaluation.
///
/// Arguments:
///
/// * `lookup` – an implementation of the [`Lookup`] trait, serving as a DNS
///   resolver
/// * `config` – a configuration object
/// * `ip` – the client IP address. This corresponds to the *&lt;ip&gt;*
///   argument in RFC 7208.
/// * `sender` – the sender identity. This corresponds to both the
///   *&lt;sender&gt;* and *&lt;domain&gt;* (= the domain part of
///   *&lt;sender&gt;*) arguments in RFC 7208; see the discussion below.
/// * `helo_domain` – the HELO/EHLO domain, used only for the `%{h}` macro
///
/// The return type `QueryResult` always conveys an SPF result, and, if
/// available, additional diagnostic information.
///
/// This function corresponds to the function [*check_host()*] of RFC 7208, as
/// is evident in the final three arguments `ip`, `sender`, and `helo_domain`.
/// However, the correspondence is not exact. The `ip` argument matches
/// *&lt;ip&gt;*. The `sender` argument covers both *&lt;sender&gt;* and
/// *&lt;domain&gt;*, since *&lt;domain&gt;* can be mechanically derived from
/// *&lt;sender&gt;*. Finally, `helo_domain` covers an argument missing in
/// *check_host()*, namely, the `%{h}` macro, which always evaluates to the HELO
/// domain.
///
/// The arguments `sender` and `helo_domain` are of type string slice. This is a
/// somewhat ‘weak’ type in the sense that it allows an unconstrained range of
/// (valid and invalid) inputs. Now, according to the specification, an
/// evaluation can only be performed when the domain of the sender identity is a
/// valid, fully-qualified domain name, else the result *none* is returned. In
/// other words, a valid `sender` is a prerequisite for an SPF query. For this
/// reason, this function parses and validates the `sender` argument eagerly at
/// the beginning. The `helo_domain` argument, on the other hand, which is used
/// only for the `%{h}` macro, is only examined when it is encountered during
/// macro expansion, as it rarely occurs in practice and should not impede
/// executing the SPF query. This aspect of the API is a bit subtle, and clients
/// who need more control over these inputs are advised to do their own
/// validation beforehand.
///
/// According to RFC 8616, internationalised domain names must be converted to
/// their ASCII representation before executing the SPF query. The
/// `evaluate_spf` function accepts both ASCII and Unicode-encoded inputs, and
/// will in any case properly apply the IDNA algorithm with Punycode encoding.
/// Internationalised email addresses and domain names may therefore be passed
/// in directly in Unicode format.
///
/// # Examples
///
/// The following examples illustrate usage of this function for SPF
/// verification of a host.
///
/// ## Verifying the HELO identity
///
/// When verifying the HELO/EHLO identity, the client host presents some
/// hostname with the `HELO` or `EHLO` SMTP command, for example,
/// `mail.example.org`.
///
/// Pass this string as both the `sender` and `helo_domain` argument.
///
/// ```
/// # use viaspf::{Name, LookupResult, Lookup, evaluate_spf};
/// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
/// # let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
/// # struct VoidLookup;
/// # impl Lookup for VoidLookup {
/// #     fn lookup_a(&self, name: &Name) -> LookupResult<Vec<Ipv4Addr>> { Ok(vec![]) }
/// #     fn lookup_aaaa(&self, name: &Name) -> LookupResult<Vec<Ipv6Addr>> { Ok(vec![]) }
/// #     fn lookup_mx(&self, name: &Name) -> LookupResult<Vec<Name>> { Ok(vec![]) }
/// #     fn lookup_txt(&self, name: &Name) -> LookupResult<Vec<String>> { Ok(vec![]) }
/// #     fn lookup_ptr(&self, ip: IpAddr) -> LookupResult<Vec<Name>> { Ok(vec![]) }
/// # }
/// # let lookup = VoidLookup;
/// # let config = Default::default();
/// let result = evaluate_spf(&lookup, &config, ip, "mail.example.org", "mail.example.org");
/// ```
///
/// In the terms of the *check_host()* function specification,
/// * *&lt;domain&gt;* will then be the sender identity, that is
///   `mail.example.org`;
/// * *&lt;sender&gt;* itself gets qualified with the local part `postmaster`
///   (see section 4.3 in the RFC) to become `postmaster@mail.example.org`.
///
/// ## Verifying the MAIL FROM identity
///
/// When verifying the MAIL FROM identity, the client host presents some email
/// address with the `MAIL FROM` SMTP command, for example, `amy@example.org`.
/// Before that, it will also have presented some HELO/EHLO hostname, for
/// example, `mail.example.org`.
///
/// Pass these strings as the `sender` and `helo_domain` argument, respectively.
///
/// ```
/// # use viaspf::{Name, LookupResult, Lookup, evaluate_spf};
/// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
/// # let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
/// # struct VoidLookup;
/// # impl Lookup for VoidLookup {
/// #     fn lookup_a(&self, name: &Name) -> LookupResult<Vec<Ipv4Addr>> { Ok(vec![]) }
/// #     fn lookup_aaaa(&self, name: &Name) -> LookupResult<Vec<Ipv6Addr>> { Ok(vec![]) }
/// #     fn lookup_mx(&self, name: &Name) -> LookupResult<Vec<Name>> { Ok(vec![]) }
/// #     fn lookup_txt(&self, name: &Name) -> LookupResult<Vec<String>> { Ok(vec![]) }
/// #     fn lookup_ptr(&self, ip: IpAddr) -> LookupResult<Vec<Name>> { Ok(vec![]) }
/// # }
/// # let lookup = VoidLookup;
/// # let config = Default::default();
/// let result = evaluate_spf(&lookup, &config, ip, "amy@example.org", "mail.example.org");
/// ```
///
/// In the terms of the *check_host()* function specification,
/// * *&lt;domain&gt;* will then be the domain part of the sender identity, that
///   is `example.org`;
/// * *&lt;sender&gt;* will be the sender identity, that is `amy@example.org`.
///
/// [`Lookup`]: trait.Lookup.html
/// [*check_host()*]: https://www.rfc-editor.org/rfc/rfc7208#section-4
pub fn evaluate_spf(
    lookup: &impl Lookup,
    config: &Config,
    ip: IpAddr,
    sender: &str,
    helo_domain: &str,
) -> QueryResult {
    // §4.3: ‘If the <domain> is malformed […] or is not a multi-label domain
    // name, […] check_host() immediately returns the result "none".’
    let sender = match Sender::new(sender) {
        Ok(sender) => sender,
        Err(_) => {
            let trace = if config.capture_trace() {
                let mut trace = Trace::new();
                trace.add_event(Tracepoint::InvalidSenderParam(sender.to_owned()));
                Some(trace)
            } else {
                None
            };
            return QueryResult {
                result: SpfResult::None,
                cause: None,
                trace,
            };
        }
    };
    let domain = sender.domain_part().clone();

    // No validation of `helo_domain`: this input is used only for the `%{h}`
    // macro, and will be considered only when expanding such a macro. We have
    // chosen not to validate eagerly, since an invalid `%{h}` value should not
    // impede SPF evaluation. In practice, the HELO host can be an IP address
    // literal (‘[1.2.3.4]’). There is a tradeoff here, since some clients do
    // want to detect an invalid `helo_domain` (they won’t notice until they
    // find `%{h}` being replaced with `unknown`) – those will have to do the
    // validation on their end.
    let helo_domain = helo_domain.to_owned();

    let mut query = Query::new(
        config,
        QueryParams::new(ip, domain, sender, helo_domain),
        QueryState::new(),
    );

    let resolver = Resolver::new(lookup);

    let result = query.execute(&resolver);

    let cause = query.result_cause;
    let trace = if config.capture_trace() {
        Some(query.trace)
    } else {
        None
    };

    QueryResult {
        result,
        cause,
        trace,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn spf_result_fail_display_empty() {
        let e = ExplanationString::Default(String::new());
        assert_eq!(&SpfResult::Fail(e).to_string(), "fail");
    }

    #[test]
    fn spf_result_fail_display_with_explanation() {
        let e = ExplanationString::Default(String::from("SPF failed"));
        assert_eq!(&SpfResult::Fail(e).to_string(), "fail (SPF failed)");
    }
}