Puppet Class: profile::postfix::mx

Defined in:
modules/profile/manifests/postfix/mx.pp

Summary

Setup Postfix and Rspamd on MX hosts

Overview

SPDX-License-Identifier: Apache-2.0

Examples:

static_transport_maps example
gmail:
  type: 'hash'
    content: |
      wikimedia.org smtp:aspmx.l.google.com

Parameters:

  • config (Hash) (defaults to: lookup('profile::postfix::mx::config', { 'default_value' => {} }))

    Postfix configuration, excluding virtual_alias_maps, transport_maps, and the base Postfix configuration which is generated by this class, then to the Postfix module.

  • static_transport_maps (Profile::Postfix::Static_transport_maps) (defaults to: lookup('profile::postfix::mx::static_transport_maps', {'default_value' => {}}))

    Postfix transport maps whose values are supplied inline.

  • dynamic_transport_maps (Profile::Postfix::Dynamic_transport_maps) (defaults to: lookup('profile::postfix::mx::dynamic_transport_maps', {'default_value' => {}}))

    Postfix transport maps whose values are generated elsewhere, i.e. just the path to the generated map on disk.

  • domain_aliases_generic (Array[Stdlib::Host]) (defaults to: lookup('profile::postfix::mx::domain_aliases_generic', {'default_value' => []}))

    List of domains which have generic aliases, e.g. postmaster

  • domain_aliases (Profile::Postfix::Domain_aliases) (defaults to: lookup('profile::postfix::mx::domain_aliases', {'default_value' => {}}))

    Hash of domain name to specific domain aliases in Postfix lookup format

  • rspamd_dkim_keys (Hash[String[1], String[1]]) (defaults to: lookup('profile::postfix::mx::rspamd_dkim_keys', { 'default_value' => {} }))

    Hash of DKIM key name to private key value

  • rspamd_config (Hash) (defaults to: lookup('profile::postfix::mx::rspamd_config', { 'default_value' => {} }))

    Rspamd config, passed directly to rspamd module

  • rspamd_override_config (Hash) (defaults to: lookup('profile::postfix::mx::rspamd_override_config', { 'default_value' => {} }))

    Rspamd config, passed directly to rspamd module after adding trusted networks.

  • rspamd_sender_discards (Array[String[1]]) (defaults to: lookup('profile::postfix::mx::rspamd_sender_discards', {'default_value' => []}))

    Sender address patterns to silently discard, these patterns should conform to the Rspamd syntax: rspamd.com/doc/modules/multimap.html#regexp-maps

  • plain_auth_logins (Hash[Stdlib::Email, String[1]]) (defaults to: lookup('profile::postfix::mx::plain_auth_logins', {'default_value' => {}}))

    Hash of username to hashed password for SMTP plain authenticated relaying, protected by TLS.

  • trusted_networks (Array[Stdlib::IP::Address]) (defaults to: lookup('profile::postfix::mx::trusted_networks', {'default_value' => $::network::constants::aggregate_networks}))

    List of CIDRs to skip spam checking and relay checks.

  • mail_aliases (Optional[Profile::Postfix::Mail_aliases]) (defaults to: lookup('profile::postfix::mx::mail_aliases', {'default_value' => undef}))

    Config for script to send wikipedia.org mail aliases to ITS for review

  • verp_config (Optional[Profile::Postfix::Verp]) (defaults to: lookup('profile::postfix::mx::verp_config', {'default_value' => undef}))

    Config for enabling VERP for wikimedia bounces.

  • mta_mode (Profile::Postfix::Mta_mode) (defaults to: lookup('profile::postfix::mx::mta_mode', {'default_value' => 'null-client'}))

    General mode of postfix instance: null-client, outbound, or inbound



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
# File 'modules/profile/manifests/postfix/mx.pp', line 45

