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
//! The enrichment module exposes functionality to enrich
//! a given domain with interesting metadata. Currently
//! including:
//!
//! * DNS resolution (through HTTP/80 lookup).
//! * Open SMTP server (for email misdirects).
//!
//! Example:
//!
//! ```
//! use twistrs::enrich::DomainMetadata;
//!
//! #[tokio::main]
//! async fn main() {
//!     let domain_metadata = DomainMetadata::new(String::from("google.com"));
//!     domain_metadata.dns_resolvable().await;
//! }
//! ```
//!
//! Note that the enrichment module is independent from the
//! permutation module and can be used with any given FQDN.
use serde::Serialize;
use std::net::IpAddr;

#[cfg(feature = "geoip_lookup")]
use maxminddb;
#[cfg(feature = "geoip_lookup")]
use maxminddb::geoip2;

#[cfg(feature = "whois_lookup")]
use whois_rust::WhoIsLookupOptions;

#[cfg(feature = "smtp_lookup")]
use async_smtp::{Envelope, SendableEmail, SmtpClient, SmtpTransport};

#[cfg(feature = "smtp_lookup")]
use tokio::{io::BufStream, net::TcpStream};

use hyper::{Body, Request};
use tokio::net;

use crate::constants::HTTP_CLIENT;
use crate::error::Error;

#[cfg(feature = "whois_lookup")]
use crate::constants::WHOIS;

#[derive(thiserror::Error, Debug)]
pub enum EnrichmentError {
    #[error("error resolving domain name (domain: {domain})")]
    DnsResolutionError { domain: String },

    #[cfg(feature = "whois_lookup")]
    #[error("error resolving domain name (domain: {domain}, error: {error})")]
    WhoIsLookupError {
        domain: String,
        error: whois_rust::WhoIsError,
    },

    #[cfg(feature = "smtp_lookup")]
    #[error("error performing smtp lookup (domain: {domain}, error: {error})")]
    SmtpLookupError {
        domain: String,
        error: anyhow::Error,
    },

    #[error("error performing http banner lookup (domain: {domain}, error: {error})")]
    HttpBannerError {
        domain: String,
        error: anyhow::Error,
    },

    #[error("error performing geoip lookup (domain: {domain}, error: {error})")]
    GeoIpLookupError {
        domain: String,
        error: anyhow::Error,
    },
}

/// Container to store interesting FQDN metadata
/// on domains that we resolve.
///
/// Whenever any domain enrichment occurs, the
/// following struct is return to indicate the
/// information that was derived.
///
/// **N.B**—there will be cases where a single
/// domain can have multiple `DomainMetadata`
/// instancees associated with it.
#[derive(Debug, Clone, Serialize, Default)]
pub struct DomainMetadata {
    /// The domain that is being enriched.
    pub fqdn: String,

    /// Any IPv4 and IPv6 ips that were discovered during
    /// domain resolution.
    pub ips: Option<Vec<IpAddr>>,

    /// Any SMTP message data (if any) that was returned by
    /// an SMTP server.
    pub smtp: Option<SmtpMetadata>,

    /// HTTP server banner data extracted.
    pub http_banner: Option<String>,

    /// IP addresses resolved through GeoIP lookup to City, Country, Continent.
    pub geo_ip_lookups: Option<Vec<(IpAddr, String)>>,

    /// Block of text returned by the WhoIs registrar.
    pub who_is_lookup: Option<String>,
}

/// SMTP specific metadata generated by a partic
/// ular domain.
#[derive(Debug, Clone, Serialize)]
pub struct SmtpMetadata {
    /// Whether the email was dispatched successfully
    pub is_positive: bool,

    /// Message received back from the SMTP server
    pub message: String,
}

impl DomainMetadata {
    /// Create a new empty state for a particular FQDN.
    pub fn new(fqdn: String) -> DomainMetadata {
        DomainMetadata {
            fqdn,
            ..Default::default()
        }
    }

