Postfix

Hace unos años monté un servidor de correo, después de muchos dolores de cabeza conseguí hacerlo funcionar y mitigar el problema del Spam. Debido a que las guias que seguí en su momento ya no estan disponibles y que adapté la configuración a mi gusto me dispongo a hacer un resumen de los pasos a seguir.

A lo largo de los años he montado varios servidores de correo. En este articulo voy a mostrar la configuración que utilizo actualmente, intentando explicar en detalle para que sirve cada parametro de la configuración. Esta guía esta basada en una recopilación de muchas otras, algunas de ellas están enlazadas mas adelante, pero otras han dejado de estar disponibles.

Referencias

Complete Virtual Mail Server

http://www.postfix.org/BASIC_CONFIGURATION_README.html

http://www.postfix.org/postconf.5.html

instalar sasl postfix postfixadmin dovecot y filtros de spam en debian

http://sefirosweb.es/ubuntu/mailserver/

http://en.redinskala.com/postfix-maillog-interpretation/

stay-off-of-blacklists-limit-postfix-recipients

https://mecsa.jrc.ec.europa.eu/en/postfix

DNS

Aunque no es estrictamente obligatorio, es mas que recomendable configurar correctamente la resolución DNS del servidor de correo, ademas de configurar la resolución inversa de la IP (PTR).

  • Registro A para mail.example.com apuntando a la ip del servidor.
  • Registro PTR para la ip del servidor resolviendo a mail.example.com , esta se suele modificar en la configuración del hosting o VPS.
  • Ademas, los registros MX, A y TXT/SPF correspondientes a los dominios que queramos recibir y enviar correo.

Usuario vmail

Al utilizar dominios y usuarios virtuales, todo el correo se almacenará en el directorio /var/mail/vhosts/, por lo que se crea un usuario y grupo para administrar este directorio.

groupadd -g 5000 vmail
useradd -m -d /var/vmail -s /bin/false -u 5000 -g vmail vmail
addgroup postfix vmail
addgroup dovecot vmail

mkdir -v /var/mail/vhosts/
chown -R vmail:vmail /var/mail/vhosts/
chmod 2770 /var/mail/vhosts/

Database MySQL

Para gestionar dominios, usuarios y demás datos de postfix se utiliza una base de datos MySQL. Necesitaremos tener instalado mysql-server.

Necesitamos crear el usuario y la base de datos mail. Después de esto creamos las tablas con el archivo postfix.sql.

CREATE DATABASE IF NOT EXISTS `mail`;
GRANT USAGE ON *.* TO 'mail'@'%' IDENTIFIED BY 'P4$$w0rD';
GRANT ALL PRIVILEGES ON `mail`.* TO 'mail'@'localhost';
FLUSH PRIVILEGES;
mysql -u mail -p mail < postfix.sql

Las tablas utilizadas son las siguientes:

  • domains
  • users
  • forwardings: Redirecciones de correo.
  • transport
  • relay domains
  • relay_recipients
  • whitelist
  • whitelist_recipient
  • blacklist
  • blacklist_recipient

  • quota

Instalar Postfix

postfix/smtpd - This is typically the SMTP daemon process for handling incoming mail and routing to the appropriate internal location.

postfix/smtp - This is typically the SMTP daemon process for delivering mail out to the world.

Se instalan los siguientes paquetes:

apt install postfix postfix-mysql

Hacemos un backup de la configuración original.

cp -v /etc/postfix/main.cf /etc/postfix/main.cf.orig
cp -v /etc/postfix/master.cf /etc/postfix/master.cf.orig

main.cf

Este archivo controla los parámetros de configuración de Postfix. Los parámetros no especificados toman su valor por defecto.

Cambiamos el mensaje en el banner de conexión

#smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_banner = $myhostname

Configuración de SSL usando certificados de letsencrypt

# TLS parameters
smtpd_tls_cert_file=/etc/letsencrypt/live/mail.example.com/fullchain.pem
smtpd_tls_key_file=/etc/letsencrypt/live/mail.example.com/privkey.pem
smtpd_tls_CAfile=/etc/letsencrypt/live/mail.example.com/chain.pem

smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

Hardening SSL

