Dormiu bem, Cinderela? Tomara, porque o bicho vai pegar agora. É nessa parte da série que vamos configurar todo o serviço de emails e isso vai doer.

Como todos os componentes necessários aqui precisam funcionar de modo completamente integrado, não é possível fazer a coisa aos poucos. Quer dizer, até é, mas fica tão complexo por causa das idas e vindas nos arquivos de configuração que é insano tentar manter a coerência. O jeito mais simples é fazer tudo de uma vez. Mas não se preocupe, vou explicar tudo direitinho na próxima parte. Agora é só configuração mesmo.

Todas os arquivos de configuração apresentados abaixo são completos, exceto quando especificado o contrário. O conteúdo deles deve substituir integralmente os arquivos originais, mas é claro que você precisa alterar os dados que são específicos ao seu ambiente, tipo nome do servidor, senhas e os caminhos para os certificados e chaves.

Sem mais delongas, ao trabalho!

Postfix

Evidentemente, o primeiro a ser configurado é o MTA. E vamos na ordem que os componentes se integram até o final.

Conteúdo do arquivo /etc/postfix/master.cf:

#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
# This is the regular incoming mail service on port 25.
#  Used by non secure and secure (via STARTTLS) incoming mail featuring:
#  - Postscreen overload protection (includes DNSBL);
#  - SpamAssassin filter.
smtp      inet  n       -       n       -       1       postscreen
tlsproxy  unix  -       -       n       -       0       tlsproxy
dnsblog   unix  -       -       n       -       0       dnsblog
smtpd     pass  -       -       n       -       -       smtpd
  -o content_filter=spamd
#
# This is the regular mail submission service on port 587.
#   Used for secure (via STARTTLS) email submission by MUAs.
#   Features DKIM message signature on outgoing mail.
submission  inet  n     -       n       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_etrn_restrictions=reject
  -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
  -o content_filter=dksign:[127.0.0.1]:10027
  -o receive_override_options=no_address_mappings
  -o milter_macro_daemon_name=ORIGINATING
#
# This are default Postfix services.
pickup    unix  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
tlsmgr    unix  -       -       n       1000?   1       tlsmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       n       -       -       smtp
relay     unix  -       -       n       -       -       smtp
  -o smtp_helo_timeout=5
  -o smtp_connect_timeout=5
showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
retry     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
anvil     unix  -       -       n       -       1       anvil
scache    unix  -       -       n       -       1       scache
# ====================================================================
# These are the required external services integration.
#
# SpamAssassin service.
spamd     unix  -       n       n       -       -       pipe
  flags=Rq user=spamd argv=/usr/bin/spamc -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}
#
# DKIM service.
#
# Service for sending messages TO the DKIM signing proxy for signing.
#   Note: we allow "4" simultaneous deliveries here; high-volume sites may
#     want a number higher than 4.
#   Note: the smtp_discard_ehlo_keywords option requires Postfix 2.2 or
#     better. Leave it off if your version does not support it.
dksign    unix  -       -       n       -       4       smtp
  -o smtp_send_xforward_command=yes
  -o smtp_discard_ehlo_keywords=8bitmime,starttls
#
# Service for accepting signed messages FROM the DKIM signing proxy.
127.0.0.1:10028 inet  n  -      n       -       10      smtpd
  -o content_filter=
  -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks
  -o smtpd_helo_restrictions=
  -o smtpd_client_restrictions=
  -o smtpd_sender_restrictions=
  -o smtpd_recipient_restrictions=permit_mynetworks,reject
  -o mynetworks=127.0.0.0/8
  -o smtpd_authorized_xforward_hosts=127.0.0.0/8

Conteúdo do arquivo /etc/postfix/main.cf:

# General Postfix settings
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = yes
inet_interfaces = all
inet_protocols = ipv4
mailbox_command =
  /usr/libexec/dovecot/deliver -c
  /etc/dovecot/conf.d/01-mail-stack-delivery.conf -m "${EXTENSION}"
mailbox_size_limit = 0
readme_directory = no
recipient_delimiter = +
relayhost =

# Server identity settings
myhostname = mail.exemplo.com
myorigin = $mydomain
mydestination = localhost, localhost.$mydomain
mynetworks = 127.0.0.0/8 172.16.1.0/24
smtpd_banner = $myhostname ESMTP

# SASL settings
smtpd_sasl_auth_enable = yes
smtpd_sasl_authenticated_header = yes
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_type = dovecot

# IMPORTANT!
#   relay_domains should be empty to prevent your server from becoming a
#   spam relay!
relay_domains =

# SMTPD restritcions settings
smtpd_delay_reject = yes
smtpd_helo_required = yes
smtpd_helo_restrictions =
  permit_mynetworks,
  permit_sasl_authenticated,
  check_helo_access hash:/etc/postfix/helo_access
  # Due to crap DNS/RDNS configuration made by morons at some ISP services
  #   it's not possible to enable reject_invalid_helo_hostname,
  #   reject_non_fqdn_helo_hostname and reject_unknown_helo_hostname here, as
  #   the required name resolution will fail, leading to 550 errors when
  #   sending mail from MUAs under these dumb networks.
  #   This is particularly true for the NET Virtua.
  permit
