vsmtp-server 2.2.1

Next-gen MTA. Secured, Faster and Greener
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
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
/*
 * vSMTP mail transfer agent
 * Copyright (C) 2022 viridIT SAS
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see https://www.gnu.org/licenses/.
 *
*/

use crate::Handler;
use tokio_rustls::rustls;
use vsmtp_common::{
    auth::{Credentials, Mechanism},
    status::Status,
    ClientName, Reply,
};
use vsmtp_mail_parser::MailParser;
use vsmtp_protocol::{
    AcceptArgs, AuthArgs, AuthError, CallbackWrap, ConnectionKind, EhloArgs, HeloArgs,
    ReceiverContext,
};
use vsmtp_rule_engine::{ExecutionStage, RuleEngine, RuleState};

impl<Parser, ParserFactory> Handler<Parser, ParserFactory>
where
    Parser: MailParser + Send + Sync,
    ParserFactory: Fn() -> Parser + Send + Sync,
{
    pub(super) fn on_accept_inner(
        &mut self,
        ctx: &mut ReceiverContext,
        args: &AcceptArgs,
    ) -> Reply {
        if self
            .rule_engine
            .get_delegation_directive_bound_to_address(args.server_addr)
            .is_some()
        {
            self.state
                .context()
                .write()
                .expect("bad state")
                .set_skipped(Status::DelegationResult);
            self.skipped = Some(Status::DelegationResult);
        }

        let reply =
            match self
                .rule_engine
                .run_when(&self.state, &mut self.skipped, ExecutionStage::Connect)
            {
                // FIXME: do we really want to let the end-user override the EHLO/HELO reply?
                Status::Faccept(reply) | Status::Accept(reply) => reply,
                Status::Quarantine(_) | Status::Next | Status::DelegationResult => {
                    format!("220 {} Service ready\r\n", self.config.server.name)
                        .parse::<Reply>()
                        .unwrap()
                }
                Status::Deny(reply) => {
                    ctx.deny();
                    return reply;
                }
                // FIXME: user ran a delegate method before postq/delivery
                Status::Delegated(_) => unreachable!(),
            };

        // NOTE: in that case, the return value is ignored and
        // we have to manually trigger the TLS handshake,
        if args.kind == ConnectionKind::Tunneled
            && !self
                .state
                .context()
                .read()
                .expect("state poisoned")
                .is_secured()
        {
            match &self.rustls_config {
                Some(config) => ctx.upgrade_tls(config.clone(), std::time::Duration::from_secs(2)),
                None => ctx.deny(),
            }
            return "100 ignored value\r\n".parse().unwrap();
        }

        reply
    }

    pub(super) fn generate_sasl_callback_inner(&self) -> CallbackWrap {
        CallbackWrap(Box::new(RsaslSessionCallback {
            rule_engine: self.rule_engine.clone(),
            state: self.state.clone(),
        }))
    }

    pub(super) fn on_post_tls_handshake_inner(
        &mut self,
        sni: Option<String>,
        protocol_version: rustls::ProtocolVersion,
        cipher_suite: rustls::CipherSuite,
        peer_certificates: Option<Vec<rustls::Certificate>>,
        alpn_protocol: Option<Vec<u8>>,
    ) -> Reply {
        let server_name = sni.map(|sni| sni.parse().unwrap());

        self.state
            .context()
            .write()
            .expect("state poisoned")
            .to_secured(
                server_name.clone(),
                protocol_version,
                cipher_suite,
                peer_certificates,
                alpn_protocol,
            )
            .expect("bad state");

        format!(
            "220 {} Service ready\r\n",
            server_name.unwrap_or_else(|| self.config.server.name.clone())
        )
        .parse::<Reply>()
        .unwrap()
    }

    pub(super) fn on_starttls_inner(&mut self, ctx: &mut ReceiverContext) -> Reply {
        if self
            .state
            .context()
            .read()
            .expect("state poisoned")
            .is_secured()
        {
            "554 5.5.1 Error: TLS already active\r\n"
                .parse::<Reply>()
                .unwrap()
        } else {
            self.rustls_config.as_ref().map_or(
                "454 TLS not available due to temporary reason\r\n"
                    .parse::<Reply>()
                    .unwrap(),
                |config| {
                    ctx.upgrade_tls(config.clone(), std::time::Duration::from_secs(2));
                    "220 TLS go ahead\r\n".parse::<Reply>().unwrap()
                },
            )
        }
    }

    pub(super) fn on_auth_inner(
        &mut self,
        ctx: &mut ReceiverContext,
        args: AuthArgs,
    ) -> Option<Reply> {
        if let Some(auth) = &self.config.server.smtp.auth {
            if !self
                .state
                .context()
                .read()
                .expect("state poisoned")
                .is_secured()
                && args.mechanism.must_be_under_tls()
                && !auth.enable_dangerous_mechanism_in_clair
            {
                return Some(
                    "538 5.7.11 Encryption required for requested authentication mechanism\r\n"
                        .parse::<Reply>()
                        .unwrap(),
                );
            }

            ctx.authenticate(args.mechanism, args.initial_response);

            None
        } else {
            Some("502 Command not implemented\r\n".parse::<Reply>().unwrap())
        }
    }

    pub(super) fn on_post_auth_inner(
        &mut self,
        ctx: &mut ReceiverContext,
        result: Result<(), AuthError>,
    ) -> Reply {
        match result {
            Ok(()) => {
                self.state
                    .context()
                    .write()
                    .expect("state poisoned")
                    .auth_mut()
                    .expect("bad state")
                    .authenticated = true;

                "235 2.7.0 Authentication succeeded\r\n"
                    .parse::<Reply>()
                    .unwrap()
            }
            Err(AuthError::ClientMustNotStart) => {
                "501 5.7.0 Client must not start with this mechanism\r\n"
                    .parse::<Reply>()
                    .unwrap()
            }
            Err(AuthError::ValidationError(..)) => {
                ctx.deny();
                "535 5.7.8 Authentication credentials invalid\r\n"
                    .parse::<Reply>()
                    .unwrap()
            }
            Err(AuthError::Canceled) => {
                let state = self.state.context();
                let mut guard = state.write().expect("state poisoned");
                let auth_properties = guard.to_auth().expect("bad state");

                auth_properties.cancel_count += 1;
                let attempt_count_max = self
                    .config
                    .server
                    .smtp
                    .auth
                    .as_ref()
                    .map_or(-1, |auth| auth.attempt_count_max);

                if attempt_count_max != -1
                    && auth_properties.cancel_count >= attempt_count_max.try_into().unwrap()
                {
                    ctx.deny();
                }

                "501 Authentication canceled by client\r\n"
                    .parse::<Reply>()
                    .unwrap()
            }
            Err(AuthError::Base64 { .. }) => "501 5.5.2 Invalid, not base64\r\n"
                .parse::<Reply>()
                .unwrap(),
            Err(AuthError::SessionError(e)) => {
                tracing::warn!(%e, "auth error");
                ctx.deny();
                "454 4.7.0 Temporary authentication failure\r\n"
                    .parse::<Reply>()
                    .unwrap()
            }
            Err(AuthError::IO(e)) => todo!("{e}"),
            Err(AuthError::ConfigError(rsasl::prelude::SASLError::NoSharedMechanism)) => {
                ctx.deny();
                "504 5.5.4 Mechanism is not supported\r\n"
                    .parse::<Reply>()
                    .unwrap()
            }
            Err(AuthError::ConfigError(e)) => todo!("handle non_exhaustive pattern: {e}"),
        }
    }

    pub(super) fn on_helo_inner(&mut self, ctx: &mut ReceiverContext, args: HeloArgs) -> Reply {
        self.state
            .context()
            .write()
            .expect("state poisoned")
            .to_helo(ClientName::Domain(args.client_name), true)
            .expect("bad state");

        match self
            .rule_engine
            .run_when(&self.state, &mut self.skipped, ExecutionStage::Helo)
        {
            Status::Faccept(reply) | Status::Accept(reply) => reply,
            Status::Quarantine(_) | Status::Next | Status::DelegationResult => {
                "250 Ok\r\n".parse::<Reply>().unwrap()
            }
            Status::Deny(code) => {
                ctx.deny();
                code
            }
            // FIXME: user ran a delegate method before postq/delivery
            Status::Delegated(_) => unreachable!(),
        }
    }

    pub(super) fn on_ehlo_inner(&mut self, ctx: &mut ReceiverContext, args: EhloArgs) -> Reply {
        let vsl_ctx = self.state.context();

        vsl_ctx
            .write()
            .expect("state poisoned")
            .to_helo(args.client_name, false)
            .expect("bad state");

        match self
            .rule_engine
            .run_when(&self.state, &mut self.skipped, ExecutionStage::Helo)
        {
            Status::Faccept(reply) | Status::Accept(reply) => reply,
            Status::Quarantine(_) | Status::Next | Status::DelegationResult => {
                let ctx = vsl_ctx.read().expect("state poisoned");

                let auth_mechanism_list: Option<(Vec<Mechanism>, Vec<Mechanism>)> = self
                    .config
                    .server
                    .smtp
                    .auth
                    .as_ref()
                    .map(|auth| auth.mechanisms.iter().partition(|m| m.must_be_under_tls()));

                if ctx.is_secured() {
                    [
                        Some(format!("250-{}\r\n", ctx.server_name())),
                        auth_mechanism_list.as_ref().map(|(must_be_secured, _)| {
                            format!(
                                "250-AUTH {}\r\n",
                                must_be_secured
                                    .iter()
                                    .map(ToString::to_string)
                                    .collect::<Vec<_>>()
                                    .join(" ")
                            )
                        }),
                        Some("250-8BITMIME\r\n".to_string()),
                        Some("250 SMTPUTF8\r\n".to_string()),
                    ]
                    .into_iter()
                    .flatten()
                    .collect::<String>()
                    .parse::<Reply>()
                    .unwrap()
                } else {
                    [
                        Some(format!("250-{}\r\n", &ctx.server_name())),
                        auth_mechanism_list.as_ref().map(|(plain, secured)| {
                            if self
                                .config
                                .server
                                .smtp
                                .auth
                                .as_ref()
                                .map_or(false, |auth| auth.enable_dangerous_mechanism_in_clair)
                            {
                                format!(
                                    "250-AUTH {}\r\n",
                                    &[secured.clone(), plain.clone()]
                                        .concat()
                                        .iter()
                                        .map(ToString::to_string)
                                        .collect::<Vec<_>>()
                                        .join(" ")
                                )
                            } else {
                                format!(
                                    "250-AUTH {}\r\n",
                                    secured
                                        .iter()
                                        .map(ToString::to_string)
                                        .collect::<Vec<_>>()
                                        .join(" ")
                                )
                            }
                        }),
                        Some("250-STARTTLS\r\n".to_string()),
                        Some("250-8BITMIME\r\n".to_string()),
                        Some("250 SMTPUTF8\r\n".to_string()),
                    ]
                    .into_iter()
                    .flatten()
                    .collect::<String>()
                    .parse::<Reply>()
                    .unwrap()
                }
            }
            Status::Deny(code) => {
                ctx.deny();
                code
            }
            // FIXME: user ran a delegate method before postq/delivery
            Status::Delegated(_) => unreachable!(),
        }
    }
}

