[toc] # Configuración de Postfix y PostfixSRS <p style="text-align: justify;"> Vamos a configurar Postfix como servidor de correo y PostfixSRS (Sender Rewriting Scheme) para manejar reenvíos de correos de forma segura. # See /usr/share/postfix/main.cf.dist for a commented, more complete version # Debian specific: Specifying a file name will cause the first # line of that file to be used as the name. The Debian default # is /etc/mailname. #myorigin = /etc/mailname smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu) biff = no # appending .domain is the MUA's job. append_dot_mydomain = no # Uncomment the next line to generate "delayed mail" warnings #delay_warning_time = 4h readme_directory = no # See http://www.postfix.org/COMPATIBILITY_README.html -- default to 3.6 on # fresh installs. compatibility_level = 3.6 # TLS parameters smtpd_tls_cert_file = /etc/ssl/certs/email.ccuellar.test.crt smtpd_tls_key_file = /etc/ssl/private/email.ccuellar.test.key smtpd_use_tls = yes smtpd_tls_auth_only = yes smtp_tls_security_level = may smtpd_tls_security_level = may # Authentication smtpd_sasl_type = dovecot smtpd_sasl_path = private/auth smtpd_sasl_auth_enable = yes smtpd_helo_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unknown_recipient_domain, reject_unlisted_recipient, reject_unauth_destination, reject_rbl_client dul.dnsbl.sorbs.net, reject_rbl_client sbl-xbl.spamhaus.org, reject_rbl_client bl.spamcop.net smtpd_sender_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_sender, reject_unknown_sender_domain smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, defer_unauth_destination myhostname = email.ccuellar.test alias_maps = hash:/etc/aliases alias_database = hash:/etc/aliases mydomain = ccuellar.test myorigin = $mydomain mydestination = $myhostname, localhost.localdomain, localhost relayhost = mynetworks = 10.24.153.0/24, 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 smtp_dns_support_level = enabled mailbox_size_limit = 0 recipient_delimiter = + inet_interfaces = all inet_protocols = all # Handing off local delivery to Dovecot's LMTP, and telling it where to store mail virtual_transport = lmtp:unix:private/dovecot-lmtp # Virtual domains, users, and aliases virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf, mysql:/etc/postfix/mysql-virtual-email2email.cf # Even more Restrictions and MTA params disable_vrfy_command = yes strict_rfc821_envelopes = yes #smtpd_etrn_restrictions = reject #smtpd_reject_unlisted_sender = yes #smtpd_reject_unlisted_recipient = yes smtpd_delay_reject = yes smtpd_helo_required = yes smtp_always_send_ehlo = yes #smtpd_hard_error_limit = 1 smtpd_timeout = 30s smtp_helo_timeout = 15s smtp_rcpt_timeout = 15s smtpd_recipient_limit = 20 minimal_backoff_time = 180s maximal_backoff_time = 3h # Reply Rejection Codes invalid_hostname_reject_code = 550 non_fqdn_reject_code = 550 unknown_address_reject_code = 550 unknown_client_reject_code = 550 unknown_hostname_reject_code = 550 unverified_recipient_reject_code = 550 unverified_sender_reject_code = 550 # More parameters by Sergio unknown_local_recipient_reject_code = 450 bounce_queue_lifetime = 3d # Bounce templates bounce_template_file = /etc/postfix/bounce.cf maximal_queue_lifetime = 4d header_checks = regexp:/etc/postfix/header_checks smtpd_soft_error_limit = 3 smtpd_hard_error_limit = 12 message_size_limit = 20480000 ## Configurar bounce.cf <p style="text-align: justify;"> Ahora vamos a configurar un archivo específico para los mensajes personalizados de respuesta o rebote en Postfix. Creamos el archivo llamado /etc/postfix/bounce.cf y definimos los mensajes según las necesidades del servidor. De esta forma, adaptamos las respuestas de manera más clara y apropiada. sudo vi /etc/postfix/bounce.cf Añadimos: failure_template = <<EOF Charset: UTF-8 From: MAILER-DAEMON (Mail Delivery System) Subject: Servidor de correo: Mensaje no entregado Postmaster-Subject: Postmaster: Mensaje no entregado POR FAVOR, LEA DETENIDAMENTE ESTE MENSAJE. Éste es un mensaje de correo enviado automáticamente por su servidor de correo. No ha sido posible entregar su mensaje a uno o más destinatarios. El mensaje que causó el error está adjunto a este mensaje. EOF delay_template = <<EOF Charset: UTF-8 From: MAILER-DAEMON (Mail Delivery System) Subject: Servidor de correo: Mensaje postpuesto Postmaster-Subject: Postmaster: Mensaje postpuesto POR FAVOR, LEA DETENIDAMENTE ESTE MENSAJE. Este es un mensaje de correo enviado automáticamente por el servidor de correo. . ############################################## # ÉSTE ES SÓLO UN MENSAJE DE AVISO # # NO ES NECESARIO QUE REENVÍE EL MENSAJE. # ############################################## Su mensaje no pudo ser entregado al destinatario después de intentarlo durante $delay_warning_time_hours hora(s). Se seguirá intentando enviar el mensaje hasta que pasen $maximal_queue_lifetime_days días. EOF success_template = <<EOF Charset: UTF-8 From: MAILER-DAEMON (Mail Delivery System) Subject: Servidor de correo: Informe de entrega correcta de mensaje POR FAVOR, LEA DETENIDAMENTE ESTE MENSAJE. Este es un mensaje de correo enviado automáticamente por su servidor de correo. Su mensaje fue entregado correctamente al/a los destinatario/s indicados a continuación. Si el mensaje fue entregado directamente a los destinatarios, no recibirá más notificaciones; en caso contrario, si el mensaje tuviera que pasar por más servidores de correo, es posible que reciba más notificaciones de estos servidores. EOF verify_template = <<EOF Charset: UTF-8 From: MAILER-DAEMON (Mail Delivery System) Subject: Servidor de correo: Informe de estado de entrega de mensaje POR FAVOR, LEA DETENIDAMENTE ESTE MENSAJE. Este es un mensaje de correo enviado automáticamente por su servidor de correo. Adjunto a este mensaje se encuentra el informe de entrega solicitado. EOF ## header_checks <p style="text-align: justify;"> Este archivo se usa para inspeccionar las cabeceras de los correos y registrar información útil, como el asunto o el remitente. sudo vi /etc/postfix/header_checks Añade: # Registramos todos los asuntos de los correos /^subject:/ WARN # Opcional: Registramos otros campos (descomenta si lo necesitas) #/^from:/ WARN #/^to:/ WARN ### Convertir Archivos en Bases de Datos <p style="text-align: justify;"> Postfix no puede leer directamente estos archivos de texto. Necesitamos convertirlos en archivos .db usando el comando postmap. sudo postmap /etc/postfix/header_checks ## Configurar archivos MySQL <p style="text-align: justify;"> Postfix necesita interactuar con la base de datos MySQL para gestionar dominios, usuarios y alias. Crea los siguientes archivos: ### Archivo para dominios virtuales sudo vi /etc/postfix/mysql-virtual-mailbox-domains.cf Añade: user = mailuser password = tu_contraseña hosts = 127.0.0.1 dbname = mailserver query = SELECT 1 FROM virtual_domains WHERE name='%s' AND active='1' ### Archivo para buzones virtuales sudo vi /etc/postfix/mysql-virtual-mailbox-maps.cf Añade: user = mailuser password = tu_contraseña hosts = 127.0.0.1 dbname = mailserver query = SELECT 1 FROM virtual_users WHERE email='%s' AND active='1' ### Archivo para alias virtuales sudo vi /etc/postfix/mysql-virtual-alias-maps.cf Añade: user = mailuser password = tu_contraseña hosts = 127.0.0.1 dbname = mailserver query = SELECT destination FROM virtual_aliases WHERE source='%s' AND active='1' <p style="text-align: justify;"> Por último, configuramos el archivo /etc/postfix/mysql-virtual-email2email.cf, que se encargará de gestionar las verificaciones necesarias de Postfix para los alias. Este paso asegura que el sistema maneje correctamente los alias en el servidor de correo, dejando todo preparado para su funcionamiento. sudo vi /etc/postfix/mysql-virtual-email2email.cf Añade: user = mailuser password = tu_contraseña hosts = 127.0.0.1 dbname = mailserver query = SELECT email FROM virtual_users WHERE email='%s' and active='1' ## Verificar configuraciones MySQL Verifica que Postfix pueda leer los datos de la base de datos: sudo postmap -q user1@ccuellar.test mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf Si el buzón existe, el comando devolverá 1. ## Configurar master.cf <p style="text-align: justify;"> El archivo master.cf es como el "cerebro" de Postfix: controla cómo se inician y funcionan todos los procesos del servidor de correo. Ahora vamos a editarlo para asegurarnos de que todo esté configurado correctamente. sudo cp /etc/postfix/master.cf /etc/postfix/master.cf.orig sudo vi /etc/postfix/master.cf Añade: # # 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) (no) (never) (100) # ========================================================================== smtp inet n - y - - smtpd #smtp inet n - y - 1 postscreen smtps inet n - y - - smtpd -o syslog_name=postfix/smtps -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes -o smtpd_relay_restrictions=permit_sasl_authenticated,reject #smtpd pass - - y - - smtpd #dnsblog unix - - y - 0 dnsblog #tlsproxy unix - - y - 0 tlsproxy # Choose one: enable submission for loopback clients only, or for any client. #127.0.0.1:submission inet n - y - - smtpd submission inet n - y - - smtpd -o syslog_name=postfix/submission -o smtpd_tls_security_level=encrypt -o smtpd_sasl_auth_enable=yes -o smtpd_sasl_type=dovecot -o smtpd_sasl_path=private/auth -o smtpd_relay_restrictions=permit_sasl_authenticated,reject #submission inet n - y - - smtpd # -o syslog_name=postfix/submission # -o smtpd_tls_security_level=encrypt # -o smtpd_sasl_auth_enable=yes # -o smtpd_tls_auth_only=yes # -o local_header_rewrite_clients=static:all # -o smtpd_reject_unlisted_recipient=no # Instead of specifying complex smtpd_<xxx>_restrictions here, # specify "smtpd_<xxx>_restrictions=$mua_<xxx>_restrictions" # here, and specify mua_<xxx>_restrictions in main.cf (where # "<xxx>" is "client", "helo", "sender", "relay", or "recipient"). # -o smtpd_client_restrictions= # -o smtpd_helo_restrictions= # -o smtpd_sender_restrictions= # -o smtpd_relay_restrictions= # -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject # -o milter_macro_daemon_name=ORIGINATING # Choose one: enable submissions for loopback clients only, or for any client. #127.0.0.1:submissions inet n - y - - smtpd #submissions inet n - y - - smtpd # -o syslog_name=postfix/submissions # -o smtpd_tls_wrappermode=yes # -o smtpd_sasl_auth_enable=yes # -o local_header_rewrite_clients=static:all # -o smtpd_reject_unlisted_recipient=no # Instead of specifying complex smtpd_<xxx>_restrictions here, # specify "smtpd_<xxx>_restrictions=$mua_<xxx>_restrictions" # here, and specify mua_<xxx>_restrictions in main.cf (where # "<xxx>" is "client", "helo", "sender", "relay", or "recipient"). # -o smtpd_client_restrictions= # -o smtpd_helo_restrictions= # -o smtpd_sender_restrictions= # -o smtpd_relay_restrictions= # -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject # -o milter_macro_daemon_name=ORIGINATING #628 inet n - y - - qmqpd pickup unix n - y 60 1 pickup cleanup unix n - y - 0 cleanup qmgr unix n - n 300 1 qmgr #qmgr unix n - n 300 1 oqmgr tlsmgr unix - - y 1000? 1 tlsmgr rewrite unix - - y - - trivial-rewrite bounce unix - - y - 0 bounce defer unix - - y - 0 bounce trace unix - - y - 0 bounce verify unix - - y - 1 verify flush unix n - y 1000? 0 flush proxymap unix - - n - - proxymap proxywrite unix - - n - 1 proxymap smtp unix - - y - - smtp relay unix - - y - - smtp -o syslog_name=postfix/$service_name # -o smtp_helo_timeout=5 -o smtp_connect_timeout=5 showq unix n - y - - showq error unix - - y - - error retry unix - - y - - error discard unix - - y - - discard local unix - n n - - local virtual unix - n n - - virtual lmtp unix - - y - - lmtp anvil unix - - y - 1 anvil scache unix - - y - 1 scache postlog unix-dgram n - n - 1 postlogd # # ==================================================================== # Interfaces to non-Postfix software. Be sure to examine the manual # pages of the non-Postfix software to find out what options it wants. # # Many of the following services use the Postfix pipe(8) delivery # agent. See the pipe(8) man page for information about ${recipient} # and other message envelope options. # ==================================================================== # # maildrop. See the Postfix MAILDROP_README file for details. # Also specify in main.cf: maildrop_destination_recipient_limit=1 # #maildrop unix - n n - - pipe # flags=DRXhu user=vmail argv=/usr/bin/maildrop -d ${recipient} # # ==================================================================== # # Recent Cyrus versions can use the existing "lmtp" master.cf entry. # # Specify in cyrus.conf: # lmtp cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4 # # Specify in main.cf one or more of the following: # mailbox_transport = lmtp:inet:localhost # virtual_transport = lmtp:inet:localhost # # ==================================================================== # # Cyrus 2.1.5 (Amos Gouaux) # Also specify in main.cf: cyrus_destination_recipient_limit=1 # #cyrus unix - n n - - pipe # flags=DRX user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user} # # ==================================================================== # # Old example of delivery via Cyrus. # #old-cyrus unix - n n - - pipe # flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user} # # ==================================================================== # # See the Postfix UUCP_README file for configuration details. # uucp unix - n n - - pipe flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient) # # Other external delivery methods. # #ifmail unix - n n - - pipe # flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient) #bsmtp unix - n n - - pipe # flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient #scalemail-backend unix - n n - 2 pipe # flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension} #mailman unix - n n - - pipe # flags=FRX user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py ${nexthop} ${user} ## Configurar PostfixSRS ### Instalar PostfixSRS sudo apt update sudo apt install postsrsd Configurar Postfix para usar SRS sudo vi /etc/postfix/main.cf Añade al final: #PostfixSRS sender_canonical_maps = tcp:localhost:10001 sender_canonical_classes = envelope_sender recipient_canonical_maps = tcp:localhost:10002 recipient_canonical_classes = envelope_recipient,header_recipient Reinicia los servicios: sudo systemctl restart postfix sudo systemctl restart postsrsd ## Comprobar que todo funciona ### Verificar sintaxis de Postfix: sudo postfix check sudo systemctl restart postfix sudo systemctl status postfix 🤗 --- ## [Índice de secciones aquí](https://hackmd.io/@ccuellar/rJ73y6FpJe) ## [👈Anterior sección](https://hackmd.io/@ccuellar/ryMRcAFT1g) 😄 [Siguiente sección 👉](https://hackmd.io/@ccuellar/BJJyhAYpye)