    /// Asynchronous DNS resolution on a `DomainMetadata` instance.
    ///
    /// Returns `Ok(DomainMetadata)` is the domain was resolved,
    /// otherwise returns `Err(EnrichmentError)`.
    ///
    /// **N.B**—also host lookups are done over port 80.
    pub async fn dns_resolvable(&self) -> Result<DomainMetadata, Error> {
        Ok(net::lookup_host(&format!("{}:80", self.fqdn)[..])
            .await
            .map(|addrs| DomainMetadata {
                fqdn: self.fqdn.clone(),
                ips: Some(addrs.map(|addr| addr.ip()).collect()),
                smtp: None,
                http_banner: None,
                geo_ip_lookups: None,
                who_is_lookup: None,
            })
            .map_err(|_| EnrichmentError::DnsResolutionError {
                domain: self.fqdn.clone(),
            })?)
    }

    /// Asynchronous SMTP check. Attempts to establish an SMTP
    /// connection to the FQDN on port 25 and send a pre-defi
    /// ned email.
    ///
    /// Currently returns `Ok(DomainMetadata)` always, which
    /// internally contains `Option<SmtpMetadata>`. To check
    /// if the SMTP relay worked, check that
    /// `DomainMetadata.smtp` is `Some(v)`.
    #[cfg(feature = "smtp_lookup")]
    pub async fn mx_check(&self) -> Result<DomainMetadata, Error> {
        let email = SendableEmail::new(
            Envelope::new(
                Some("twistrs@example.com".parse().unwrap()),
                vec!["twistrs@example.com".parse().unwrap()],
            )
            .map_err(|e| EnrichmentError::SmtpLookupError {
                domain: self.fqdn.clone(),
                error: anyhow::Error::msg(e),
            })?,
            "And that's how the cookie crumbles\n",
        );

        let stream = BufStream::new(
            TcpStream::connect(&format!("{}:25", self.fqdn))
                .await
                .map_err(|e| EnrichmentError::SmtpLookupError {
                    domain: self.fqdn.clone(),
                    error: anyhow::Error::msg(e),
                })?,
        );
        let client = SmtpClient::new();
        let mut transport = SmtpTransport::new(client, stream).await.map_err(|e| {
            EnrichmentError::SmtpLookupError {
                domain: self.fqdn.clone(),
                error: anyhow::Error::msg(e),
            }
        })?;

        let result = transport.send(email).await.map(|response| DomainMetadata {
            fqdn: self.fqdn.clone(),
            ips: None,
            smtp: Some(SmtpMetadata {
                is_positive: response.is_positive(),
                message: response.message.into_iter().collect::<String>(),
            }),
            http_banner: None,
            geo_ip_lookups: None,
            who_is_lookup: None,
        });

        Ok(match result {
            Ok(domain_metadata) => Ok(domain_metadata),
            Err(async_smtp::error::Error::Timeout(_)) => Ok(DomainMetadata::new(self.fqdn.clone())),
            Err(e) => Err(EnrichmentError::SmtpLookupError {
                domain: self.fqdn.clone(),
                error: anyhow::Error::msg(e),
            }),
        }?)
    }

    /// Asynchronous HTTP Banner fetch. Searches and parses `server` header
    /// from an HTTP request to gather the HTTP banner.
    ///
    /// Note that a `HEAD` request is issued to minimise bandwidth. Also note
    /// that the internal [`HttpConnector`](https://docs.rs/hyper/0.13.8/hyper/client/struct.HttpConnector.html)
    /// sets the response buffer window to 1024 bytes, the CONNECT timeout to
    /// 5s and enforces HTTP scheme.
    ///
    /// ```
    /// use twistrs::enrich::DomainMetadata;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let domain_metadata = DomainMetadata::new(String::from("www.phishdeck.com"));
    ///     println!("{:?}", domain_metadata.http_banner().await);
    /// }
    /// ```
    pub async fn http_banner(&self) -> Result<DomainMetadata, Error> {
        // Construst the basic request to be sent out
        let request = Request::builder()
            .method("HEAD")
            .uri(format!("http://{}", &self.fqdn))
            .header("User-Agent", "github-juxhindb-twistrs-http-banner/1.0")
            .body(Body::from("")) // This is annoying
            .map_err(|e| EnrichmentError::HttpBannerError {
                domain: self.fqdn.clone(),
                error: anyhow::Error::msg(e),
            })?;

        if let Ok(response) = HTTP_CLIENT.request(request).await {
            if let Some(server_header) = response.headers().get("server") {
                let server =
                    server_header
                        .to_str()
                        .map_err(|e| EnrichmentError::HttpBannerError {
                            domain: self.fqdn.clone(),
                            error: anyhow::Error::msg(e),
                        })?;

                return Ok(DomainMetadata {
                    fqdn: self.fqdn.clone(),
                    ips: None,
                    smtp: None,
                    http_banner: Some(String::from(server)),
                    geo_ip_lookups: None,
                    who_is_lookup: None,
                });
            }
        }

        Err(EnrichmentError::HttpBannerError {
            domain: self.fqdn.clone(),
            error: anyhow::Error::msg("unable to extract or parse server header from response"),
        }
        .into())
    }