# Hardening SSL configuration
smtp_tls_security_level = may
smtp_tls_loglevel = 1
# only offer authentication after STARTTLS
smtpd_tls_auth_only = yes
# Disable SSL compression
#tls_ssl_options = NO_COMPRESSION
# Disable SSLv2 and SSLv3 leaving TLSv1, TLSv1.1 and TLSv1.2 enabled.
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3
smtpd_tls_protocols = !SSLv2 !SSLv3
# Configure the allowed cipher list
smtpd_tls_mandatory_ciphers=high
tls_high_cipherlist=EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA384:EECDH+aRSA+SHA256:EECDH:+CAMELLIA256:+AES256:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!ECDSA:CAMELLIA256-SHA:AES256-SHA:CAMELLIA128-SHA:AES128-SHA
# Enable EECDH key exchange for Forward Security
smtpd_tls_eecdh_grade=ultra

# Trusted CA
smtp_tls_CApath = /etc/ssl/certs
#smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

smtpd_tls_received_header = yes

Configuramos el hostname del servidor en myhostname

myhostname = mail.example.com

#mydestination = $myhostname, mail.example.com, mail, localhost.localdomain, localhost
mydestination = localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128

# Forzar el uso de ipv4, si queremos enviar correos desde ipv6 debermos configurar los registros DNS asociados con IPv6.
inet_protocols = ipv4


# Conexion      smtpd_client_restrictions
# HELO/EHLO     smtpd_helo_restrictions
# MAIL FROM     smtpd_sender_restrictions
# RCPT TO       smtpd_recipient_restrictions

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination


smtpd_sender_restrictions =
        # Permitir Usuarios autenticados
        permit_sasl_authenticated,
        # Rechazar mails provenientes de nuestros dominios sin autenticar, SPAM (comprobar si con las otras medidas esta no seria necesaria.)
        check_sender_access proxy:mysql:/etc/postfix/mysql-sender_access.cf
        permit


smtpd_recipient_restrictions =
        # Rechazar "recipient" en blacklist [No enviar correo local a direcciones de la blacklist ]
        check_recipient_access mysql:/etc/postfix/mysql-blacklist.cf,
        # Rechazar "recipient" en blacklist_recipient [Direcciones locales desactivadas, util cuando usamos catch-all]
        check_recipient_access mysql:/etc/postfix/mysql-blacklist-recipient.cf,
        # Omitir comprobaciones para direcciones locales en la Whitelist (Explicar en que caso usar estas direcciones)
        check_recipient_access mysql:/etc/postfix/mysql-whitelist-recipient.cf

        # Rechazar si RCPT TO no es FQDN
        reject_non_fqdn_recipient,
        # Rechazar si MAIL FROM no es FQDN
        reject_non_fqdn_sender,
        # Rechazar si el dominio del RCPT TO no existe
        reject_unknown_recipient_domain,
        # Rechazar si el dominio del MAIL FROM no existe
        reject_unknown_sender_domain,
        # Comprobar sender=usuario SASL (smtpd_sender_login_maps)
        reject_sender_login_mismatch,
        # Permitir IP's locales
        permit_mynetworks,
        # Permitir Usuarios autenticados
        permit_sasl_authenticated,
        # Rechazar si el domino del RCPT TO no coincide con mydestination, virtual_maps, relay_domains, inet_interfaces
        reject_unauth_destination,

        #
        reject_unauth_pipelining,
        # Rechazar si HELO es incorrecto
        reject_invalid_helo_hostname,
        # Rechazar si HELO no es FQDN
        reject_non_fqdn_helo_hostname,
        # Rechazar si el dominio de HELO no existe. Esta regla es demasiado agresiva, ya que muchos sysadmin no configuran bien el HELO de sus servidores.
        #reject_unknown_helo_hostname,

        # Reject the request when the client IP address has no address->name mapping.
        reject_unknown_reverse_client_hostname

        # Rechazar destinatarios no validos
        reject_unlisted_recipient
        # Permitir WHITELIST, saltarse la comprobacion de policyd-weight
        check_sender_access mysql:/etc/postfix/mysql-whitelist.cf,
        # Rechazar "sender" en blacklist [ No recibir correo de la blacklist ]
        check_sender_access mysql:/etc/postfix/mysql-blacklist.cf,
        # Rechazar "helo" en blacklist [No recibir correo de la blacklist ]
        check_helo_access mysql:/etc/postfix/mysql-blacklist.cf,
        # Rechazar "IP/Host" en blacklist
        check_client_access mysql:/etc/postfix/mysql-blacklist.cf,

        ## Rechazar si el dominio de HELO no existe (despues de aplicar whitelisting). Esta regla es demasiado agresiva, ya que muchos sysadmin no configuran bien el HELO de sus servidores.
        reject_unknown_helo_hostname,

        # PolicySPF - Rechazar SPF no valido
        check_policy_service unix:private/policyspf,
        # Policyd-weight
        check_policy_service inet:127.0.0.1:12525,

        permit