smtpd_sender_restrictions =
  permit_mynetworks,
  reject_non_fqdn_sender,
  reject_unknown_sender_domain,
  permit
smtpd_recipient_restrictions =
  reject_unknown_client_hostname,
  reject_unknown_sender_domain,
  reject_unknown_recipient_domain,
  reject_unauth_pipelining,
  permit_mynetworks,
  permit_sasl_authenticated,
  reject_unauth_destination,
  reject_invalid_hostname,
  reject_non_fqdn_sender,
  permit

# Dealing with rejection: use permanent 550 errors to stop retries
unknown_address_reject_code = 550
unknown_hostname_reject_code = 550
unknown_client_reject_code = 550

# TLS settings
tls_random_source = dev:/dev/urandom

# Custom smtp TLS settings
smtp_tls_loglevel = 1
smtp_tls_note_starttls_offer = yes
smtp_tls_security_level = may
smtp_tls_protocols = !SSLv2
smtp_tls_cert_file = /etc/ssl/private/certificate.crt
smtp_tls_key_file = /etc/ssl/private/certificate.key
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

# Custom smtpd TLS settings
smtpd_tls_loglevel = 1
smtpd_tls_auth_only = yes
smtpd_tls_ciphers = high
smtpd_tls_security_level = may
smtpd_tls_protocols = !SSLv2
smtpd_tls_received_header = yes
smtpd_tls_cert_file = /etc/ssl/private/certificate.crt
smtpd_tls_key_file = /etc/ssl/private/certificate.key
smtpd_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtpd_tls_dh1024_param_file = /etc/ssl/private/dhparam.pem
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache

# Customized Dovecot and virtual user-specific settings
home_mailbox = Maildir/
message_size_limit = 40000000
virtual_transport = lmtp:unix:private/dovecot-lmtp

# ViMbAdmin related settings
virtual_minimum_uid = 5000
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
virtual_mailbox_base = /var/mail/vmail
virtual_mailbox_domains = mysql:/etc/postfix/mysql/virtual_domains_maps.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql/virtual_mailbox_maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql/virtual_alias_maps.cf
virtual_transport = lmtp:unix:private/dovecot-lmtp

# Other custom mail server settings
default_destination_concurrency_limit = 5
disable_vrfy_command = yes
relay_destination_concurrency_limit = 1

# Postsreen spam prevention
postscreen_greet_action = enforce
postscreen_dnsbl_action = enforce
postscreen_access_list = permit_mynetworks
postscreen_dnsbl_sites =
  zen.spamhaus.org,
  b.barracudacentral.org,
  bl.spamcop.net

Conteúdo do arquivo /etc/postfix/helo_access:

exemplo.com       REJECT  Get lost, you liar!
mail.exemplo.com  REJECT  Get lost, you liar!

Conteúdo do arquivo /etc/aliases:

#
# Sample aliases file. Install in the location as specified by the
# output from the command "postconf alias_maps". Typical path names
# are /etc/aliases or /etc/mail/aliases.
#
#       >>>>>>>>>>      The program "newaliases" must be run after
#       >> NOTE >>      this file is updated for any changes to
#       >>>>>>>>>>      show through to Postfix.
#

# Person who should get root's mail. Don't receive mail as root!
root:           eumesmo@exemplo.com

# Basic system aliases -- these MUST be present
MAILER-DAEMON:  postmaster
postmaster:     root

# General redirections for pseudo accounts
bin:            root
daemon:         root
named:          root
nobody:         root
uucp:           root
www:            root
ftp-bugs:       root
postfix:        root

# Put your local aliases here.

# Well-known aliases
manager:        root
dumper:         root
operator:       root
abuse:          postmaster

# trap decode to catch security attacks
decode:         root

Agora rode:

# newaliases
# postmap /etc/postfix/helo_access
# mkdir -p /etc/postfix/mysql

Conteúdo do arquivo /etc/postfix/mysql/virtual_alias_maps.cf:

user = vimbadmin
password = <sena fodona do vimbadmin>
hosts = localhost
dbname = vimbadmin
query = SELECT goto FROM alias WHERE address = '%s' AND active = '1'

Conteúdo do arquivo /etc/postfix/mysql/virtual_domains_maps.cf:

user = vimbadmin
password = <sena fodona do vimbadmin>
hosts = localhost
dbname = vimbadmin
query = SELECT domain FROM domain WHERE domain = '%s' AND backupmx = '0' AND active = '1'

Conteúdo do arquivo /etc/postfix/mysql/virtual_mailbox_maps.cf:

user = vimbadmin
password = <sena fodona do vimbadmin>
hosts = localhost
dbname = vimbadmin
table = mailbox
select_field = maildir
where_field = username

Conteúdo do arquivo /etc/postfix/mysql/virtual_transport_maps.cf:

user = vimbadmin
password = <sena fodona do vimbadmin>
hosts = localhost
dbname = vimbadmin
table = domain
select_field = transport
where_field = domain
additional_conditions = and backupmx = '0' and active = '1'

Feche a configuração do Postfix com:

# chmod 500 /etc/postfix/mysql
# chmod 400 /etc/postfix/mysql/virtual_*

