ic-bn-lib 0.2.2

Internet Computer Boundary Nodes shared modules
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
pub mod ehlo;
pub mod mail_from;
pub mod manager;
pub mod rcpt_to;
pub mod session;

use std::{
    fmt::{self, Display},
    io,
    net::IpAddr,
    sync::Arc,
    time::Duration,
};

use anyhow::Context;
use bytes::Bytes;
use fqdn::FQDN;
use hickory_resolver::net::NetError;
use ic_bn_lib_common::types::http::TlsInfo;
use mail_auth::MessageAuthenticator;
use rustls::ServerConfig;
use serde_with::SerializeDisplay;
use smtp_proto::{
    EXT_8BIT_MIME, EXT_CHUNKING, EXT_ENHANCED_STATUS_CODES, EXT_PIPELINING, EXT_SIZE,
    EXT_SMTP_UTF8, EXT_START_TLS, EhloResponse, Error as SmtpError, Request,
    request::receiver::{
        BdatReceiver, DataReceiver, DummyDataReceiver, DummyLineReceiver, RequestReceiver,
    },
};
use strum::{Display, IntoStaticStr};
use tokio::io::AsyncWriteExt;
use tokio_util::time::FutureExt;
use uuid::Uuid;

use crate::{
    network::AsyncReadWrite,
    smtp::{
        DeliversMail, DummyDeliveryAgent, DummyRecipientResolver, EmailMessage, MessageError,
        Metrics, ProtocolError, ReceivesSmtpNotifications, ResolvesRecipient, SessionCounters,
        SessionMeta, address::EmailAddress,
    },
};

pub(crate) const MAX_REPLY_LEN: usize = 256;

