summaryrefslogtreecommitdiff
path: root/sys/mta/default.nix
blob: 9a1875b515fc30e97a98e1ff1cdb28d52701ddeb (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
{ config, lib, pkgs, ... }:
with lib; let
  cfg = config.local.mta;

  inherit (config.local) domains virtual users;
  inherit (config.networking) domain;

  virtualDomains = filterAttrs (name: _: name != domain) virtual;
in
{
  options.local.mta = {
    enable = mkEnableOption "mail transfer agent";

    mdaAddr = mkOption {
      type = types.str;
    };

    saslPort = mkOption {
      type = types.port;
    };

    lmtpPort = mkOption {
      type = types.port;
    };
  };

  config = mkIf cfg.enable {
    services = {
      fail2ban.jails.postfix.settings = {
        filter = "postfix[mode=aggressive]";
      };

      opendkim = {
        enable = true;

        group = "postfix";
        domains = "csl:" + concatStringsSep "," ([ domain ] ++ attrNames virtualDomains);
        selector = "202408";

        configFile = pkgs.writeText "opendkim.conf" ''
          UMask 007
        '';
      };

      postfix =
        let
          cert = config.security.acme.certs.${domains.smtp.main}.directory;
        in
        {
          enable = true;
          enableSmtp = true;
          enableSubmissions = true;

          inherit domain;
          hostname = domains.smtp.main;
          #TODO: check_recipient_access para rechazar localhost desde afuera
          destination = [ "localhost" "$mydomain" ];
          origin = "$mydomain";

          networksStyle = "host";

          sslKey = "${cert}/key.pem";
          sslCert = "${cert}/fullchain.pem";

          # También es postmaster
          rootAlias = config.local.sysadmin;

          extraAliases = concatLines
            (flatten (mapAttrsToList
              (name: user: map
                (alias: "${alias}: ${name}")
                user.hardAliases)
              users));

          localRecipients = map
            (user: "${user}@${domain}")
            (attrNames (users // virtual.${domain}.users));

          virtual = concatLines (flatten (mapAttrsToList
            (name: virtual: mapAttrsToList
              (alias: targets: "${alias}@${name} ${concatStringsSep ", " targets}")
              virtual.aliases)
            virtual));

          mapFiles = {
            sender_ccerts =
              pkgs.writeText "postfix-sender_ccerts"
                (concatLines (flatten (mapAttrsToList
                  (username: user: map
                    (alias: "${alias}@${domain} CCERTS ${concatStringsSep "," (map (certPath: config.local.pki.byPath.${certPath}.fingerprint.sha256) user.mail.certs)}")
                    ([ username ] ++ user.hardAliases))
                  (filterAttrs (_: user: user.mail.certs != [ ]) users))));

            sender_login =
              pkgs.writeText "postfix-sender_login"
                (concatLines (flatten (mapAttrsToList
                  (username: user: map
                    (alias: "${alias}@${domain} ${username}")
                    ([ username ] ++ user.hardAliases))
                  users)));

            virtual_recipients =
              pkgs.writeText "postfix-virtual_recipients"
                (concatLines (flatten (mapAttrsToList
                  (virtualDomain: virtual: mapAttrsToList
                    # El lado derecho de esta tabla debe existir pero nunca se usa
                    (username: _: "${username}@${virtualDomain} foo")
                    virtual.users)
                  virtualDomains)));

            virtual_rules =
              pkgs.writeText "postfix-virtual_rules"
                (concatLines (flatten (mapAttrsToList
                  (name: virtual: map
                    (rule: "/^${rule.pattern}@${name}$/ ${concatStringsSep ", " rule.targets}")
                    virtual.rules)
                  virtual)));
          };

          config =
            let
              mdaTransport = "lmtp:inet:${cfg.mdaAddr}:${toString cfg.lmtpPort}";
            in
            {
              # user+extension@domain.tld
              recipient_delimiter = "+";

              message_size_limit = toString (50 * 1048576);

              virtual_alias_maps = mkAfter [ "pcre:/etc/postfix/virtual_rules" ];
              virtual_mailbox_domains = attrNames virtualDomains;
              virtual_mailbox_maps = [ "hash:/etc/postfix/virtual_recipients" ];

              local_transport = mdaTransport;
              virtual_transport = mdaTransport;

              smtpd_sasl_type = "dovecot";
              smtpd_sasl_path = "inet:${cfg.mdaAddr}:${toString cfg.saslPort}";
              smtpd_sasl_local_domain = "$mydomain";
              smtpd_sasl_security_options = [ "noanonymous" ];

              smtpd_tls_auth_only = true;
              # Nota: smtpd_tls_dh1024_param_file fue deprecado en 3.9

              smtpd_tls_CAfile = "${config.local.pki.ca.mail.fullchain}";
              smtpd_tls_ccert_verifydepth = "1";
              tls_append_default_CA = false; # Crítico

              # Inventado, no es parámetro de postfix
              local_submission_client_restrictions = [
                "permit_tls_all_clientcerts"
                "permit_sasl_authenticated"
                "reject"
              ];

              smtpd_relay_restrictions = [
                "permit_mynetworks"
                "permit_tls_all_clientcerts"
                "permit_sasl_authenticated"
                "reject_unauth_destination"
              ];

              smtpd_sender_login_maps = [ "hash:/etc/postfix/sender_login" ];

              smtpd_sender_restrictions = [
                "check_sender_access hash:/etc/postfix/sender_ccerts"
                "reject_sender_login_mismatch"
              ];

              smtpd_milters = "unix:/run/opendkim/opendkim.sock";
              non_smtpd_milters = "$smtpd_milters";
              milter_default_action = "accept";
            };

          # Importante: existe submissionOptions por aparte, no son iguales
          submissionsOptions = {
            smtpd_client_restrictions = "$local_submission_client_restrictions";
            smtpd_sasl_auth_enable = "yes";
            smtpd_tls_ask_ccert = "yes";
            smtpd_tls_security_level = "encrypt";
          };
        };
    };

    networking.firewall.allowedTCPPorts = [ 25 465 ];

    local = {
      boot.impermanence.directories = [
        { directory = "/var/lib/opendkim"; user = "opendkim"; group = "postfix"; mode = "u=rwx,g=,o="; }
        { directory = "/var/lib/postfix"; user = "root"; group = "root"; mode = "u=rwx,g=rx,o=rx"; }
      ];

      certs.smtp.enable = true;
    };
  };
}