Dovecot

Chegou a vez do Dovecot.

Conteúdo do arquivo /etc/dovecot/dovecot.conf:

## Dovecot configuration file

## Main settings
shutdown_clients = yes
default_login_user = dovenull
protocols = lmtp imap sieve
mail_plugins = quota
mail_home = /var/mail/vmail/%d/%n
mail_location = maildir:/var/mail/vmail/%d/%n:LAYOUT=fs
auth_username_chars = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-_@

## SSL settings (match Postfix)
ssl = required
ssl_cert = </etc/ssl/private/certificate.crt
ssl_key = </etc/ssl/private/certificate.key
ssl_client_ca_dir = /etc/ssl/certs
ssl_cipher_list = ALL:!EXPORT:!LOW:!MEDIUM:+RC4:@STRENGTH
ssl_dh_parameters_length = 2048

## IMAP settings
service imap-login {
  # Disable insecure IMAP listener
  inet_listener imap {
    address = 127.0.0.1
    port = 0
  }
  # Enable secure IMAP listener over IPV4 only, default port (993)
  inet_listener imaps {
    address = *
  }
}

# IMAP restrictions
protocol imap {
  mail_max_userip_connections = 15
  mail_plugins = $mail_plugins quota imap_quota
  imap_client_workarounds = delay-newmail tb-extra-mailbox-sep
}

## POP3 settings
# There's no POP3 settings because it's disabled.

## LMTP settings
lmtp_save_to_detail_mailbox = yes
service lmtp {
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
    user = postfix
    group = postfix
    mode = 0600
  }
}
protocol lmtp {
  postmaster_address = postmaster@exemplo.com
  mail_plugins = $mail_plugins quota sieve
  quota_full_tempfail = no
  deliver_log_format = msgid=%m: %$
  rejection_reason = Your message to <%t> was automatically rejected: %n%r
}

## Authentication settings
auth_mechanisms = plain login

# Database backend for authentication for LMTP and Postfix
passdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}
# Combine passdb and userdb backends for LMTP
userdb {
  driver = prefetch
}
# The userdb below is used only by LDA and quota
userdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}

# Mailboxes are virtual
userdb {
  driver = static
  args = uid=vmail gid=vmail home=/var/mail/vmail/%d/%n
}

# Log all failed authentication attempts
auth_verbose=yes

# Postfix smtp-auth
service auth {
  unix_listener /var/spool/postfix/private/auth {
    mode = 0600
    user = postfix
    group = postfix
  }
  unix_listener auth-userdb {
    mode = 0600
    user = vmail
  }
  user = dovecot
}

## Quota settings
# Default quotas (ViMbAdmin takes care of this)
plugin {
  quota_rule = *:storage=1G
  quota_rule2 = Trash:storage=+100M
  quota_rule3 = Sent:storage=+100M
}
# Quota warnings
plugin {
  quota_warning = storage=95%% quota-warning 95 %u
  quota_warning2 = storage=80%% quota-warning 80 %u
}
service quota-warning {
  executable = script /usr/local/bin/quota-warning
  user = vmail
  unix_listener quota-warning {
    user = vmail
  }
}
# Enable per user quota
plugin {
  quota = maildir:User quota
}

## Sieve settings
plugin {
  sieve = ~/.dovecot.sieve
  sieve_dir = ~/sieve
  sieve_before = /var/mail/vmail/sieve-before
  sieve_after = /var/mail/vmail/sieve-after
  recipient_delimiter = +
}

# Enable ManageSieve listener to IPv4 only, default port (4190)
service managesieve-login {
  inet_listener sieve {
    address = *
  }
  service_count = 1
}
protocol sieve {
  managesieve_max_line_length = 65536
  managesieve_implementation_string = dovecot
}

## Default mailboxes settings
namespace inbox {
  inbox = yes
  # These mailboxes are widely used and could perhaps be created automatically
  mailbox Enviadas {
    special_use = \Sent
    auto = subscribe
  }
  mailbox Lixo {
    special_use = \Trash
    auto = subscribe
  }
  mailbox Rascunhos {
    special_use = \Drafts
    auto = subscribe
  }
  mailbox Spam {
    special_use = \Junk
    auto = subscribe
  }
}

# Temporary IMAP stuff for gmail migration
#imapc_host = imap.gmail.com
#imapc_port = 993
#imapc_ssl = imaps
#imapc_features = rfc822.size
#imapc_features = $imapc_features fetch-headers
#imapc_master_user = user@gmail.com
#imapc_password = secret
#imapc_user = %u
#mail_prefetch_count = 20

Conteúdo do arquivo /etc/dovecot/dovecot-sql.conf.ext:

# Backend settings
driver = mysql
connect = host=localhost user=vimbadmin password=<sena fodona do vimbadmin> dbname=vimbadmin
default_pass_scheme = SHA512-CRYPT

# Backend query for LMTP and Postfix
password_query = \
SELECT username AS user, password AS password, \
       homedir AS home, maildir AS mail, \
       concat('*:bytes=', quota) AS quota_rule, uid, gid \
