crymap 2.0.1

A simple, secure IMAP server with encrypted data at rest
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
//-
// Copyright (c) 2020, 2023, 2024, Jason Lingle
//
// This file is part of Crymap.
//
// Crymap 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 (at  your option) any later
// version.
//
// Crymap 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
// Crymap. If not, see <http://www.gnu.org/licenses/>.

use std::cell::RefCell;
use std::net::IpAddr;
use std::os::unix::io::RawFd;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

use log::{error, info, warn};
use nix::sys::time::TimeValLike;
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};

use crate::{
    imap::command_processor::CommandProcessor,
    support::{
        async_io::ServerIo, dns, log_prefix::LogPrefix,
        system_config::SystemConfig, unix_privileges,
    },
};

const STDIN: RawFd = 0;
const STDOUT: RawFd = 1;

// Need to use a this and not die! so that errors go to syslog/etc
macro_rules! fatal {
    ($ex:ident, $($stuff:tt)*) => {{
        error!($($stuff)*);
        crate::support::sysexits::$ex.exit()
    }}
}

#[tokio::main(flavor = "current_thread")]
pub async fn imaps(
    system_config: SystemConfig,
    system_root: PathBuf,
    mut users_root: PathBuf,
) {
    let system_config = Arc::new(system_config);

    let acceptor = create_ssl_acceptor(&system_config, &system_root);
    let dns_resolver =
        match hickory_resolver::AsyncResolver::tokio_from_system_conf() {
            Ok(r) => Some(Rc::new(r)),
            Err(e) => {
                error!("Failed to initialise DNS resolver: {e}");
                None
            },
        };

    // We've opened access to everything on the main system we need; now we can
    // apply chroot and privilege deescalation.
    let (log_prefix, _) =
        configure_system("imaps", &system_config, &mut users_root);

    let io = ServerIo::new_stdio().unwrap_or_else(|e| {
        fatal!(
            EX_OSERR,
            "{} Unable to put input/output into non-blocking mode: {}",
            log_prefix,
            e
        )
    });

    match tokio::time::timeout(
        Duration::from_secs(30),
        io.ssl_accept(&acceptor),
    )
    .await
    {
        Ok(Ok(())) => {},
        Ok(Err(e)) => {
            warn!("{} SSL handshake failed: {}", log_prefix, e);
            std::process::exit(0)
        },
        Err(_timeout) => {
            warn!("{} SSL handshake timed out", log_prefix);
            std::process::exit(0)
        },
    }

    // Get the key material out of memory.
    drop(acceptor);

    info!("{} SSL handshake succeeded", log_prefix);

    let processor = CommandProcessor::new(
        log_prefix.clone(),
        system_config,
        users_root,
        dns_resolver,
    );
    let local_set = tokio::task::LocalSet::new();
    local_set
        .run_until(crate::imap::server::run(io, processor))
        .await;
}

#[tokio::main(flavor = "current_thread")]
pub async fn lmtp(
    system_config: SystemConfig,
    system_root: PathBuf,
    mut users_root: PathBuf,
) {
    let host_name = smtp_host_name(&system_config);
    let ssl_acceptor = create_ssl_acceptor(&system_config, &system_root);

    // We've opened access to everything on the main system we need; now we can
    // apply chroot and privilege deescalation.
    let (log_prefix, peer_name) =
        configure_system("lmtp", &system_config, &mut users_root);

    let io = ServerIo::new_stdio().unwrap_or_else(|e| {
        fatal!(
            EX_OSERR,
            "Failed to put stdio into non-blocking mode: {e:?}",
        )
    });

    let result = crate::smtp::inbound::serve_lmtp(
        io,
        Arc::new(system_config),
        log_prefix.clone(),
        ssl_acceptor,
        users_root,
        host_name,
        peer_name,
    )
    .await;

    match result {
        Ok(()) => info!("{} Normal client disconnect", log_prefix),
        Err(e) => warn!("{} Abnormal client disconnect: {}", log_prefix, e),
    }
}