class profile::postfix::mx (
    Hash                                     $config                 = lookup('profile::postfix::mx::config', { 'default_value' => {} }),
    Profile::Postfix::Static_transport_maps  $static_transport_maps  = lookup('profile::postfix::mx::static_transport_maps', {'default_value' => {}}),
    Profile::Postfix::Dynamic_transport_maps $dynamic_transport_maps = lookup('profile::postfix::mx::dynamic_transport_maps', {'default_value' => {}}),
    Array[Stdlib::Host]                      $domain_aliases_generic = lookup('profile::postfix::mx::domain_aliases_generic', {'default_value' => []}),
    Profile::Postfix::Domain_aliases         $domain_aliases         = lookup('profile::postfix::mx::domain_aliases', {'default_value' => {}}),
    Hash                                     $rspamd_config          = lookup('profile::postfix::mx::rspamd_config', { 'default_value' => {} }),
    Hash                                     $rspamd_override_config = lookup('profile::postfix::mx::rspamd_override_config', { 'default_value' => {} }),
    Hash[String[1], String[1]]               $rspamd_dkim_keys       = lookup('profile::postfix::mx::rspamd_dkim_keys', { 'default_value' => {} }),
    Array[String[1]]                         $rspamd_sender_discards = lookup('profile::postfix::mx::rspamd_sender_discards', {'default_value' => []}),
    Hash[Stdlib::Email, String[1]]           $plain_auth_logins      = lookup('profile::postfix::mx::plain_auth_logins', {'default_value' => {}}),
    Array[Stdlib::IP::Address]               $trusted_networks       = lookup('profile::postfix::mx::trusted_networks', {'default_value' => $::network::constants::aggregate_networks}),
    Optional[Profile::Postfix::Mail_aliases] $mail_aliases           = lookup('profile::postfix::mx::mail_aliases', {'default_value' => undef}),
    Optional[Profile::Postfix::Verp]         $verp_config            = lookup('profile::postfix::mx::verp_config', {'default_value' => undef}),
    Profile::Postfix::Mta_mode               $mta_mode               = lookup('profile::postfix::mx::mta_mode', {'default_value' => 'null-client'}),
) {
    $trusted_networks_filtered = $trusted_networks.filter |$x| {
        $x !~ /127.0.0.0|::1/
    }

    $domain_aliases_maps = $domain_aliases.map |$domain, $_| {
        "hash:/etc/postfix/aliases/virtual-${domain}"
    }
    $domain_aliases_generic_maps = $domain_aliases_generic.map |$domain| {
        "hash:/etc/postfix/aliases/virtual-${domain}"
    }
    $static_transport_maps_paths = $static_transport_maps.map |$name, $data| {
        "${data['type']}:/etc/postfix/transport-${name}"
    }
    $dynamic_transport_maps_paths = $dynamic_transport_maps.map |$_, $data| {
        "${data['type']}:${data['path']}"
    }

    # Postfix style with ipv6 networks surrounded by square braces
    $agg_nets = regsubst(
        $network::constants::aggregate_networks,
        '^([a-f0-9:]+)(\/.*)',
        '[\1]\2',
    )

    $base_config = {
        # Disable any compatibility settings prior to version 3.6, which
        # had the last change in defaults
        compatibility_level          => '3.6',
        mynetworks                   => $agg_nets,
        myhostname                   => $facts['fqdn'],
        inet_interfaces              => case $mta_mode {
            'null-client': { ['loopback-only'] }
            default:       { ['all'] }
        },
        # Override the default 'mail' syslog facility so our rsyslog config
        # doesn't result in double logging.
        syslog_facility              => 'local0',
        # Require TLS to advertise SMTP auth
        smtpd_tls_auth_only          => 'yes',
        header_checks                => ['regexp:/etc/postfix/header_checks'],
        smtpd_sender_restrictions    => [
            'reject_unknown_sender_domain',
            'reject_authenticated_sender_login_mismatch'
        ],
        smtpd_relay_restrictions     => [
            'permit_mynetworks',
            'permit_sasl_authenticated',
            'reject_unauth_destination',
        ],
        smtpd_recipient_restrictions => [
            'permit_mynetworks',
            'reject_unknown_recipient_domain',
        ],
        smtpd_milters                => ['unix:/rspamd/milter.sock'],
        # Disable local mail delivery
        local_transport              => 'error:local mail delivery is disabled',
        # Require mail clients to say helo
        smtpd_helo_required          => 'yes',
        # Require mail clients to use standard envelope commands
        strict_rfc821_envelopes      => 'yes',
        # Reject egress mail that is not configured
        smtpd_reject_unlisted_sender => 'yes',
    }

    if length($domain_aliases_maps + $domain_aliases_generic_maps) > 0 {
        $virtual_alias_maps = {
            virtual_alias_maps => $domain_aliases_maps + $domain_aliases_generic_maps
        }
    } else {
        $virtual_alias_maps = {}
    }
    if length($static_transport_maps_paths + $dynamic_transport_maps) > 0 {
        $transport_maps = {
            transport_maps => $static_transport_maps_paths + $dynamic_transport_maps_paths
        }
    } else {
        $transport_maps = {}
    }

    if 'virtual_alias_maps' in $config {
        fail('virtual_alias_maps may not be provided in $config, as it will be masked by domain_aliases{,_generic}')
    }
    if 'transport_maps' in $config {
        fail('transport_maps may not be provided in $config, as it will be masked by $transport_maps_{static,dynamic}')
    }

    mailalias { 'root':
        recipient => 'root@wikimedia.org',
    }

    if $plain_auth_logins != {} {
        $dovecot_config = {
            smtpd_sasl_type                 => 'dovecot',
            smtpd_sasl_path                 => 'private/auth',
            smtpd_sasl_auth_enable          => 'yes',
            smtpd_sasl_authenticated_header => 'yes',
            smtpd_sender_login_maps         => [
                'hash:/etc/postfix/controlled_envelope_senders'
            ],
        }
        ensure_packages(['dovecot-core'])
        file { '/etc/dovecot/plain_auth_logins':
            ensure  => present,
            owner   => 'root',
            group   => 'dovecot',
            mode    => '0440',
            content => Sensitive($plain_auth_logins.reduce('') |$memo, $v| {
                "${memo}${v[0]}:${v[1]}\n"
            }),
            require => Package['dovecot-core']
        }

        file { '/etc/dovecot':
          ensure  => directory,
          mode    => '0755',
          recurse => true,
          purge   => true,
          force   => true,
        }

        file { '/etc/dovecot/dovecot.conf':
          ensure  => file,
          mode    => '0755',
          content => @(EOF),
              auth_mechanisms = plain
              passdb {
                driver = passwd-file
                args = scheme=CRYPT username_format=%u /etc/dovecot/plain_auth_logins
              }
              service auth {
                # Postfix smtp-auth
                unix_listener /var/spool/postfix/private/auth {
                  mode = 0660
                  user = postfix
                  group = postfix
                }
              }
              | EOF
          notify  => Service['dovecot'],
          require => File['/var/spool/postfix'],
        }
        service {'dovecot':}
        postfix::lookup::database { '/etc/postfix/controlled_envelope_senders':
            content => $plain_auth_logins.keys().reduce('') |$memo, $addr| {
                "${memo}${addr} ${addr}\n"
            },
        }
    } else {
        $dovecot_config = {}
    }

    class { 'postfix':
        * => $config + $base_config + $dovecot_config + $virtual_alias_maps + $transport_maps
    }

    # We need rspamd to create the milter socket, before installing postfix
    Class['Rspamd'] -> Class['Postfix']

    case $mta_mode {
        'inbound': {
            acme_chief::cert { 'mx-in':
                puppet_rsc => Service['postfix'],
                key_group  => 'postfix',
            }
        }
        'outbound': {
            acme_chief::cert { 'mx-out':
                puppet_rsc => Service['postfix'],
                key_group  => 'postfix',
            }
        }
        'null-client': {
            # TODO: do we want to encrypt null-client traffic?
        }
        default: { fail('mta_mode not supported') }
    }

    monitoring::service { 'smtp':
        description   => 'Postfix SMTP',
        check_command => 'check_smtp_tls_le',
        notes_url     => 'https://wikitech.wikimedia.org/wiki/Mail#Troubleshooting',
    }

    firewall::service { 'smtp':
        proto => 'tcp',
        port  => '25',
    }

    if $mail_aliases {
        file { '/etc/mail-aliases.conf':
            ensure  => present,
            mode    => '0444',
            content => epp(
                'profile/postfix/mx/mail-aliases.conf.epp',
                {
                    'subject' => $mail_aliases['subject'],
                    'rcpt'    => $mail_aliases['rcpt'],
                    'path'    => $mail_aliases['path'],
                }
            ),
        }

        file { '/usr/local/bin/mail-aliases':
            ensure  => present,
            mode    => '0555',
            source  => 'puppet:///modules/profile/postfix/mx/mail-aliases.sh',
            require => File['/etc/mail-aliases.conf'],
        }

        systemd::timer::job { 'mail-aliases':
            ensure             => present,
            user               => 'postfix',
            description        => 'Emails the wikimedia.org mail alias file to ITS once per week',
            command            => '/usr/local/bin/mail-aliases',
            interval           => {'start' => 'OnCalendar', 'interval' => 'weekly'},
            monitoring_enabled => false,
            logging_enabled    => false,
            require            => File['/usr/local/bin/mail-aliases'],
        }
    }

    logrotate::conf { 'postfix':
        ensure  => present,
        content => @(EOF),
            # Managed by Puppet
            # logrotate(8) config
            /var/log/postfix.log {
                daily
                dateext
                dateyesterday
                rotate 60
                missingok
                nocreate
                compress
                delaycompress
                sharedscripts
                postrotate
                    systemctl kill -s HUP rsyslog.service
                endscript
            }
            | EOF
    }

    rsyslog::conf { 'postfix':
        priority => 20,
        content  => @(EOF),
            # Managed by Puppet
            # rsyslog.conf(5) config
            if ($programname startswith 'postfix') then {
                action(type="omfile" file="/var/log/postfix.log")
            }
            | EOF
    }

    class { 'prometheus_postfix_exporter': }

    # TODO: Move exim logic to profile::base
    package { [
        'exim4',
        'exim4-base',
        'exim4-config',
        'exim4-daemon-heavy',
        'exim4-daemon-light',
    ]:
        ensure => purged,
        notify => Exec['kill-exim4'],
        before => [
            Package['postfix'],
            Package['prometheus-postfix-exporter'],
        ]
    }

    exec { 'kill-exim4':
        command     => '/usr/bin/systemctl kill exim4',
        refreshonly => true,
    }

    # Install an email debugging tool
    ensure_packages(['swaks'])

    postfix::lookup::database { '/etc/aliases':
        type => 'hash',
    }

    Mailalias <||> -> Postfix::Lookup::Database['/etc/aliases']

    file { '/etc/postfix':
        ensure  => directory,
        mode    => '0755',
        # let debian manage these configish files, if we wipe them out, postfix
        # does not start.
        ignore  => [
            'makedefs.out',
            'post-install',
            'postfix-files',
            'postfix-script',
        ],
        recurse => true,
        purge   => true,
        force   => true,
    }

    $rspamd_base_config = {
        milter_headers => {
            use => [
                'x-spam-status',
                'authentication-results',
            ],
        },
        multimap => {
            trusted_networks => {
                type      => 'ip',
                map       => 'file:///var/lib/rspamd/trusted_networks.map',
                symbol    => 'TRUSTED_NETWORKS',
                action    => 'accept',
                prefilter => true,
            },
            sender_discards => {
                type      => 'from',
                map       => 'file:///var/lib/rspamd/sender_discards.map',
                symbol    => 'SENDER_DISCARDS',
                action    => 'discard',
                prefilter => true,
                regexp    => true,
            }
        },
        actions => {
            discard => {
                flags => ['no_threshold'],
            }
        },
        # NOTE: mode 666 is okay here because the parent directory is only accessible
        # by postfix and rspamd, we need 666 so that postfix can write to the
        # socket which has an ownership of _rspamd:_rspamd, we can't easily
        # change the ownership because we install rspamd first.
        'worker-proxy.inc' => {
            bind_socket => '/var/spool/postfix/rspamd/milter.sock mode=0666',
        },
    }

    file { '/var/spool/postfix':
        ensure => directory,
        mode   => '0755',
    }

    file { '/var/spool/postfix/rspamd':
        ensure  => directory,
        owner   => 'postfix',
        group   => '_rspamd',
        mode    => '0770',
        # Needed for postfix user & _rspamd group
        require => [
            Package['postfix'],
            Package['rspamd'],
        ],
    }

    file { '/var/lib/rspamd/sender_discards.map':
        ensure  => present,
        mode    => '0444',
        content => $rspamd_sender_discards.reduce('') |$memo, $v| {
            "${memo}${v}\n"
        },
        # needed to create the /var/lib/rspamd dir
        require => Package['rspamd'],
    }

    # Skip spam checking for trusted networks, this is needed in addition to
    # local_addrs, which skips other Rspamd checks.
    file { '/var/lib/rspamd/trusted_networks.map':
        ensure  => present,
        mode    => '0444',
        content => $trusted_networks_filtered.reduce('') |$memo, $v| {
            "${memo}${v}\n"
        },
        # needed to create the /var/lib/rspamd dir
        require => Package['rspamd'],
    }

    class { 'rspamd':
        manage_package_repo => false,
        config              => $rspamd_base_config + $rspamd_config,
        require             => File['/var/spool/postfix'],
    }

    $rspamd_override_config_base =  {
        'options.inc' => {
            'local_addrs' => $trusted_networks_filtered,
        }
    }

    rspamd::create_config_file_resources(
        $rspamd_override_config_base + $rspamd_override_config, { mode => 'override' }
    )

    if $rspamd_dkim_keys != {} {
        file { '/etc/rspamd/dkim':
            ensure  => directory,
            mode    => '0755',
            require => Package['rspamd'],
        }

        $rspamd_dkim_keys.each |$name, $key| {
            file { "/etc/rspamd/dkim/${name}":
              ensure  => file,
              owner   => '_rspamd',
              group   => '_rspamd',
              mode    => '0400',
              content => Sensitive($key),
              require => Package['rspamd'],
              notify  => Service['rspamd'],
            }
        }
    }

    postfix::lookup::database { '/etc/postfix/header_checks':
        content => @(EOF),
            # Strip incoming spam headers
            /^X-Spam-Score:.*/			IGNORE
            | EOF
    }

    if $verp_config {
        postfix::master { 'wiki-verp-bounce-handler/unix':
            chroot       => 'n',
            unprivileged => 'n',
            # The command must not have a trailing newline, so we chomp it off
            command      => epp(
                'profile/postfix/mx/verp_cmd.epp',
                {
                    'post_connect_server' => $verp_config['post_connect_server'],
                    'bounce_post_url'     => $verp_config['bounce_post_url'],
                }
            ).chomp,
        }
    }

    file { '/etc/postfix/aliases':
        ensure => directory,
        mode   => '0755',
    }

    $domain_aliases_generic.each |$domain| {
        postfix::lookup::database { "/etc/postfix/aliases/virtual-${domain}":
            content => epp(
                'profile/postfix/mx/generic_aliases.epp',
                { domain => $domain }
            )
        }
    }
    $domain_aliases.each |$domain, $virtual_aliases| {
        postfix::lookup::database { "/etc/postfix/aliases/virtual-${domain}":
            content => epp(
                'profile/postfix/mx/virtual-aliases.epp',
                { 'virtual_aliases' => $virtual_aliases }
            ),
        }
    }
    $static_transport_maps.each |$name, $data| {
        postfix::lookup::database { "/etc/postfix/transport-${name}":
            content => $data['content']
        }
    }
}