FROM   mailbox \
WHERE  username = '%Lu' AND active = '1' \
AND    ( access_restriction = 'ALL' OR LOCATE( access_restriction, '%Us' ) > 0 )

# Backend query for LDA and quota
user_query = \
SELECT homedir AS home, maildir AS mail, \
       concat('*:bytes=', quota) as quota_rule, uid, gid \
FROM   mailbox \
WHERE  username = '%u'

# Backend query for doveadm
iterate_query = \
SELECT username \
FROM   mailbox \
WHERE  active = '1'

Conteúdo do arquivo /usr/local/bin/quota-warning:

#!/bin/sh

PERCENT=$1
USER=$2

cat << EOF | /usr/lib/dovecot/dovecot-lda -d $USER -o "plugin/quota=maildir:User quota:noenforcing"
From: naoresponda@exemplo.com
Subject: [AVISO] Sua caixa de correio está quase cheia!

Sua caixa de correio está $PERCENT% cheia.

Você precisa apagar algumas mensagens do servidor.

IMPORTANTE: não ignore esta mensagem, pois se sua caixa
de correio atingir 100%, você deixará de receber novas
mensagens.

Atenciosamente,

Servidor de Correio
exemplo.com

EOF

E pra fechar o Dovecot, rode:

# chown -R vmail:dovecot /etc/dovecot
# chmod 440 /etc/dovecot/dovecot-sql.conf.ext
# chmod 755 /usr/local/bin/quota-warning

DKIMproxy

Comece removendo os arquivos de exemplo do DKIMproxy.

# rm -rf /etc/dkimproxy/*.example

Conteúdo do arquivo /etc/dkimproxy/dkimproxy_in.conf:

# specify what address/port DKIMproxy should listen on
listen    127.0.0.1:10025

# specify what address/port DKIMproxy forwards mail to
relay     127.0.0.1:10026

Conteúdo do arquivo /etc/dkimproxy/dkimproxy_out.conf:

# specify what address/port DKIMproxy should listen on
listen    127.0.0.1:10027

# specify what address/port DKIMproxy forwards mail to
relay     127.0.0.1:10028

# specify signature rules file
sender_map /etc/dkimproxy/sender_map

# specify action on error
reject_error 1

Conteúdo do arquivo /etc/dkimproxy/sender_map:

exemplo.com dkim(s=mail,d=exemplo.com,c=relaxed/relaxed,a=rsa-sha256,key=/etc/dkimproxy/exemplo.com_dkim_private.key)

E pra encerrar com o DKIMproxy, precisamos gerar o par de chaves privada e pública e protegê-las.

# openssl genrsa -out exemplo.com_dkim_private.key 1024
# openssl rsa -in exemplo.com_dkim_private.key -pubout -out exemplo.com_dkim_public.key
# chown dkim /etc/dkimproxy/*.key
# chmod 400 /etc/dkimproxy/*.key

SpamAssassin

E por último, o assassino de spam. Aliás, adoro o nome desse software!

Conteúdo do arquivo /etc/spamassassin.conf:

# Change to one to enable spamd
ENABLED=1

# Default paths
SAHOME="/var/lib/spamassassin"
SAGLOBALCFGPATH="/etc/mail/spamassassin"

# Options
# See man spamd for possible options. The -d option is automatically added.
OPTIONS="-x --max-children 5 --helper-home-dir ${SAHOME} -u spamd -g spamd --siteconfigpath ${SAGLOBALCFGPATH}"

# Pid file
# Where should spamd write its PID to file? If you use the -u or
# --username option above, this needs to be writable by that user.
# Otherwise, the init script will not be able to shut spamd down.
PIDFILE="/var/run/spamd.pid"

Conteúdo do arquivo /etc/mail/spamassassin/init.pre:

# This is the right place to customize your installation of SpamAssassin.
#
# See 'perldoc Mail::SpamAssassin::Conf' for details of what can be
# tweaked.
#
# This file contains plugin activation commands for plugins included
# in SpamAssassin 3.0.x releases.  It will not be installed if you
# already have a file in place called "init.pre".
#
# There are now multiple files read to enable plugins in the
# /etc/mail/spamassassin directory; previously only one, "init.pre" was
# read.  Now both "init.pre", "v310.pre", and any other files ending in
# ".pre" will be read.  As future releases are made, new plugins will be
# added to new files, named according to the release they're added in.
###########################################################################

# RelayCountry - add metadata for Bayes learning, marking the countries
# a message was relayed through
#
# Note: This requires the Geo::IP Perl module
#
loadplugin Mail::SpamAssassin::Plugin::RelayCountry

# URIDNSBL - look up URLs found in the message against several DNS
# blocklists.
#
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL

# Hashcash - perform hashcash verification.
#
loadplugin Mail::SpamAssassin::Plugin::Hashcash

# SPF - perform SPF verification.
#
loadplugin Mail::SpamAssassin::Plugin::SPF

Conteúdo do arquivo /etc/mail/spamassassin/local.cf:

# This is the right place to customize your installation of SpamAssassin.
#
# See 'perldoc Mail::SpamAssassin::Conf' for details of what can be
# tweaked.
#
# Only a small subset of options are listed below
#
###########################################################################