///
pub struct ValidationVSL;

impl rsasl::validate::Validation for ValidationVSL {
    type Value = ();
}

#[derive(Debug, thiserror::Error)]
pub enum ValidationError {
    #[error(
        "the rules at stage '{}' returned non '{}' status",
        ExecutionStage::Authenticate,
        Status::Accept("250 Ok\r\n".parse::<Reply>().unwrap()).as_ref()
    )]
    NonAcceptCode,
}

struct RsaslSessionCallback {
    rule_engine: std::sync::Arc<RuleEngine>,
    state: std::sync::Arc<RuleState>,
}

impl RsaslSessionCallback {
    #[allow(clippy::unnecessary_wraps)]
    fn inner_validate(
        &self,
        credentials: Credentials,
    ) -> Result<<ValidationVSL as rsasl::validate::Validation>::Value, ValidationError> {
        self.state
            .context()
            .write()
            .expect("state poisoned")
            .with_credentials(credentials)
            .expect("bad state");

        let mut skipped = None;
        let result =
            self.rule_engine
                .run_when(&self.state, &mut skipped, ExecutionStage::Authenticate);

        if !matches!(result, Status::Accept(..)) {
            return Err(ValidationError::NonAcceptCode);
        }

        Ok(())
    }
}

impl rsasl::callback::SessionCallback for RsaslSessionCallback {
    fn callback(
        &self,
        session_data: &rsasl::callback::SessionData,
        context: &rsasl::callback::Context<'_>,
        request: &mut rsasl::callback::Request<'_>,
    ) -> Result<(), rsasl::prelude::SessionError> {
        let _ = (session_data, context, request);
        Ok(())
    }

    fn validate(
        &self,
        session_data: &rsasl::callback::SessionData,
        context: &rsasl::callback::Context<'_>,
        validate: &mut rsasl::validate::Validate<'_>,
    ) -> Result<(), rsasl::validate::ValidationError> {
        let credentials = Credentials::try_from((session_data, context)).map_err(|e| match e {
            vsmtp_common::auth::Error::MissingField => {
                rsasl::validate::ValidationError::MissingRequiredProperty
            }
            otherwise => rsasl::validate::ValidationError::Boxed(Box::new(otherwise)),
        })?;

        validate.with::<ValidationVSL, _>(|| {
            self.inner_validate(credentials)
                .map_err(|e| rsasl::validate::ValidationError::Boxed(Box::new(e)))
        })?;

        Ok(())
    }
}