smtpd_data_restrictions =
        reject_multi_recipient_bounce


unverified_recipient_reject_code = 550
unverified_sender_reject_code = 550
reject_code = 550
unknown_address_reject_code = 550
unknown_client_reject_code = 550
unknown_hostname_reject_code = 550

# Limite mensaje
message_size_limit = 10240000

# Aunque Postfix decida en cualquier fase que no va a aceptar el mensaje,
# deja pasar por todas las fases y emite el error al final de la fase RCPT TO
# se puede anular con smtpd_delay_reject = no.
# En ultimas versiones por defecto es "yes"
smtpd_delay_reject = yes
# Desactivar comando VRFY
disable_vrfy_command = yes
# Requerir HELO
smtpd_helo_required = yes

# Deshabilitar DSN (+info)
smtpd_discard_ehlo_keywords = silent-discard VRFY ETRN DSN

# Dominios virtuales
virtual_alias_domains =

# Limite 10 receptores por correo
smtpd_recipient_limit = 10
smtpd_client_connection_rate_limit = 10
smtpd_client_message_rate_limit = 5
smtpd_client_recipient_rate_limit = 10

bounce_queue_lifetime = 2h
maximal_queue_lifetime = 2h

# Tabla con permisos de sender
smtpd_sender_login_maps = mysql:/etc/postfix/mysql-smtpd_sender_login_maps.cf

# Tabla de relay de salida
relay_domains = $mydestination, proxy:mysql:/etc/postfix/mysql-virtual_relay_domains.cf

# Tabla con forwardings y cuentas
virtual_alias_maps = proxy:mysql:/etc/postfix/mysql-virtual_forwardings.cf, proxy:mysql:/etc/postfix/mysql-virtual_email.cf

# Tabla con dominios virtuales
virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domains.cf
# Tabla con ruta del mailbox de usuarios
virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailboxes.cf

# Ruta principal para mailbox (no usado actualmente)
#virtual_mailbox_base = /var/mail/vhosts
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000

# Tabla con reenvios
transport_maps = proxy:mysql:/etc/postfix/mysql-virtual_transports.cf

# Tabla con usuarios relay
relay_recipient_maps = proxy:mysql:/etc/postfix/mysql-virtual_relay_recipients.cf

##virtual_create_maildirsize = yes
##virtual_maildir_extended = yes
# Tabla con limite quota
virtual_mailbox_limit_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailbox_limit_maps.cf
##virtual_mailbox_limit_override = yes
##virtual_maildir_limit_message = "El buzón del usuario está lleno."
##virtual_overquota_bounce = yes
# virtual_mailbox_size_limit = proxy:mysql:/etc/postfix/mysql-virtual_mailbox_limit_maps.cf
# virtual_mailbox_extended = yes

# VERIFICAR
proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $virtual_mailbox_limit_maps $smtpd_sender_restrictions
#$sender_bcc_maps $recipient_bcc_maps
append_at_myorigin = no


virtual_transport = lmtp:unix:private/dovecot-lmtp

# Postfix SMTP SASL authentication.
smtpd_sasl_type=dovecot
smtpd_sasl_path=private/auth

# Desactivar autenticacion como cliente
smtp_sasl_auth_enable = no

# Activar autenticacion como servidor
smtpd_sasl_auth_enable = yes
#smtpd_sasl_security_options = noanonymous # (default)
smtpd_sasl_local_domain = $mydomain
#Enable interoperability with remote SMTP clients that implement an obsolete version of the AUTH command
broken_sasl_auth_clients = yes



# Filtrar mail con amavis
#comentar receive_override_options si se desactiva amavis
content_filter = smtp-amavis:[127.0.0.1]:10024
receive_override_options = no_address_mappings


# Evita los correos duplicados cuando nos envian un correo multiple al alias y/o al usuario
enable_original_recipient = no

# No mostrar detalles en caso de usuario desconocido
show_user_unknown_table_name = no

smtpd_hard_error_limit = 1
#smtputf8_enable = yes