#   Add [***SPAM***] to the Subject header of spam e-mails
#
rewrite_header Subject [***SPAM***]

#   Save spam messages as a message/rfc822 MIME attachment instead of
#   modifying the original message (0: off, 2: use text/plain instead)
#
# report_safe 1

#   Set which networks or hosts are considered 'trusted' by your mail
#   server (i.e. not spammers)
#
trusted_networks 172.16.1

#   Set file-locking method (flock is not safe over NFS, but is faster)
#
lock_method flock

#   Set the threshold at which a message is considered spam (default: 5.0)
#
required_score 3.0

#   Use Bayesian classifier (default: 1)
#
# use_bayes 1

#   Bayesian classifier auto-learning (default: 1)
#
# bayes_auto_learn 1

#   Set headers which may provide inappropriate cues to the Bayesian
#   classifier
#
bayes_ignore_header X-Bogosity
bayes_ignore_header X-Spam-Flag
bayes_ignore_header X-Spam-Status

#   Some shortcircuiting, if the plugin is enabled
#
ifplugin Mail::SpamAssassin::Plugin::Shortcircuit
#
#   default: strongly-whitelisted mails are *really* whitelisted now, if the
#   shortcircuiting plugin is active, causing early exit to save CPU load.
#   Uncomment to turn this on
#
shortcircuit USER_IN_WHITELIST       on
shortcircuit USER_IN_DEF_WHITELIST   on
shortcircuit USER_IN_ALL_SPAM_TO     on
shortcircuit SUBJECT_IN_WHITELIST    on

#   the opposite; blacklisted mails can also save CPU
#
shortcircuit USER_IN_BLACKLIST       on
shortcircuit USER_IN_BLACKLIST_TO    on
shortcircuit SUBJECT_IN_BLACKLIST    on

#   if you have taken the time to correctly specify your "trusted_networks",
#   this is another good way to save CPU
#
shortcircuit ALL_TRUSTED             on

#   and a well-trained bayes DB can save running rules, too
#
# shortcircuit BAYES_99                spam
# shortcircuit BAYES_00                ham

endif # Mail::SpamAssassin::Plugin::Shortcircuit

# Force global Bayesian databases instead of per-user
#
bayes_path /var/lib/spamassassin/.spamassassin/bayes
bayes_file_mode 0666

## Set Pyzor & Razor config file paths
#
razor_config /var/lib/spamassassin/.razor/razor-agent.conf
pyzor_options --homedir /var/lib/spamassassin/.pyzor

Conteúdo do arquivo /etc/mail/spamassassin/spamc.conf:

# spamc global configuration file

# connect to localhost
-d 127.0.0.1

# max message size for scanning = 5MB
-s 5242880

# enable safe failover
-f

Conteúdo do arquivo /etc/mail/spamassassin/v320.pre:

# This is the right place to customize your installation of SpamAssassin.
#
# See 'perldoc Mail::SpamAssassin::Conf' for details of what can be
# tweaked.
#
# This file was installed during the installation of SpamAssassin 3.2.0,
# and contains plugin loading commands for the new plugins added in that
# release.  It will not be overwritten during future SpamAssassin installs,
# so you can modify it to enable some disabled-by-default plugins below,
# if you so wish.
#
# There are now multiple files read to enable plugins in the
# /etc/mail/spamassassin directory; previously only one, "init.pre" was
# read.  Now both "init.pre", "v310.pre", and any other files ending in
# ".pre" will be read.  As future releases are made, new plugins will be
# added to new files, named according to the release they're added in.
###########################################################################

# Check - Provides main check functionality
#
loadplugin Mail::SpamAssassin::Plugin::Check

# HTTPSMismatch - find URI mismatches between href and anchor text
#
loadplugin Mail::SpamAssassin::Plugin::HTTPSMismatch

# URIDetail - test URIs using detailed URI information
#
loadplugin Mail::SpamAssassin::Plugin::URIDetail

# Shortcircuit - stop evaluation early if high-accuracy rules fire
#
loadplugin Mail::SpamAssassin::Plugin::Shortcircuit

# Plugins which used to be EvalTests.pm
# broken out into separate plugins
loadplugin Mail::SpamAssassin::Plugin::Bayes
loadplugin Mail::SpamAssassin::Plugin::BodyEval
loadplugin Mail::SpamAssassin::Plugin::DNSEval
loadplugin Mail::SpamAssassin::Plugin::HTMLEval
loadplugin Mail::SpamAssassin::Plugin::HeaderEval
loadplugin Mail::SpamAssassin::Plugin::MIMEEval
loadplugin Mail::SpamAssassin::Plugin::RelayEval
loadplugin Mail::SpamAssassin::Plugin::URIEval
loadplugin Mail::SpamAssassin::Plugin::WLBLEval

# VBounce - anti-bounce-message rules, see rules/20_vbounce.cf
#
loadplugin Mail::SpamAssassin::Plugin::VBounce

# Rule2XSBody - speedup by compilation of ruleset to native code
#
# loadplugin Mail::SpamAssassin::Plugin::Rule2XSBody

# ASN - Look up the Autonomous System Number of the connecting IP
# and create a header containing ASN data for bayes tokenization.
# See plugin's POD docs for usage info.
#
# loadplugin Mail::SpamAssassin::Plugin::ASN