#[tokio::main(flavor = "current_thread")]
pub async fn smtpin(
    system_config: SystemConfig,
    system_root: PathBuf,
    mut users_root: PathBuf,
) {
    let host_name = smtp_host_name(&system_config);
    let ssl_acceptor = create_ssl_acceptor(&system_config, &system_root);

    // We've opened access to everything on the main system we need; now we can
    // apply chroot and privilege deescalation.
    let (log_prefix, _peer_name) =
        configure_system("smtpin", &system_config, &mut users_root);

    let peer_ip = if let Ok(addr) =
        nix::sys::socket::getpeername::<nix::sys::socket::SockaddrIn>(STDIN)
    {
        IpAddr::V4(*std::net::SocketAddrV4::from(addr).ip())
    } else if let Ok(addr) =
        nix::sys::socket::getpeername::<nix::sys::socket::SockaddrIn6>(STDIN)
    {
        let addr = *std::net::SocketAddrV6::from(addr).ip();
        if let Some(v4) = addr.to_ipv4_mapped() {
            IpAddr::V4(v4)
        } else {
            IpAddr::V6(addr)
        }
    } else {
        fatal!(EX_OSERR, "stdin does not seem to be a TCP connection");
    };

    let resolver =
        match hickory_resolver::AsyncResolver::tokio_from_system_conf() {
            Ok(r) => r,
            Err(e) => {
                fatal!(EX_OSERR, "Failed to initialise DNS resolver: {e}")
            },
        };

    let io = ServerIo::new_stdio().unwrap_or_else(|e| {
        fatal!(
            EX_OSERR,
            "Failed to put stdio into non-blocking mode: {e:?}",
        )
    });

    let local_set = tokio::task::LocalSet::new();
    let result = local_set
        .run_until(crate::smtp::inbound::serve_smtpin(
            io,
            Some(Rc::new(resolver)),
            Rc::new(RefCell::new(dns::Cache::default())),
            Arc::new(system_config),
            log_prefix.clone(),
            ssl_acceptor,
            users_root,
            host_name,
            peer_ip,
        ))
        .await;

    match result {
        Ok(()) => info!("{} Normal client disconnect", log_prefix),
        Err(e) => warn!("{} Abnormal client disconnect: {}", log_prefix, e),
    }
}

#[tokio::main(flavor = "current_thread")]
pub async fn smtpsub(
    system_config: SystemConfig,
    system_root: PathBuf,
    mut users_root: PathBuf,
    implicit_tls: bool,
) {
    if system_config.smtp.host_name.is_empty() {
        fatal!(
            EX_CONFIG,
            "smtp.host_name must be explicitly configured for SMTP submission",
        );
    }
    let host_name = system_config.smtp.host_name.clone();
    let verbose_outbound_tls = system_config.smtp.verbose_outbound_tls;
    let ssl_acceptor = create_ssl_acceptor(&system_config, &system_root);

    // We've opened access to everything on the main system we need; now we can
    // apply chroot and privilege deescalation.
    let (log_prefix, _peer_name) = configure_system(
        if implicit_tls { "smtpssub" } else { "smtpsub" },
        &system_config,
        &mut users_root,
    );

    let resolver =
        match hickory_resolver::AsyncResolver::tokio_from_system_conf() {
            Ok(r) => Rc::new(r),
            Err(e) => {
                fatal!(EX_OSERR, "Failed to initialise DNS resolver: {e}",)
            },
        };
    let dns_cache = Rc::new(RefCell::new(dns::Cache::default()));

    let io = ServerIo::new_stdio().unwrap_or_else(|e| {
        fatal!(
            EX_OSERR,
            "Failed to put stdio into non-blocking mode: {e:?}",
        )
    });

    let ssl_acceptor = if implicit_tls {
        match tokio::time::timeout(
            Duration::from_secs(30),
            io.ssl_accept(&ssl_acceptor),
        )
        .await
        {
            Ok(Ok(())) => {},
            Ok(Err(e)) => {
                warn!("{} SSL handshake failed: {}", log_prefix, e);
                std::process::exit(0)
            },
            Err(_timeout) => {
                warn!("{} SSL handshake timed out", log_prefix);
                std::process::exit(0)
            },
        }

        // Get the key material out of memory.
        drop(ssl_acceptor);
        None
    } else {
        Some(ssl_acceptor)
    };

    info!("{} SSL handshake succeeded", log_prefix);

    let local_set = tokio::task::LocalSet::new();
    let log_prefix2 = log_prefix.clone();
    let result = local_set
        .run_until(crate::smtp::inbound::serve_smtpsub(
            io,
            Arc::new(system_config),
            log_prefix.clone(),
            ssl_acceptor,
            users_root,
            host_name.clone(),
            Box::new(move |account, id| {
                tokio::task::spawn_local({
                    let log_prefix = log_prefix2.clone();
                    let dns_cache = Rc::clone(&dns_cache);
                    let resolver = Rc::clone(&resolver);
                    let host_name = host_name.clone();
                    async move {
                        let result = crate::smtp::outbound::send_message(
                            dns_cache,
                            Some(resolver),
                            account,
                            id,
                            host_name.clone(),
                            verbose_outbound_tls,
                            None,
                        )
                        .await;
                        if let Err(e) = result {
                            error!(
                                "{log_prefix} Error setting up \
                                    message delivery: {e}"
                            );
                        }
                    }
                });
            }),
        ))
        .await;

    match result {
        Ok(()) => info!("{} Normal client disconnect", log_prefix),
        Err(e) => warn!("{} Abnormal client disconnect: {}", log_prefix, e),
    }

    // Wait for all mail to be sent.
    local_set.await;
}