    /// Asynchronous cached `GeoIP` lookup. Interface deviates from the usual enrichment
    /// interfaces and requires the callee to pass a [`maxminddb::Reader`](https://docs.rs/maxminddb/0.15.0/maxminddb/struct.Reader.html)
    /// to perform the lookup through. Internally, the maxminddb call is blocking and
    /// may result in performance drops, however the lookups are in-memory.
    ///
    /// The only reason you would want to do this, is to be able to get back a `DomainMetadata`
    /// to then process as you would with other enrichment methods. Internally the lookup will
    /// try to stitch together the City, Country & Continent that the [`IpAddr`](https://doc.rust-lang.org/std/net/enum.IpAddr.html)
    /// resolves to.
    ///
    /// ```
    /// use maxminddb::Reader;
    /// use twistrs::enrich::DomainMetadata;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let reader = maxminddb::Reader::open_readfile("./data/MaxMind-DB/test-data/GeoIP2-City-Test.mmdb").unwrap();
    ///     let domain_metadata = DomainMetadata::new(String::from("www.phishdeck.com"));
    ///     println!("{:?}", domain_metadata.geoip_lookup(&reader).await);
    /// }
    /// ```
    ///
    /// ### Features
    ///
    /// This function requires the `geoip_lookup` feature toggled.
    #[cfg(feature = "geoip_lookup")]
    pub async fn geoip_lookup(
        &self,
        geoip: &maxminddb::Reader<Vec<u8>>,
    ) -> Result<DomainMetadata, Error> {
        let mut result: Vec<(IpAddr, String)> = Vec::new();

        match &self.ips {
            Some(ips) => {
                for ip in ips {
                    if let Ok(lookup_result) = geoip.lookup::<geoip2::City>(*ip) {
                        let mut geoip_string = String::new();

                        if lookup_result.city.is_some() {
                            geoip_string.push_str(
                                lookup_result
                                    .city
                                    .ok_or(EnrichmentError::GeoIpLookupError {
                                        domain: self.fqdn.clone(),
                                        error: anyhow::Error::msg("could not find city"),
                                    })?
                                    .names
                                    .ok_or(EnrichmentError::GeoIpLookupError {
                                        domain: self.fqdn.clone(),
                                        error: anyhow::Error::msg("could not find city names"),
                                    })?["en"],
                            );
                        }

                        if lookup_result.country.is_some() {
                            if !geoip_string.is_empty() {
                                geoip_string.push_str(", ");
                            }

                            geoip_string.push_str(
                                lookup_result
                                    .country
                                    .ok_or(EnrichmentError::GeoIpLookupError {
                                        domain: self.fqdn.clone(),
                                        error: anyhow::Error::msg("could not find country"),
                                    })?
                                    .names
                                    .ok_or(EnrichmentError::GeoIpLookupError {
                                        domain: self.fqdn.clone(),
                                        error: anyhow::Error::msg("could not find country names"),
                                    })?["en"],
                            );
                        }

                        if lookup_result.continent.is_some() {
                            if !geoip_string.is_empty() {
                                geoip_string.push_str(", ");
                            }

                            geoip_string.push_str(
                                lookup_result
                                    .continent
                                    .ok_or(EnrichmentError::GeoIpLookupError {
                                        domain: self.fqdn.clone(),
                                        error: anyhow::Error::msg("could not find continent"),
                                    })?
                                    .names
                                    .ok_or(EnrichmentError::GeoIpLookupError {
                                        domain: self.fqdn.clone(),
                                        error: anyhow::Error::msg("could not find continent name"),
                                    })?["en"],
                            );
                        }

                        result.push((*ip, geoip_string));
                    }
                }

                Ok(DomainMetadata {
                    fqdn: self.fqdn.clone(),
                    ips: None,
                    smtp: None,
                    http_banner: None,
                    geo_ip_lookups: Some(result),
                    who_is_lookup: None,
                })
            }
            None => Ok(DomainMetadata::new(self.fqdn.clone())),
        }
    }