# ImageInfo - rules to match metadata of image attachments
#
loadplugin Mail::SpamAssassin::Plugin::ImageInfo

Os demais arquivos /etc/mail/spamassassin/v*.pre não recebem nenhuma alteração.

Precisamos criar o diretório onde o SpamAssassin vai armazenar seus arquivos de trabalho.

# mkdir /var/lib/spamassassin/.spamassassin
# chown spamd:spamd /var/lib/spamassassin

Agora crie os diretórios para os filtros globais do Sieve que tratam o spam.

# mkdir -p /var/mail/vmail/sieve-after/
# mkdir -p /var/mail/vmail/sieve-before/

Conteúdo do arquivo /var/mail/vmail/sieve-before/globalspam.sieve:

require ["envelope", "fileinto", "imap4flags", "regex"];

# Discard spam higher than level 10
if header :contains "X-Spam-Level" "**********" {
  discard;
  stop;
}

# Send spam higher than level 3 to junk folder
if header :contains "X-Spam-Level" "***" {
  fileinto "Spam";
  setflag "\\seen";
}

Hora de atualizar o banco de dados com os spammers filhos duma puta.

# sa-update

Se você ver um erro Error Opening file /usr/share/GeoIP/GeoIPv6.dat, ignore-o. Não usamos IPv6, logo o banco de dados do GeoIP com endereços IPv6 não é importante. Se você rodar o sa-update novamente, o erro terá desaparecido.

O sa-update rodará semanalmente pelo cron do sistema. Isso é feito pelo arquivo /etc/cron.weekly/sa-update.sh instalado pelo pacote do SpamAssassin. Se você quiser uma frequencia diária, mova-o para /etc/cron.daily.

Continuando com a configuração do SpamAssassin, inicializamos os utilitários de suporte.

# mkdir /var/lib/spamassassin/.razor
# mkdir /var/lib/spamassassin/.pyzor
# pyzor --homedir /var/lib/spamassassin/.pyzor discover
# razor-admin -home=/var/lib/spamassassin/.razor -register
# razor-admin -home=/var/lib/spamassassin/.razor -create
# razor-admin -home=/var/lib/spamassassin/.razor -discover
# vi /var/lib/spamassassin/.razor/razor-agent.conf

Faça essa alteração:

--- razor-agent.conf.default    2015-05-16 20:05:52.488478020 -0300
+++ razor-agent.conf    2015-05-16 20:06:13.939478020 -0300
@@ -8,6 +8,7 @@
# see razor-agent.conf(5) man page
#

+razorhome              = /var/lib/spamassassin/.razor
debuglevel             = 3
identity               = identity
ignorelist             = 0

Finalizando com o SpamAssassin, rode:

# sievec /var/mail/vmail/sieve-before/
# chown -R vmail:vmail /var/mail/vmail/sieve-*
# chown -R spamd:spamd /var/lib/spamassassin

Inicializando

É chegado o grande momento! O seu servidor vai virar um carteiro! Mas antes, precisamos ajustar algumas coisinhas.

Edite o arquivo /etc/rc.d/rc.dkimproxy e faça estas alterações:

--- rc.dkimproxy.default        2015-05-16 19:35:04.606799770 -0300
+++ rc.dkimproxy        2015-05-16 19:35:52.585799770 -0300
@@ -80,7 +80,7 @@
                ;;

        start)
-               test -f $DKIMPROXY_IN_CFG && $0 start-in || exit $?
+               #test -f $DKIMPROXY_IN_CFG && $0 start-in || exit $?
                test -f $DKIMPROXY_OUT_CFG && $0 start-out || exit $?
                ;;

@@ -109,7 +109,7 @@
                ;;

        stop)
-               test -f $DKIMPROXY_IN_CFG && $0 stop-in || exit $?
+               #test -f $DKIMPROXY_IN_CFG && $0 stop-in || exit $?
                test -f $DKIMPROXY_OUT_CFG && $0 stop-out || exit $?
                ;;

@@ -146,7 +146,7 @@
                ;;

        status)
-               test -f $DKIMPROXY_IN_CFG && $0 status-in || exit $?
+               #test -f $DKIMPROXY_IN_CFG && $0 status-in || exit $?
                test -f $DKIMPROXY_OUT_CFG && $0 status-out || exit $?
                ;;
        *)

Agora edite o arquivo /etc/rc.d/rc.spamd para alterar:

--- rc.spamd.default    2015-05-16 19:37:31.105799770 -0300
+++ rc.spamd    2015-05-16 19:37:53.819799770 -0300
@@ -12,7 +12,7 @@
DESC="SpamAssassin Mail Filter Daemon"
PIDFILE="/var/run/$NAME.pid"
PNAME="spamd"
-DOPTIONS="-d --pidfile=$PIDFILE"
+DOPTIONS="-4 -d --pidfile=$PIDFILE"

KILL="/bin/kill"
KILLALL="/bin/killall"

Neste momento eu recomendo muito que você abra uma nova janela ou aba do terminal, conecte-se no servidor via SSH e monitore o arquivo de log do email, assim:

# tail -f /var/log/maillog

