summaryrefslogtreecommitdiff
path: root/hosts/surtr/email/default.nix
blob: e3437a6b97caab8d99f16fe744ce668e342b2848 (plain)
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
{ config, pkgs, lib, ... }:

with lib;

let
  dovecotSievePipeBin = pkgs.stdenv.mkDerivation {
    name = "dovecot-sieve-pipe-bin";
    src = ./dovecot-pipe-bin;
    buildInputs = with pkgs; [ makeWrapper coreutils bash rspamd ];
    buildCommand = ''
      mkdir -p $out/pipe/bin
      cp $src/* $out/pipe/bin/
      chmod a+x $out/pipe/bin/*
      patchShebangs $out/pipe/bin

      for file in $out/pipe/bin/*; do
        wrapProgram $file \
          --set PATH "${pkgs.coreutils}/bin:${pkgs.rspamd}/bin"
      done
    '';
  };

  spmDomains = ["bouncy.email"];
in {
  config = {
    nixpkgs.overlays = [
      (final: prev: {
        postfix = prev.postfix.override {
          withLDAP = false;
          withPgSQL = true;
        };
        dovecot = prev.dovecot.override {
          withSQLite = false;
          withPgSQL = true;
        };
      })
    ];
    
    services.postfix = {
      enable = true;
      hostname = "surtr.yggdrasil.li";
      recipientDelimiter = "";
      setSendmail = true;
      postmasterAlias = ""; rootAlias = ""; extraAliases = "";
      destination = [];
      sslCert = "/run/credentials/postfix.service/surtr.yggdrasil.li.pem";
      sslKey = "/run/credentials/postfix.service/surtr.yggdrasil.li.key.pem";
      networks = ["127.0.0.0/8" "[::ffff:127.0.0.0]/104" "[::1]/128" "10.141.0.0/16"];
      config = let
        relay_ccert = "texthash:${pkgs.writeText "relay_ccert" ""}";
      in {
        #the dh params
        smtpd_tls_dh1024_param_file = toString config.security.dhparams.params."postfix-1024".path;
        smtpd_tls_dh512_param_file = toString config.security.dhparams.params."postfix-512".path;
        #enable ECDH
        smtpd_tls_eecdh_grade = "strong";
        #enabled SSL protocols, don't allow SSLv2 and SSLv3
        smtpd_tls_protocols = ["!SSLv2" "!SSLv3" "!TLSv1" "!TLSv1.1" "!TLSv1.2"];
        smtpd_tls_mandatory_protocols = ["!SSLv2" "!SSLv3" "!TLSv1" "!TLSv1.1" "!TLSv1.2"];
        #allowed ciphers for smtpd_tls_security_level=encrypt
        smtpd_tls_mandatory_ciphers = "high";
        #allowed ciphers for smtpd_tls_security_level=may
        #smtpd_tls_ciphers = high
        #enforce the server cipher preference
        tls_preempt_cipherlist = true;
        #disable following ciphers for smtpd_tls_security_level=encrypt
        smtpd_tls_mandatory_exclude_ciphers = ["aNULL" "MD5" "DES" "ADH" "RC4" "PSD" "SRP" "3DES" "eNULL"];
        #disable following ciphers for smtpd_tls_security_level=may
        smtpd_tls_exclude_ciphers = ["aNULL" "MD5" "DES" "ADH" "RC4" "PSD" "SRP" "3DES" "eNULL"];
        #enable TLS logging to see the ciphers for inbound connections
        smtpd_tls_loglevel = "1";
        #enable TLS logging to see the ciphers for outbound connections
        smtp_tls_loglevel = "1";

        smtpd_tls_received_header = true;

        smtpd_tls_ask_ccert = true;
        smtpd_tls_CAfile = toString ./ca/ca.crt;

        smtp_tls_security_level = "dane";
        smtp_dns_support_level = "dnssec";

        tls_server_sni_maps = ''texthash:${pkgs.writeText "sni" ''
          bouncy.email /run/credentials/postfix.service/bouncy.email.full.pem
          mailin.bouncy.email /run/credentials/postfix.service/mailin.bouncy.email.full.pem
          mailsub.bouncy.email /run/credentials/postfix.service/mailsub.bouncy.email.full.pem
          .bouncy.email /run/credentials/postfix.service/bouncy.email.full.pem
        ''}'';

        local_recipient_maps = "";

        # 10 GiB
        message_size_limit = "10737418240";
        # 10 GiB
        mailbox_size_limit = "10737418240";

        smtpd_delay_reject = true;
        smtpd_helo_required = true;
        smtpd_helo_restrictions = "permit";

        smtpd_recipient_restrictions = [
          "reject_unauth_pipelining"
          "reject_non_fqdn_recipient"
          "reject_unknown_recipient_domain"
          "check_recipient_access pgsql:${pkgs.writeText "check_recipient_access.cf" ''
            hosts = postgresql:///email
            dbname = email
            query = SELECT action FROM virtual_mailbox_access WHERE lookup = '%s'
          ''}"
          "permit_mynetworks"
          "check_ccert_access ${relay_ccert}"
          "reject_non_fqdn_helo_hostname"
          "reject_invalid_helo_hostname"
          "reject_unauth_destination"
          "reject_unknown_recipient_domain"
          "reject_unverified_recipient"
        ];
        unverified_recipient_reject_code = "550";
        unverified_recipient_reject_reason = "Recipient address lookup failed";
        address_verify_map = "internal:address_verify_map";
        address_verify_positive_expire_time = "1h";
        address_verify_positive_refresh_time = "15m";
        address_verify_negative_expire_time = "15s";
        address_verify_negative_refresh_time = "5s";
        address_verify_cache_cleanup_interval = "5s";
        address_verify_poll_delay = "1s";

        smtpd_relay_restrictions = [
          "permit_mynetworks"
          "check_ccert_access ${relay_ccert}"
          "reject_unauth_destination"
        ];

        propagate_unmatched_extensions = ["canonical" "virtual" "alias"];
        smtpd_authorized_verp_clients = "$authorized_verp_clients";
        authorized_verp_clients = "$mynetworks";

        milter_default_action = "accept";
        smtpd_milters = [config.services.opendkim.socket "local:/run/rspamd/rspamd-milter.sock"];
        non_smtpd_milters = [config.services.opendkim.socket "local:/run/rspamd/rspamd-milter.sock"];

        alias_maps = "";

        queue_run_delay = "10s";
        minimal_backoff_time = "1m";
        maximal_backoff_time = "10m";
        maximal_queue_lifetime = "100m";
        bounce_queue_lifetime = "20m";

        smtpd_discard_ehlo_keyword_address_maps = "cidr:${pkgs.writeText "esmtp_access" ''
          # Allow DSN requests from local subnet only
          192.168.0.0/16      silent-discard
          172.16.0.0/12       silent-discard
          10.0.0.0/8          silent-discard
          0.0.0.0/0           silent-discard, dsn
          fd00::/8            silent-discard
          ::/0                silent-discard, dsn
        ''}";

        sender_canonical_maps = "tcp:localhost:${toString config.services.postsrsd.forwardPort}";
        sender_canonical_classes = "envelope_sender";
        recipient_canonical_maps = "tcp:localhost:${toString config.services.postsrsd.reversePort}";
        recipient_canonical_classes = ["envelope_recipient" "header_recipient"];

        virtual_mailbox_domains = ''pgsql:${pkgs.writeText "virtual_mailbox_domains.cf" ''
          hosts = postgresql:///email
          dbname = email
          query = SELECT 1 FROM virtual_mailbox_domain WHERE domain = '%s'
        ''}'';
        virtual_mailbox_maps = ''pgsql:${pkgs.writeText "virtual_mailbox_maps.cf" ''
          hosts = postgresql:///email
          dbname = email
          query = SELECT 1 FROM virtual_mailbox_mapping WHERE lookup = '%s'
        ''}'';
        dvlmtp_destination_recipient_limit = "1";
        virtual_transport = "dvlmtp:unix:/run/postfix/dovecot-lmtp";
      };
      masterConfig = {
        smtps = {
          type = "inet";
          private = false;
          command = "smtpd";
          args = [
            "-o" "smtpd_tls_wrappermode=yes"
            "-o" "smtpd_tls_ask_ccert=yes"
            "-o" "smtpd_tls_req_ccert=yes"
            "-o" "smtpd_client_restrictions=permit_tls_all_clientcerts,reject"
            "-o" "smtpd_relay_restrictions=permit_tls_all_clientcerts,reject"
            "-o" "smtpd_sender_restrictions=reject_unknown_sender_domain,reject_unverified_sender"
            "-o" "unverified_sender_reject_code=550"
            "-o" "unverified_sender_reject_reason={Sender address rejected: undeliverable address}"
            "-o" "smtpd_recipient_restrictions=reject_unauth_pipelining,reject_non_fqdn_recipient,reject_unknown_recipient_domain,permit_tls_all_clientcerts,reject"
            "-o" "milter_macro_daemon_name=surtr.yggdrasil.li"
            "-o" ''smtpd_milters=${config.services.opendkim.socket}''
          ];
        };
        dvlmtp = {
          command = "lmtp";
          args = [
            "flags=DORX"
          ];
        };
      };
    };

    services.postsrsd = {
      enable = true;
      domain = "surtr.yggdrasil.li";
      separator = "+";
      excludeDomains = [ "surtr.yggdrasil.li"
                         ".bouncy.email" "bouncy.email"
                       ];
    };

    services.opendkim = {
      enable = true;
      user = "postfix"; group = "postfix";
      socket = "local:/run/opendkim/opendkim.sock";
      domains = ''csl:${concatStringsSep "," ["surtr.yggdrasil.li" "bouncy.email"]}'';
      selector = "surtr";
      configFile = builtins.toFile "opendkim.conf" ''
        Syslog true
        MTA surtr.yggdrasil.li
        MTACommand ${config.security.wrapperDir}/sendmail
        LogResults true
      '';
    };

    services.rspamd = {
      enable = true;
      workers = {
        controller = {
          type = "controller";
          count = 1;
          bindSockets = [
            { mode = "0660";
              socket = "/run/rspamd/worker-controller.sock";
              owner = config.services.rspamd.user;
              group = config.services.rspamd.group;
            }
          ];
          includes = [];
          extraConfig = ''
            static_dir = "''${WWWDIR}"; # Serve the web UI static assets
          '';
        };
        external = {
          type = "rspamd_proxy";
          bindSockets = [
            { mode = "0660";
              socket = "/run/rspamd/rspamd-milter.sock";
              owner = config.services.rspamd.user;
              group = config.services.rspamd.group;
            }
          ];
          extraConfig = ''
            milter = yes;
            timeout = 120s;

            upstream "local" {
              default = yes;
              self_scan = yes;
            }
          '';
        };
      };
      locals = {
        "milter_headers.conf".text = ''
          use = ["authentication-results", "x-spamd-result", "x-rspamd-queue-id", "x-rspamd-server", "x-spam-level", "x-spam-status"];
          extended_headers_rcpt = [];
        '';
        "actions.conf".text = ''
          reject = 15;
          add_header = 10;
          greylist = 5;
        '';
        "groups.conf".text = ''
          symbols {
            "BAYES_SPAM" {
              weight = 2.0;
            }
          }
        '';
        "dmarc.conf".text = ''
          reporting = true;
          send_reports = true;
          report_settings {
            org_name = "Yggdrasil.li";
            domain = "yggdrasil.li";
            email = "postmaster@yggdrasil.li";
          }
        '';
        "redis.conf".text = ''
          servers = "${config.services.redis.servers.rspamd.unixSocket}";
        '';
        "dkim_signing.conf".text = "enabled = false;";
        "neural.conf".text = "enabled = false;";
        "classifier-bayes.conf".text = ''
          enable = true;
          expire = 8640000;
          new_schema = true;
          backend = "redis";
          per_user = true;
          min_learns = 0;

          autolearn = [0, 10];

          statfile {
              symbol = "BAYES_HAM";
              spam = false;
          }
          statfile {
              symbol = "BAYES_SPAM";
              spam = true;
          }
        '';
        # "redirectors.inc".text = ''
        #   visit.creeper.host
        # '';
      };
    };

    users.groups.${config.services.rspamd.group}.members = [ config.services.postfix.user "dovecot2" ];

    services.redis.servers.rspamd.enable = true;

    users.groups.${config.services.redis.servers.rspamd.user}.members = [ config.services.rspamd.user ];

    services.dovecot2 = {
      enable = true;
      enablePAM = false;
      sslServerCert = "/run/credentials/dovecot2.service/surtr.yggdrasil.li.pem";
      sslServerKey = "/run/credentials/dovecot2.service/surtr.yggdrasil.li.key.pem";
      sslCACert = toString ./ca/ca.crt;
      mailLocation = "maildir:/var/lib/mail/%u/maildir:UTF-8:INDEX=/var/lib/dovecot/indices/%u";
      modules = with pkgs; [ dovecot_pigeonhole dovecot_fts_xapian ];
      mailPlugins.globally.enable = [ "fts" "fts_xapian" ];
      protocols = [ "lmtp" "sieve" ];
      extraConfig = let
        dovecotSqlConf = pkgs.writeText "dovecot-sql.conf" ''
          driver = pgsql
          connect = dbname=email
          password_query = SELECT NULL as password, 'Y' as nopassword, "user", quota_rule, 'dovecot2' as uid, 'dovecot2' as gid FROM imap_user WHERE "user" = '%n'
          user_query = SELECT "user", quota_rule, 'dovecot2' as uid, 'dovecot2' as gid FROM imap_user WHERE "user" = '%n'
          iterate_query = SELECT "user" FROM imap_user
        '';
      in ''
        mail_home = /var/lib/mail/%u

        first_valid_uid = ${toString config.users.users.dovecot2.uid}
        last_valid_uid = ${toString config.users.users.dovecot2.uid}
        first_valid_gid = ${toString config.users.groups.dovecot2.gid}
        last_valid_gid = ${toString config.users.groups.dovecot2.gid}

        local_name imap.bouncy.email {
          ssl_cert = </run/credentials/dovecot2.service/imap.bouncy.email.pem
          ssl_key = </run/credentials/dovecot2.service/imap.bouncy.email.key.pem
        }
        local_name bouncy.email {
          ssl_cert = </run/credentials/dovecot2.service/bouncy.email.pem
          ssl_key = </run/credentials/dovecot2.service/bouncy.email.key.pem
        }

        ssl_require_crl = no
        ssl_verify_client_cert = yes

        ssl_min_protocol = TLSv1.2
        ssl_cipher_list = ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
        ssl_prefer_server_ciphers = no

        auth_ssl_username_from_cert = yes
        ssl_cert_username_field = commonName
        auth_mechanisms = external

        auth_verbose = yes
        verbose_ssl = yes
        auth_debug = yes

        service auth {
          user = dovecot2
        }
        service auth-worker {
          user = dovecot2
        }

        userdb {
          driver = prefetch
        }
        userdb {
          driver = sql
          args = ${dovecotSqlConf}
        }
        passdb {
          driver = sql
          args = ${dovecotSqlConf}
        }

        protocol lmtp {
          userdb {
            driver = sql
            args = ${pkgs.writeText "dovecot-sql.conf" ''
              driver = pgsql
              connect = dbname=email
              user_query = SELECT DISTINCT ON (extension IS NULL, local IS NULL) "user", quota_rule, 'dovecot2' as uid, 'dovecot2' as gid FROM lmtp_mapping WHERE CASE WHEN extension IS NOT NULL AND local IS NOT NULL THEN ('%n' :: citext) = local || '+' || extension AND domain = ('%d' :: citext) WHEN local IS NOT NULL THEN (local = ('%n' :: citext) OR ('%n' :: citext) ILIKE local || '+%%') AND domain = ('%d' :: citext) WHEN extension IS NOT NULL THEN ('%n' :: citext) ILIKE '%%+' || extension AND domain = ('%d' :: citext) ELSE domain = ('%d' :: citext) END ORDER BY (extension IS NULL) ASC, (local IS NULL) ASC
            ''}

            skip = never
            result_failure = return-fail
            result_internalfail = return-fail
          }
        }

        mail_plugins = $mail_plugins quota
        mailbox_list_index = yes
        postmaster_address = postmaster@yggdrasil.li
        recipient_delimiter = 
        auth_username_chars = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-+_@

        service lmtp {
          vsz_limit = 1G

          unix_listener /run/postfix/dovecot-lmtp {
            mode = 0600
            user = postfix
            group = postfix
          }
        }

        namespace inbox {
          separator = /
          inbox = yes
          prefix = 

          mailbox Trash {
            auto = no
            special_use = \Trash
          }
          mailbox Junk {
            auto = no
            special_use = \Junk
          }
          mailbox Drafts {
            auto = no
            special_use = \Drafts
          }
          mailbox Sent {
            auto = subscribe
            special_use = \Sent
          }
          mailbox "Sent Messages" {
            auto = no
            special_use = \Sent
          }
        }

        plugin {
          quota = count
          quota_rule = *:storage=1GB
          quota_rule2 = Trash:storage=+10%%
          quota_status_overquota = "552 5.2.2 Mailbox is full"
          quota_status_success = DUNNO
          quota_status_nouser = DUNNO
          quota_grace = 10%%
          quota_max_mail_size = ${config.services.postfix.config.message_size_limit}
          quota_vsizes = yes
        }

        protocol imap {
          mail_max_userip_connections = 50
          mail_plugins = $mail_plugins imap_quota imap_sieve
        }

        service imap-login {
          inet_listener imap {
            port = 0
          }
        }

        service managesieve-login {
          inet_listener sieve {
            port = 4190
          }
        }

        plugin {
          sieve_plugins = sieve_imapsieve sieve_extprograms
          sieve = file:~/sieve;active=~/dovecot.sieve
          sieve_redirect_envelope_from = orig_recipient
          sieve_before = /etc/dovecot/sieve_before.d

          sieve_global_extensions = +vnd.dovecot.pipe +vnd.dovecot.environment
          sieve_pipe_bin_dir = ${dovecotSievePipeBin}/pipe/bin

          imapsieve_mailbox1_name = *
          imapsieve_mailbox1_causes = FLAG
          imapsieve_mailbox1_before = /etc/dovecot/sieve_flag.d/learn-junk.sieve
        }

        plugin {
          plugin = fts fts_xapian
          fts = xapian
          fts_xapian = partial=2 full=20 attachments=1 verbose=1

          fts_autoindex = yes

          fts_enforced = no
        }

        service indexer-worker {
          vsz_limit = ${toString (1024 * 1024 * 1024)}
        }
      '';
    };

    systemd.services.dovecot-fts-xapian-optimize = {
      description = "Optimize dovecot indices for fts_xapian";
      requisite = [ "dovecot2.service" ];
      after = [ "dovecot2.service" ];
      startAt = "*-*-* 22:00:00 Europe/Berlin";
      serviceConfig = {
        Type = "oneshot";
        ExecStart = "${pkgs.dovecot}/bin/doveadm fts optimize -A";
        PrivateDevices = true;
        PrivateNetwork = true;
        ProtectKernelTunables = true;
        ProtectKernelModules = true;
        ProtectControlGroups = true;
        ProtectHome = true;
        ProtectSystem = true;
        PrivateTmp = true;
      };
    };
    systemd.timers.dovecot-fts-xapian-optimize = {
      timerConfig = {
        RandomizedDelaySec = 4 * 3600;
      };
    };

    environment.etc = {
      "dovecot/sieve_before.d/tag-junk.sieve".text = ''
        require ["imap4flags"];

        if header :contains "X-Spam-Flag" "YES" {
          addflag ["\\Junk"];
        }
      '';

      "dovecot/sieve_flag.d/learn-junk.sieve".text = ''
        require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables", "imap4flags"];

        if environment :matches "imap.user" "*" {
          set "username" "''${1}";
        }

        if environment :contains "imap.changedflags" "\\Junk" {
          if hasflag "\\Junk" {
            pipe :copy "learn_spam.sh" [ "''${username}" ];
          } else {
            if environment :matches "imap.mailbox" "*" {
              set "mailbox" "''${1}";
            }

            if not anyof(string "''${mailbox}" "Trash", string "''${mailbox}" "Junk") {
              pipe :copy "learn_ham.sh" [ "''${username}" ];
            }
          }
        }
      '';
    };

    security.dhparams = {
      params = {
        "postfix-512".bits = 512;
        "postfix-1024".bits = 2048;
      };
    };

    security.acme.domains = {
      "bouncy.email" = {};
      "mailin.bouncy.email" = {};
      "mailsub.bouncy.email" = {};
      "imap.bouncy.email" = {};
      "mta-sts.bouncy.email" = {};
      "surtr.yggdrasil.li" = {};
    } // listToAttrs (map (domain: nameValuePair "spm.${domain}" {}) spmDomains);

    systemd.services.postfix = {
      serviceConfig.LoadCredential = [
        "surtr.yggdrasil.li.key.pem:${config.security.acme.certs."surtr.yggdrasil.li".directory}/key.pem"
        "surtr.yggdrasil.li.pem:${config.security.acme.certs."surtr.yggdrasil.li".directory}/fullchain.pem"
        "bouncy.email.full.pem:${config.security.acme.certs."bouncy.email".directory}/full.pem"
        "mailin.bouncy.email.full.pem:${config.security.acme.certs."mailin.bouncy.email".directory}/full.pem"
        "mailsub.bouncy.email.full.pem:${config.security.acme.certs."mailsub.bouncy.email".directory}/full.pem"
      ];
    };

    systemd.services.dovecot2 = {
      preStart = ''
        for f in /etc/dovecot/sieve_flag.d/*.sieve /etc/dovecot/sieve_before.d/*.sieve; do
          ${pkgs.dovecot_pigeonhole}/bin/sievec $f
        done
      '';
      
      serviceConfig = {
        LoadCredential = [
          "surtr.yggdrasil.li.key.pem:${config.security.acme.certs."surtr.yggdrasil.li".directory}/key.pem"
          "surtr.yggdrasil.li.pem:${config.security.acme.certs."surtr.yggdrasil.li".directory}/fullchain.pem"
          "bouncy.email.key.pem:${config.security.acme.certs."bouncy.email".directory}/key.pem"
          "bouncy.email.pem:${config.security.acme.certs."bouncy.email".directory}/fullchain.pem"
          "imap.bouncy.email.key.pem:${config.security.acme.certs."imap.bouncy.email".directory}/key.pem"
          "imap.bouncy.email.pem:${config.security.acme.certs."imap.bouncy.email".directory}/fullchain.pem"
        ];
      };
    };

    services.nginx = {
      upstreams.spm = {
        servers = {
          "unix:/run/spm/server.sock" = {};
        };
      };

      virtualHosts = listToAttrs (map (domain: nameValuePair "spm.${domain}" {
        forceSSL = true;
        sslCertificate = "/run/credentials/nginx.service/spm.${domain}.pem";
        sslCertificateKey = "/run/credentials/nginx.service/spm.${domain}.key.pem";
        extraConfig = ''
          ssl_stapling off;
          ssl_verify_client on;
          ssl_client_certificate ${toString ./ca/ca.crt};
        '';
        locations."/" = {
          proxyPass = "http://spm";

          extraConfig = ''
            proxy_set_header SSL-CLIENT-VERIFY $ssl_client_verify;
            proxy_set_header SSL-CLIENT-S-DN $ssl_client_s_dn;
            proxy_set_header SPM-DOMAIN "${domain}";
          '';
        };
      }) spmDomains) // {
        "mta-sts.bouncy.email" = {
          locations."/".root = pkgs.runCommand "mta-sts" {} ''
            mkdir -p $out/.well-known
            cp ${pkgs.writeText "mta-sts.txt" ''
              version: STSv1
              mode: testing
              mx: mailin.bouncy.email
              max_age: 604800
            ''} $out/.well-known/mta-sts.txt
          '';
        };
      };
    };

    systemd.services.nginx.serviceConfig.LoadCredential = concatMap (domain: [
      "spm.${domain}.key.pem:${config.security.acme.certs."spm.${domain}".directory}/key.pem"
      "spm.${domain}.pem:${config.security.acme.certs."spm.${domain}".directory}/fullchain.pem"
    ]) spmDomains ++ [
      "mta-sts.bouncy.email.key.pem:${config.security.acme.certs."mta-sts.bouncy.email".directory}/key.pem"
      "mta-sts.bouncy.email.pem:${config.security.acme.certs."mta-sts.bouncy.email".directory}/fullchain.pem"
    ];

    systemd.services.spm = {
      serviceConfig = {
        Type = "notify";
        ExecStart = "${pkgs.spm}/bin/spm-server";
        User = "spm";
        Group = "spm";

        Environment = [
          "SPM_INSTANCE=ed1c0e1d-7be4-4dd5-b51a-291bad3ac9c9"
          "PGCONNSTR=dbname=email"
        ];

        LoadCredential = [
          "spm-keys.json:${config.sops.secrets."spm-keys.json".path}"
        ];
      };
    };
    systemd.sockets.spm = {
      wantedBy = [ "nginx.service" ];
      
      socketConfig = {
        ListenStream = "/run/spm/server.sock";
        SocketUser = "spm";
        SocketGroup = "spm";
        SocketMode = 0660;
      };
    };

    users.users.spm = {
      isSystemUser = true;
      group = "spm";
    };

    users.groups.spm = {
      members = [ config.services.nginx.user ];
    };

    sops.secrets."spm-keys.json" = {
      format = "binary";
      sopsFile = ./spm-keys.json;
    };
  };
}