    /// Asyncrhonous `WhoIs` lookup using cached `WhoIs` server config. Note that
    /// the internal lookups are not async and so this should be considered
    /// a heavy/slow call.
    ///
    /// ```
    /// use twistrs::enrich::DomainMetadata;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let domain_metadata = DomainMetadata::new(String::from("www.phishdeck.com"));
    ///     println!("{:?}", domain_metadata.whois_lookup().await);
    /// }
    /// ```
    ///
    /// ### Features
    ///
    /// This function requires the `whois_lookup` feature toggled.
    #[cfg(feature = "whois_lookup")]
    pub async fn whois_lookup(&self) -> Result<DomainMetadata, Error> {
        let mut result = DomainMetadata::new(self.fqdn.clone());

        let mut whois_lookup_options =
            WhoIsLookupOptions::from_string(&self.fqdn).map_err(|e| {
                EnrichmentError::WhoIsLookupError {
                    domain: self.fqdn.to_string(),
                    error: e,
                }
            })?;

        whois_lookup_options.timeout = Some(std::time::Duration::from_secs(5));
        whois_lookup_options.follow = 1; // Only allow at most one redirect

        result.who_is_lookup = Some(
            WHOIS
                .lookup(whois_lookup_options)
                .map_err(|e| EnrichmentError::WhoIsLookupError {
                    domain: self.fqdn.to_string(),
                    error: e,
                })?
                .split("\r\n")
                // The only entries we care about are the ones that start with 3 spaces.
                // Ideally the whois_rust library would have parsed this nicely for us.
                .filter(|s| s.starts_with("   "))
                .collect::<Vec<&str>>()
                .join("\n"),
        );

        Ok(result)
    }

    /// Performs all FQDN enrichment methods on a given FQDN.
    /// This is the only function that returns a `Vec<DomainMetadata>`.
    ///
    /// # Panics
    ///
    /// Currently panics if any of the internal enrichment methods returns
    /// an Err.
    pub async fn all(&self) -> Result<Vec<DomainMetadata>, Error> {
        // @CLEANUP(JDB): This should use try_join! in the future instead
        #[cfg(feature = "smtp_lookup")]
        let mx_check = self.mx_check();

        let result = futures::join!(self.dns_resolvable(), self.http_banner());

        Ok(vec![
            result.0.unwrap(),
            #[cfg(feature = "smtp_lookup")]
            mx_check.await.unwrap(),
            result.1.unwrap(),
        ])
    }
}

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

    #[cfg(feature = "geoip_lookup")]
    use maxminddb;

    use futures::executor::block_on;

    #[tokio::test]
    async fn test_dns_lookup() {
        let domain_metadata = DomainMetadata::new(String::from("example.com"));
        assert!(block_on(domain_metadata.dns_resolvable()).is_ok());
    }

    #[tokio::test]
    #[cfg(feature = "geoip_lookup")]
    async fn test_geoip_lookup() {
        let domain_metadata = DomainMetadata::new(String::from("example.com"))
            .dns_resolvable()
            .await
            .unwrap();

        // MaxmindDB CSV entry for example.com subnet, prone to failure but saves space
        let reader =
            maxminddb::Reader::open_readfile("./data/MaxMind-DB/test-data/GeoIP2-City-Test.mmdb")
                .unwrap();

        assert!(domain_metadata.geoip_lookup(&reader).await.is_ok());
    }

    #[tokio::test]
    #[cfg(feature = "whois_lookup")]
    async fn test_whois_lookup() {
        let domain_metadata = DomainMetadata::new(String::from("example.com"));
        assert!(domain_metadata.whois_lookup().await.is_ok());
    }
}