Finalmente, vamos começar a inicializar os serviços. De trás para frente, um por um.

# /etc/rc.d/rc.spamd start

Olhe a saída no /var/log/maillog.

May 16 20:08:51 mail spamd[9060]: logger: removing stderr method
May 16 20:08:55 mail spamd[9062]: spamd: server started on IO::Socket::INET6 [127.0.0.1]:783 (running version 3.4.0)
May 16 20:08:55 mail spamd[9062]: spamd: server pid: 9062
May 16 20:08:55 mail spamd[9062]: spamd: server successfully spawned child process, pid 9064
May 16 20:08:55 mail spamd[9062]: spamd: server successfully spawned child process, pid 9065
May 16 20:08:55 mail spamd[9062]: prefork: child states: IS
May 16 20:08:55 mail spamd[9062]: prefork: child states: II

Se for parecida com isso, tudo certo com o SpamAssassin. Podemos continuar. O próximo é o DKIMproxy.

# /etc/rc.d/rc.dkimproxy start

Esse não tem saída no log. Vamos ter que verificar seu funcionamento de outro modo.

# ss -lp | grep dkim
tcp    LISTEN     0      127          127.0.0.1:10027                 *:*        users:(("dkimproxy.out",9099,4),("dkimproxy.out",9098,4),("dkimproxy.out",9097,4),("dkimproxy.out",9096,4),("dkimproxy.out",9095,4),("dkimproxy.out",9094,4))

Se você ver algo semelhante a isso, DKIMproxy tá bombando também. Próximo: Dovecot.

# /etc/rc.d/rc.dovecot start

Acompanhe o processo pelo maillog. A primeira inicialização do Dovecot é diferente das demais. Você vai ver isso:

May 17 14:02:51 mail dovecot: master: Dovecot v2.2.13 starting up for imap, sieve (core dumps disabled)
May 17 14:02:51 mail dovecot: ssl-params: Generating SSL parameters

Esse processo vai levar um tempo. Em nossa instância t1.micro, pobrinha, coitadinha, isso deve levar cerca de sete minutos. Esse processo é repetido toda semana automaticamente, a menos que você diga para o Dovecot não fazer isso colocando no /etc/dovecot/dovecot.conf o parâmetro ssl_parameters_regenerate = 0, mas eu não recomendo por diminuir a segurança do SSL no Dovecot. Leia a documentação do Dovecot sobre SSL para mais informações.

Uma vez finalizada a geração das chaves SSL do Dovecot, o log segue:

May 17 14:09:52 mail dovecot: ssl-params: SSL parameters regeneration completed

Pronto, o Dovecot está rodando. Vamos verificar?

# ss -ltp | grep dovecot
LISTEN     0      100                     *:sieve                    *:*        users:(("dovecot",20621,15))
LISTEN     0      100                     *:imaps                    *:*        users:(("dovecot",20621,33))
# openssl s_client -connect localhost:993
<Você verá usa saída com muitas informações sobre a conexão segura e no final...>
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE AUTH=PLAIN AUTH=LOGIN] Dovecot ready.
<Digite CTRL-C para fechar a conexão e veja se no /var/log/maillog aparece isso...>
May 17 14:32:51 mail dovecot: imap-login: Disconnected (no auth attempts in 2 secs): user=<>, rip=127.0.0.1, lip=127.0.0.1, TLS: Disconnected, session=<usiBd0oWjgB/AAAB>

Se a sua saída foi semelhante, o Dovecot está tinindo. Finalmente, chegou a vez do Postfix.

# /etc/rc.d/rc.postfix start

O /var/log/maillog deve mostrar:

May 17 14:39:40 mail postfix/postfix-script[20807]: starting the Postfix mail system
May 17 14:39:40 mail postfix/master[20809]: daemon started -- version 2.11.4, configuration /etc/postfix

Verificando:

# ss -ltp | grep master
LISTEN     0      100                     *:submission                  *:*        users:(("master",20809,103))
LISTEN     0      100             127.0.0.1:10028                    *:*        users:(("master",20809,109))
LISTEN     0      100                     *:smtps                    *:*        users:(("master",20809,26))
LISTEN     0      100                     *:smtp                     *:*        users:(("master",20809,13))

Se você está vendo algo parecido com isso, é hora de enviar os primeiros emails de teste. Primeiro um local, para a conta que você criou para você mesmo lá na etapa do ViMbAdmin:

echo "Eu sou fodinha." | mail -s "Own! Meu primeiro email: local <3" -r "root@exemplo.com" eumesmo@exemplo.com

E veja o maillog:

May 17 15:09:28 mail postfix/pickup[21038]: 01F2E56F83: uid=0 from=<root@exemplo.com>
May 17 15:09:28 mail postfix/cleanup[21226]: 01F2E56F83: message-id=<5558d957.iMDgK/81SPDtiMyR%root@exemplo.com>
May 17 15:09:28 mail postfix/qmgr[21039]: 01F2E56F83: from=<root@exemplo.com>, size=450, nrcpt=1 (queue active)
May 17 15:09:28 mail dovecot: lmtp(21234): Connect from local
May 17 15:09:28 mail dovecot: lmtp(21234, eumesmo@exemplo.com): VOr1AljZWFXyUgAAZU03Dg: msgid=<5558d957.iMDgK/81SPDtiMyR%root@exemplo.com>: saved mail to INBOX
May 17 15:09:28 mail postfix/lmtp[21233]: 01F2E56F83: to=<eumesmo@exemplo.com>, relay=mail.exemplo.com[private/dovecot-lmtp], delay=0.1, delays=0.04/0.01/0.01/0.04, dsn=2.0.0, status=sent (250 2.0.0 <eumesmo@exemplo.com> VOr1AljZWFXyUgAAZU03Dg Saved)
May 17 15:09:28 mail dovecot: lmtp(21234): Disconnect from local: Successful quit
May 17 15:09:28 mail postfix/qmgr[21039]: 01F2E56F83: removed

A mensagem deverá estar na sua caixa de correio local, mas não temos um cliente configurado para vê-la ainda. Confira listando o conteúdo de /var/mail/vmail/exemplo.com/eumesmo/new/. Você pode dar um cat nos arquivos dessa pasta também. Eles são meros arquivos de texto, cada um contendo um email prontinho pra ser lido.

Abre parênteses.

Viu como é fácil pra um Google ou Microsoft bisbilhotar todo o conteúdo das suas mensagens? E viu como é fácil para um administrador de sistemas (você no caso) violar a privacidade de alguém? Por isso, lembre-se sempre do mantra do sudo:

Presumimos que você recebeu as instruções de sempre do administrador
de sistema local. Basicamente, resume-se a estas três coisas:

    #1) Respeite a privacidade dos outros.
    #2) Pense antes de digitar.
    #3) Com grandes poderes vêm grandes responsabilidades.

Notou também porque não adianta fazer malabarismos para criptografar um filesystem num ambiente que você não controla? Pois é.

Da próxima vez que você ouvir alguém falando que o serviço de email XPTO é seguro porque criptografa os discos, responda em alto e bom som: GRAN-DES BOS-TA!

E use GPG.

Fecha parênteses.

Agora veja se seu servidor consegue enviar um email para fora. Use uma conta que você tenha em algum serviço na internet.

echo "Eu sou fodão." | mail -s "Own! Meu primeiro email: remoto <3" -r "root@exemplo.com" eumesmo@gmail.com

Confira o maillog:

May 17 15:24:54 mail postfix/pickup[21038]: BB80656F82: uid=0 from=<root@exemplo.com>
May 17 15:24:54 mail postfix/cleanup[21306]: BB80656F82: message-id=<5558dcf6.gFVHtX50SdhjfTvs%root@exemplo.com>
May 17 15:24:54 mail postfix/qmgr[21039]: BB80656F82: from=<root@exemplo.com>, size=453, nrcpt=1 (queue active)
May 17 15:24:55 mail postfix/smtp[21313]: Trusted TLS connection established to aspmx.l.google.com[64.233.186.26]:25: TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)
May 17 15:24:57 mail postfix/smtp[21313]: BB80656F82: to=<eumesmo@gmail.com>, relay=aspmx.l.google.com[64.233.186.26]:25, delay=3.2, delays=0.02/0/1.5/1.7, dsn=2.0.0, status=sent (250 2.0.0 OK 1431970412 d68si10909668qhc.84 - gsmtp)
May 17 15:24:57 mail postfix/qmgr[21039]: BB80656F82: removed

Agora abra esse email na sua conta externa. Se ele não aparecer na caixa de entrada, procure no spam. Isso pode ocorrer agora por conta de coisas que ainda não fizemos no DNS, mas depois não acontecerá mais.

Procure pelos cabeçalhos Received da mensagem (opção 'exibir cabeçalho', 'mostrar original' ou coisa do gênero, conforme o seu cliente de email). Eles deverão se parecer com isso:

Received: by 10.25.84.135 with SMTP id i129csp221947lfb;
          Mon, 18 May 2015 10:33:32 -0700 (PDT)
Received: from mail.exemplo.com (mail.exemplo.com. [54.94.2.1])
          by mx.google.com with ESMTPS id d68si10909668qhc.84.2015.05.18.10.33.30
          for <eumesmo@gmail.com>
          (version=TLSv1.2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
          Mon, 18 May 2015 10:33:31 -0700 (PDT)
Received: by mail.exemplo.com (Postfix, from userid 1000)
          id 192786F90D; Mon, 18 May 2015 14:33:29 -0300 (BRT)

Se essas verificações dos emails enviados batem com o que foi mostrado acima, parabéns, meu prezado ou prezada. Seu servidor de email já está funcionando.

Existem inúmeros tipos de verificar o funcionamento dos serviços relativos a email. Você pode usar este artigo como referência para fazer mais testes.

Ufa, essa foi pauleira! Mas ainda falta um bocado de coisas pro seu servidor novo estar pronto para entrar em produção para enviar e receber emails na internet.

Abra a próxima parte da série em uma nova aba e use essa aqui pra acompanhar o blá, blá, blá. Vou explicar essa quizumba toda que fizemos aqui, uma vez que isso é importante para a segurança do seu sistema. Só depois daremos continuidade às configurações.