master.cf (cambios)

submission inet n       -       -       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
#  -o content_filter=smtp-amavis:[127.0.0.1]:10026

smtps     inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
#  -o content_filter=smtp-amavis:[127.0.0.1]:10026

Postfix-MySQL

mysql-virtual_domains.cf

user = mail
password = P4$$w0rD
dbname = mail
hosts = 127.0.0.1
query = SELECT `domain` AS `virtual` FROM `domains` WHERE `domain`='%s' LIMIT 1

Test: postmap -q example.com mysql:/etc/postfix/mysql-virtual_domains.cf

mysql-virtual_email.cf

user = mail
password = P4$$w0rD
dbname = mail
hosts = 127.0.0.1
query = SELECT `email` FROM `users` WHERE `email`='%s' AND `active`='1' AND `receive`='1'

Test: postmap -q user@example.com mysql:/etc/postfix/mysql-virtual_email.cf

mysql-virtual_forwardings.cf

user = mail
password = P4$$w0rD
dbname = mail
hosts = 127.0.0.1
query = SELECT `destination` FROM `forwardings` WHERE `active`='1' and `source`='%s'

Test postmap -q alias@example.com mysql:/etc/postfix/mysql-virtual_forwardings.cf

Install Dovecot

apt install dovecot-core dovecot-mysql dovecot-imapd dovecot-pop3d dovecot-lmtpd dovecot-sieve

Backup config

cp -v /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.orig
cp -v /etc/dovecot/conf.d/10-mail.conf /etc/dovecot/conf.d/10-mail.conf.orig
cp -v /etc/dovecot/conf.d/10-auth.conf /etc/dovecot/conf.d/10-auth.conf.orig
cp -v /etc/dovecot/dovecot-sql.conf.ext /etc/dovecot/dovecot-sql.conf.ext.orig
cp -v /etc/dovecot/conf.d/10-master.conf /etc/dovecot/conf.d/10-master.conf.orig
cp -v /etc/dovecot/conf.d/10-ssl.conf /etc/dovecot/conf.d/10-ssl.conf.orig

/etc/dovecot/conf.d/auth-sql.conf.ext (sin cambios)

passdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}
userdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}

/etc/dovecot/dovecot-sql.conf.ext (se puede sobrescribir este archivo)

driver = mysql
connect = host=127.0.0.1 dbname=mail user=mail password=P4$$w0rD
default_pass_scheme = CRYPT
#default_pass_scheme = SHA512-CRYPT
password_query = SELECT `email` AS `user`, `password` FROM `users` WHERE `email`='%u' LIMIT 1
user_query = SELECT CONCAT('/var/mail/vhosts/',SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'') AS `home`, '5000' AS `uid`, '5000' AS `gid`, concat('*:storage=', quota) AS `quota_rule` FROM `users` WHERE `email`='%u' LIMIT 1
iterate_query = SELECT `email` AS `user` FROM `users`

/etc/dovecot/conf.d/10-master.conf (descomentar lineas para habilitar IMAP y POP3, añadir lineas de LMTP)

service imap-login {
  inet_listener imap {
    port = 143
  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }
}

service pop3-login {
  inet_listener pop3 {
    port = 110
  }
  inet_listener pop3s {
    port = 995
    ssl = yes
  }
}


service lmtp {
  unix_listener lmtp {
  }

  unix_listener /var/spool/postfix/private/dovecot-lmtp {
     mode = 0600
     user = postfix
     group = postfix
  }
}


service auth {
  unix_listener auth-userdb {

  }

  # Postfix smtp-auth
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
    user = postfix
    group = postfix
  }
}

/etc/dovecot/conf.d/10-ssl.conf

ssl = required
ssl_cert = </etc/letsencrypt/live/mail.example.com/cert.pem
ssl_key = </etc/letsencrypt/live/mail.example.com/privkey.pem
ssl_ca = </etc/letsencrypt/live/mail.example.com/chain.pem
#ssl_protocols = !SSLv2 !SSLv3 #No se puede deshabilitar SSLv2 en las ultimas versiones porque ya no existe
ssl_protocols = !SSLv3
#ssl_cipher_list = ALL:!LOW:!SSLv2:!MID:!EXP:!aNULL
ssl_cipher_list = ALL:!LOW:!MID:!EXP:!aNULL

/etc/dovecot/conf.d/10-mail.conf (añadir lo siguiente)