fn smtp_host_name(system_config: &SystemConfig) -> String {
    if system_config.smtp.host_name.is_empty() {
        let host_name_cstr = nix::unistd::gethostname().unwrap_or_else(|e| {
            fatal!(
                EX_OSERR,
                "Failed to determine host name; you may \
                 need to explicitly configure it: {}",
                e
            )
        });
        host_name_cstr
            .to_str()
            .unwrap_or_else(|| {
                fatal!(EX_OSERR, "System host name is not UTF-8")
            })
            .to_owned()
    } else {
        system_config.smtp.host_name.clone()
    }
}

fn create_ssl_acceptor(
    system_config: &SystemConfig,
    system_root: &Path,
) -> SslAcceptor {
    let mut acceptor =
        match SslAcceptor::mozilla_intermediate_v5(SslMethod::tls_server()) {
            Ok(a) => a,
            Err(e) => fatal!(
                EX_SOFTWARE,
                "Failed to initialise OpenSSL acceptor: {}",
                e
            ),
        };

    let private_key_path = system_root.join(&system_config.tls.private_key);
    if let Err(e) =
        acceptor.set_private_key_file(&private_key_path, SslFiletype::PEM)
    {
        fatal!(
            EX_CONFIG,
            "Unable to load TLS private key from '{}': {}",
            private_key_path.display(),
            e
        );
    }

    let certificate_path =
        system_root.join(&system_config.tls.certificate_chain);
    if let Err(e) = acceptor.set_certificate_chain_file(&certificate_path) {
        fatal!(
            EX_CONFIG,
            "Unable to load TLS certificate chain from '{}': {}",
            certificate_path.display(),
            e
        );
    }

    if let Err(e) = acceptor.check_private_key() {
        fatal!(EX_CONFIG, "TLS key seems to be invalid: {}", e);
    }

    acceptor.build()
}

fn configure_system(
    protocol: &str,
    system_config: &SystemConfig,
    users_root: &mut PathBuf,
) -> (LogPrefix, String) {
    if let Err(exit) =
        unix_privileges::assume_system(&system_config.security, users_root)
    {
        exit.exit();
    }

    // We deliberately want to make things group-writable.
    let _ =
        nix::sys::stat::umask(nix::sys::stat::Mode::from_bits_retain(0o002));

    // We've dropped all privileges we can; it's now safe to start talking to
    // the client.
    match (nix::unistd::isatty(STDIN), nix::unistd::isatty(STDOUT)) {
        (Ok(true), _) | (_, Ok(true)) => {
            // In this case, we *do* want to use die!() since we're on a
            // terminal.
            die!(EX_USAGE, "stdin and stdout must not be a terminal")
        },
        _ => (),
    }

    let mut peer_name = nix::sys::socket::getpeername::<
        nix::sys::socket::UnixAddr,
    >(STDIN)
    .map(|addr| addr.to_string())
    .or_else(|_| {
        nix::sys::socket::getpeername::<nix::sys::socket::SockaddrIn>(STDIN)
            .map(|addr| addr.to_string())
    })
    .or_else(|_| {
        nix::sys::socket::getpeername::<nix::sys::socket::SockaddrIn6>(STDIN)
            .map(|addr| addr.to_string())
    })
    .unwrap_or_else(|_| "unknown-socket".to_owned());

    // On FreeBSD, getpeername() on a UNIX socket returns "@\0", which breaks
    // syslog if we log that.
    if peer_name.contains('\0') {
        "unknown-socket".clone_into(&mut peer_name);
    }
    let log_prefix = LogPrefix::new(format!("{protocol}:{peer_name}"));

    if let Err(e) = nix::sys::socket::setsockopt(
        &std::io::stdin(),
        nix::sys::socket::sockopt::ReceiveTimeout,
        &nix::sys::time::TimeVal::minutes(30),
    )
    .and_then(|_| {
        nix::sys::socket::setsockopt(
            &std::io::stdout(),
            nix::sys::socket::sockopt::SendTimeout,
            &nix::sys::time::TimeVal::minutes(30),
        )
    }) {
        warn!("{} Unable to configure timeouts: {}", log_prefix, e);
    }

    // It is not unusual for stdio to be UNIX sockets instead of TCP, so don't
    // complain if setting TCP_NODELAY fails.
    let _ = nix::sys::socket::setsockopt(
        &std::io::stdout(),
        nix::sys::socket::sockopt::TcpNoDelay,
        &true,
    );

    info!("{} Connection established", log_prefix);
    (log_prefix, peer_name)
}