/// Error that leads to session termination.
/// The only "expected" error is `Quit` that is caused by the client QUIT
/// command.
#[derive(thiserror::Error, Debug, IntoStaticStr, SerializeDisplay)]
#[strum(serialize_all = "snake_case")]
pub enum SessionError {
    #[error("I/O error: {0}")]
    Io(#[from] io::Error),
    #[error("Fmt error: {0}")]
    Fmt(#[from] fmt::Error),
    #[error("Dns error: {0}")]
    Dns(#[from] NetError),
    #[error("Timed out")]
    Timeout,
    #[error("TLS handshake failed: {0}")]
    TlsHandshakeFailed(String),
    #[error("{0}")]
    SmtpError(#[from] SmtpError),
    #[error("Session terminated by client (QUIT)")]
    Quit,
    #[error("Client is sending before greeting")]
    SendsBeforeGreeting,
    #[error("Too many messages per session")]
    TooManyMessagesPerSession,
    #[error("Session transfer quota ({0} bytes) was exceeded")]
    TransferQuotaExceeded(usize),
    #[error("Session TTL ({0}s) was exceeded")]
    TtlExceeded(u64),
    #[error("Too many errors")]
    TooManyErrors,
    #[error("{0}")]
    Other(#[from] anyhow::Error),
}

/// Indicates if a session needs to be upgraded to TLS
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionUpgrade {
    No,
    StartTls,
}

pub type SessionResult<T> = Result<T, SessionError>;

/// Session TLS mode
#[derive(Clone, Debug)]
pub enum SessionTlsMode {
    Disabled,
    Allowed(Arc<ServerConfig>),
    Required(Arc<ServerConfig>),
}

impl SessionTlsMode {
    pub const fn enabled(&self) -> bool {
        matches!(self, Self::Allowed(_) | Self::Required(_))
    }

    pub const fn required(&self) -> bool {
        matches!(self, Self::Required(_))
    }
}

/// SMTP session config
#[derive(Clone)]
pub struct SessionConfig {
    hostname: String,
    greeting: Bytes,
    helo: Bytes,
    ehlo: Bytes,
    ehlo_tls: Bytes,

    max_message_size: usize,

    pub max_recipients: usize,
    pub max_session_duration: Duration,
    pub max_session_data: usize,
    pub max_errors: usize,
    pub max_messages_per_session: usize,
    pub max_received_headers: usize,

    pub verify_ehlo_hostname: bool,
    pub verify_sender_domain: bool,
    pub verify_reverse_ip: bool,
    pub verify_reverse_ip_strict: bool,
    pub verify_spf: bool,
    pub verify_dkim: bool,
    pub verify_dkim_strict: bool,
    pub greeting_delay: Option<Duration>,

    pub timeout: Duration,
    pub tls_mode: SessionTlsMode,

    pub authenticator: Arc<MessageAuthenticator>,
    pub recipient_resolver: Arc<dyn ResolvesRecipient>,
    pub delivery_agent: Arc<dyn DeliversMail>,
    pub notifications_handler: Option<Arc<dyn ReceivesSmtpNotifications>>,
}

impl SessionConfig {
    pub fn new(hostname: &str, max_message_size: usize) -> Self {
        let greeting = Bytes::from(format!("220 {hostname} ESMTP IC SMTP Gateway\r\n"));
        let helo = Bytes::from(format!("250 {hostname} you had me at HELO\r\n"));
        let (ehlo, ehlo_tls) = Self::generate_ehlo(hostname, max_message_size);

        Self {
            hostname: hostname.into(),
            greeting,
            helo,
            ehlo,
            ehlo_tls,

            max_message_size,
            max_recipients: 5,
            max_session_duration: Duration::from_secs(600),
            max_session_data: 50 * 1024 * 1024,
            max_errors: 5,
            max_messages_per_session: 5,
            max_received_headers: 50,

            verify_ehlo_hostname: false,
            verify_reverse_ip: false,
            verify_reverse_ip_strict: false,
            verify_sender_domain: false,
            verify_spf: false,
            verify_dkim: false,
            verify_dkim_strict: false,

            greeting_delay: None,
            timeout: Duration::from_secs(30),

            tls_mode: SessionTlsMode::Disabled,

            // SAFETY: this never fails
            authenticator: Arc::new(MessageAuthenticator::new_cloudflare().unwrap()),
            recipient_resolver: Arc::new(DummyRecipientResolver),
            delivery_agent: Arc::new(DummyDeliveryAgent),
            notifications_handler: None,
        }
    }

    /// Generates all required HELO/EHLO bodies in advance
    fn generate_ehlo(hostname: &str, max_message_size: usize) -> (Bytes, Bytes) {
        let mut response = EhloResponse::new(hostname);
        response.capabilities = EXT_ENHANCED_STATUS_CODES
            | EXT_8BIT_MIME
            | EXT_SMTP_UTF8
            | EXT_CHUNKING
            | EXT_SIZE
            | EXT_PIPELINING;
        response.size = max_message_size;

        // EHLO w/o STARTTLS
        let mut ehlo = Vec::new();
        response.write(&mut ehlo).ok();

        // EHLO with STARTTLS
        let mut ehlo_tls = Vec::new();
        response.capabilities |= EXT_START_TLS;
        response.write(&mut ehlo_tls).ok();

        (Bytes::from(ehlo), Bytes::from(ehlo_tls))
    }
}

/// SMTP session state
#[derive(Display)]
pub enum SessionState {
    /// Need to send greeting
    Greeting,
    /// Default - command/response
    Request(RequestReceiver),
    /// ASCII data reception
    Data(DataReceiver),
    /// Binary data reception
    Bdat(BdatReceiver),
    /// Too long request received - blackhole
    RequestTooLarge(DummyLineReceiver),
    /// Too large data received - blackhole
    DataTooLarge(DummyDataReceiver),
    /// Dummy
    None,
}

impl Default for SessionState {
    fn default() -> Self {
        Self::Request(RequestReceiver::default())
    }
}

/// SMTP dynamic session data
#[derive(Clone, Debug)]
pub struct SessionData {
    message_id: Uuid,
    last_error: Option<ProtocolError>,
    reverse_ip_verified: bool,
    ehlo_hostname: Option<FQDN>,
    mail_from: Option<EmailAddress>,
    rcpt_to: Vec<EmailAddress>,
    message: Vec<u8>,
}

impl Default for SessionData {
    fn default() -> Self {
        Self {
            #[cfg(not(test))]
            message_id: Uuid::now_v7(),
            #[cfg(test)]
            message_id: Uuid::nil(),
            last_error: None,
            reverse_ip_verified: false,
            ehlo_hostname: None,
            mail_from: None,
            rcpt_to: vec![],
            message: vec![],
        }
    }
}

/// SMTP Session
pub struct Session<S: AsyncReadWrite> {
    id: Uuid,
    remote_ip: IpAddr,
    stream: S,
    state: SessionState,
    data: SessionData,
    counters: SessionCounters,
    cfg: Arc<SessionConfig>,
    tls_info: Option<TlsInfo>,
    labels: [&'static str; 2],
    metrics: Metrics,
}

impl<S: AsyncReadWrite> Display for Session<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "SMTP/Session({}{})",
            self.remote_ip,
            if self.tls_info.is_some() { "/TLS" } else { "" }
        )?;

        if let Some(v) = &self.data.ehlo_hostname {
            write!(f, "({v})")?;
        }

        Ok(())
    }
}

impl<S: AsyncReadWrite> Session<S> {
    pub fn new(remote_ip: IpAddr, stream: S, cfg: Arc<SessionConfig>, metrics: Metrics) -> Self {
        let ip_family = if remote_ip.is_ipv4() { "v4" } else { "v6" };

        Self {
            #[cfg(not(test))]
            id: Uuid::now_v7(),
            #[cfg(test)]
            id: Uuid::nil(),
            remote_ip,
            stream,
            state: SessionState::Greeting,
            data: SessionData::default(),
            counters: SessionCounters::new(),
            cfg,
            tls_info: None,
            labels: [ip_family, ""],
            metrics,
        }
    }

    /// Closes the connection
    pub async fn shutdown(&mut self) -> SessionResult<()> {
        self.stream
            .shutdown()
            .timeout(Duration::from_secs(10))
            .await
            .context("shutdown timed out")?
            .context("shutdown failed")?;

        Ok(())
    }

    fn set_error(&mut self, error: ProtocolError) {
        let error_lbl: &'static str = (&error).into();
        self.metrics
            .protocol_errors
            .with_label_values(&[self.labels[0], self.labels[1], error_lbl])
            .inc();

        self.data.last_error = Some(error.clone());
        self.counters.errors += 1;

        if let Some(v) = self.cfg.notifications_handler.clone() {
            let meta = self.meta();
            tokio::spawn(async move { v.notify_protocol_error(meta, error).await });
        }
    }

    fn notify_message(
        &self,
        msg: Arc<EmailMessage>,
        error: Option<MessageError>,
        latency: Duration,
    ) {
        self.metrics
            .message_size
            .with_label_values(&self.labels)
            .observe(msg.body.len() as f64);

        let error_lbl: &'static str = error.as_ref().map_or("", |x| x.into());
        self.metrics
            .messages
            .with_label_values(&[self.labels[0], self.labels[1], error_lbl])
            .inc();

        if let Some(v) = self.cfg.notifications_handler.clone() {
            let meta = self.meta();
            tokio::spawn(async move {
                v.notify_message(meta, msg, latency, error).await;
            });
        };
    }

    fn meta(&self) -> SessionMeta {
        SessionMeta {
            id: self.id,
            message_id: self.data.message_id,
            remote_ip: self.remote_ip,
            tls_info: self.tls_info.clone(),
            counters: self.counters.clone(),
            last_error: self.data.last_error.clone(),
            ehlo_hostname: self.data.ehlo_hostname.clone(),
            mail_from: self.data.mail_from.clone(),
            rcpt_to: self.data.rcpt_to.clone(),
        }
    }
}

/// Hand-made implementation of IntoStaticStr for an SMTP request
const fn request_str<T>(req: &Request<T>) -> &'static str {
    match req {
        Request::Bdat { .. } => "BDAT",
        Request::Data => "DATA",
        Request::Ehlo { .. } => "EHLO",
        Request::Helo { .. } => "HELO",
        Request::Help { .. } => "HELP",
        Request::Mail { .. } => "MAIL",
        Request::Rcpt { .. } => "RCPT",
        Request::Noop { .. } => "NOOP",
        Request::Quit => "QUIT",
        Request::Rset => "RSET",
        Request::StartTls => "STARTTLS",
        Request::Atrn { .. } => "ATRN",
        Request::Auth { .. } => "AUTH",
        Request::Burl { .. } => "BURL",
        Request::Etrn { .. } => "ETRN",
        Request::Expn { .. } => "EXPN",
        Request::Lhlo { .. } => "LHLO",
        Request::Vrfy { .. } => "VRFY",
    }
}

#[cfg(test)]
mod tests;