mail_location = maildir:/var/mail/vhosts/%d/%n
mail_privileged_group = mail

/etc/dovecot/conf.d/10-auth.conf (descomentar y añadir, comentar auth-system)

disable_plaintext_auth = yes
auth_mechanisms = plain login
#!include auth-system.conf.ext
!include auth-sql.conf.ext

SPF

apt install postfix-policyd-spf-python

Este filtro rechaza automaticamente todos los emails que no cumplan con la politica SPF. man policyd-spf.conf

/etc/postfix/master.cf (Añadir)

policyspf  unix  -       n       n       -       -       spawn
    user=nobody argv=/usr/bin/policyd-spf

Policy-Weight

Policy-Weight es un filtro para postfix que calcula una puntuación para cada remitente en base a su reputación en listas negras y otros factores.

apt install policyd-weight

Esta aplicación corre como servicio en 127.0.0.1:12525

DKIM

https://blog.unlugarenelmundo.es/2014/03/03/evita-que-tus-correos-sean-marcados-como-spam-usando-registros-ptr-spf-y-dkim/

DMARC

https://blog.unlugarenelmundo.es/2014/05/28/evita-que-tus-correos-sean-marcados-como-spam-y-ii-registros-dmarc/

Amavis

https://help.ubuntu.com/community/PostfixAmavisNew

https://wiki.centos.org/HowTos/Amavisd

https://dipakgajjar.com/amavisd-new-clamav-spamassassin-postfix-centos-6-7/

https://wiki.apache.org/spamassassin/IntegratedInPostfixWithAmavis

apt install amavisd-new clamav-daemon spamassassin

Decoders: apt install p7zip p7zip-full

/etc/postfix/master.cf

# Amavis OUT
smtp-amavis unix -      -       n     -       2  smtp
    -o smtp_data_done_timeout=1200
    -o smtp_send_xforward_command=yes
    -o disable_dns_lookups=yes
    -o max_use=20

# Amavis IN
127.0.0.1:10025 inet n  -       -     -       -  smtpd
    -o content_filter=
    -o local_recipient_maps=
    -o relay_recipient_maps=
    -o smtpd_restriction_classes=
    -o smtpd_delay_reject=no
    -o smtpd_client_restrictions=permit_mynetworks,reject
    -o smtpd_helo_restrictions=
    -o smtpd_sender_restrictions=
    -o smtpd_recipient_restrictions=permit_mynetworks,reject
    -o smtpd_data_restrictions=reject_unauth_pipelining
    -o smtpd_end_of_data_restrictions=
    -o mynetworks=127.0.0.0/8
    -o smtpd_error_sleep_time=0
    -o smtpd_soft_error_limit=1001
    -o smtpd_hard_error_limit=1000
    -o smtpd_client_connection_count_limit=0
    -o smtpd_client_connection_rate_limit=0
    -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks
    # No se puede poner "no_addres_mappings" porque no funcionarian los forwardings al estar ya puesto en la config de postfix.
    #-o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_milters,no_address_mappings
    -o local_header_rewrite_clients=
    -o smtpd_milters=
    -o local_recipient_maps=
    -o relay_recipient_maps=

/etc/amavis/conf.d

$pax='pax';

$inet_socket_port = [10024, 10026];

$interface_policy{'10026'} = 'BYPASS';

$policy_bank{'BYPASS'} = {  # those configured to send mail to port 10026
   originating => 1,  # Since amavisd-new 2.5.0
                      # declare that mail was submitted by our smtp client
   bypass_spam_checks_maps   => [1],  # don't spam-check this mail
   bypass_banned_checks_maps => [1],  # don't banned-check this mail
   bypass_header_checks_maps => [1],  # don't header-check this mail
};

$myhostname = "mail.example.com";

@lookup_sql_dsn = (
    ['DBI:mysql:database=mail;host=127.0.0.1;port=3306',
     'mail',
     'P4$$w0rD']);

$sql_select_policy = 'SELECT `domain` FROM `domains` WHERE CONCAT("@",domain) IN (%k)
UNION SELECT `domain` FROM `relay_domains` WHERE CONCAT("@",domain) IN (%k)';
#

$sa_spam_subject_tag = '***SPAM*** ';
$sa_tag_level_deflt  = -5; # add spam info headers if at, or above that level
$sa_tag2_level_deflt = 6.31; # add 'spam detected' headers at that level
$sa_kill_level_deflt = 6.31;
$sa_dsn_cutoff_level = 7;   # spam level beyond which a DSN is not sent

$sa_quarantine_cutoff_level = 7.5; # spam level beyond which quarantine is off

$sa_mail_body_size_limit = 400*1024; # don't waste time on SA if mail is larger
$sa_local_tests_only = 0; # only tests which do not require internet access?

$final_virus_destiny      = D_DISCARD;  # (data not lost, see virus quarantine)
$final_banned_destiny     = D_DISCARD;   # D_REJECT when front-end MTA
$final_spam_destiny       = D_PASS;
$final_bad_header_destiny = D_PASS;     # False-positive prone (for spam)

$X_HEADER_LINE = "";

Fail2ban

apt install fail2ban

/etc/fail2ban/jail.local

Change enabled=false to true in postfix and dovecot.

[postfix]

enabled  = true
port     = smtp,ssmtp,submission
filter   = postfix
logpath  = /var/log/mail.log


[dovecot]

enabled = true
port    = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s
filter  = dovecot
logpath = /var/log/mail.log

(cambia en la ultima versión) https://askubuntu.com/questions/783190/fail2ban-0-9-0-enabling-jails

DKIM

(Pendiente)

Añadir datos SQL

INSERT INTO `domains` (`domain_id`, `domain`) VALUES (NULL, 'example.com');
INSERT INTO `users` (`user_id`, `domain_id`, `email`, `password`, `quota`, `active`, `send`, `receive`) VALUES (NULL, '1', 'user@example.com', ENCRYPT('test'), NULL, '1', '1', '1');
INSERT INTO `forwardings` (`transport_id`, `domain_id`, `source`, `destination`, `active`) VALUES (NULL, '1', 'user2@example.com', 'user@example.com', '1');

# Explicar para que sirve 'transport'
INSERT INTO `transport` (`domain`, `transport`, `active`) VALUES ('hotmail.com', 'relay:mx2.example.com', '1');

INSERT INTO `whitelist` (`id`, `mail`, `date`) VALUES (NULL, 'cni.es', CURRENT_TIMESTAMP);

Log mail.log con lineas duplicadas

Comentar la linea en el archivo /etc/rsyslog.conf

#mail.*                         -/var/log/mail.log

service rsyslog restart

Archivos

MySQL

postfix.sql

CREATE TABLE IF NOT EXISTS `domains` (
  `domain_id` INT NOT NULL AUTO_INCREMENT,
  `domain` varchar(50)  NOT NULL,
  PRIMARY KEY (`domain_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` INT NOT NULL AUTO_INCREMENT,
  `domain_id` INT NOT NULL,
  `email` varchar(80) NOT NULL,
  `password` varchar(32) NOT NULL,
  `quota` int(10) DEFAULT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '1',
  `send` tinyint(1) NOT NULL DEFAULT '1',
  `receive` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `email` (`email`),
  FOREIGN KEY (`domain_id`) REFERENCES domains(`domain_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `forwardings` (
  `transport_id` INT NOT NULL AUTO_INCREMENT,
  `domain_id` INT NOT NULL,
  `source` varchar(80) NOT NULL,
  `destination` varchar(80) NOT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`transport_id`),
  FOREIGN KEY (`domain_id`) REFERENCES domains(`domain_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `transport` (
  `domain` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
  `transport` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
  `active` tinyint(1) NOT NULL DEFAULT '1',
  UNIQUE KEY `domain` (`domain`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE IF NOT EXISTS `relay_domains` (
  `domain_id` int(11) NOT NULL AUTO_INCREMENT,
  `domain` varchar(50) COLLATE utf8_bin NOT NULL,
  `active` tinyint(1) NOT NULL,
  PRIMARY KEY (`domain_id`),
  KEY `domain` (`domain`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `relay_recipients` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `email` varchar(100) COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE IF NOT EXISTS `whitelist` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `mail` varchar(150) COLLATE utf8_bin NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mail` (`mail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `whitelist_recipient` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `mail` varchar(150) COLLATE utf8_bin NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mail` (`mail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `blacklist` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `mail` varchar(150) COLLATE utf8_bin NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mail` (`mail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `blacklist_recipient` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `mail` varchar(150) COLLATE utf8_bin NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mail` (`mail`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

Cambiar pass sed -i ‘s/P4$$w0rD/newpassword/g’ mysql-*

Categorías:

Actualizado: