[2024-feb-29] Sad news: Eric Layton aka Nocturnal Slacker aka vtel57 passed away on Feb 26th, shortly after hospitalization. He was one of our Wiki's most prominent admins. He will be missed.

Welcome to the Slackware Documentation Project

¡Esta es una revisión vieja del documento!


En proceso de traducción. Victor

Creación de un servidor de correo virtual con Postfix, Dovecot y MySQL

Este artículo muestra cómo construir y configurar un servidor de correo virtual seguro utilizando Postfix, Dovecot y MySQL en una plataforma Slackware 14.1.

Debido a que las plataformas compiladas e instaladas pueden ser muy diferentes, y la configuración puede parecer compleja para aquellos que no están familiarizados con postfix, dovecot y mysql, he organizado este artículo de una manera que espero le ayude a separar y probar tareas individuales, sin perderse en el camino!

El artículo fue escrito como resultado de mi propia experiencia en la configuración de un servidor de correo virtual en mi propio VPS de Linode.com, pero he evitado muchas referencias abiertas a las herramientas o configuraciones específicas de Linode.com, por lo que debería ser fácilmente adaptado para cualquier plataforma. La única referencia de Linode.com será enumerar algunos paquetes adicionales que serán necesarios para su base Slackware 14.1.

Nuestro servidor de correo virtual de destino

Lo que entendemos por servidor de correo virtual es que los buzones de correo no necesitan corresponder a las cuentas de usuario en la máquina, sino que pertenecen a usuarios virtuales definidos en la base de datos. Esto permite servir el correo para muchos buzones de correo y en múltiples dominios.

¡La ejecución de un servidor de correo virtual puede no ser la mejor opción para muchos casos de uso, ya que presenta algunos riesgos y requisitos de seguridad adicionales! En particular, ¡no debe ejecutar un servidor de correo virtual en una máquina que proporcione cuentas de inicio de sesión para múltiples usuarios! ¡Un MTA de correo virtual solo debe configurarse en un host bien seguro dedicado al propósito!

Por seguridad, configuraremos Dovecot para proporcionar autenticación para Postfix a través de SASL en base a las credenciales del buzón de correo virtual. También requeriremos TLS/SSL para el acceso de todos los usuarios y, por supuesto, ¡nos aseguraremos de que no se convierta en un envío de correo no deseado abierto!

Para comenzar, solo necesita una instalación básica de Slackware 14.1, con parches de seguridad actualizados, en particular para bash, openssl, openssl-solibs y gnutls.

Si está instalando en un VPS de Linode.com con su base Slackware 14.1, deberá agregar algunos paquetes faltantes además de mariadb, dovecot y postfix. Durante mi propia configuración (que incluye fail2ban, no se trata aquí) necesitaba agregar: db48, cyrus-sasl, libaio, pidentd y sqlite

Hay muchas partes en nuestro servidor de correo virtual que se cubrirán en secciones separadas. Pero la mejor manera de organizarlos todos es con un gráfico simple que muestre los principales componentes instalados y sus relaciones. La figura 1, a continuación, representa una vista general del sistema de correo virtual de destino descrito en este artículo.

Figura 1: Descripción general del correo electrónico virtual

Instalación de componentes

La lista de elementos principales de la Figura 1 proporciona una lista de verificación de tareas pendientes para instalar los componentes principales de nuestro servidor de correo virtual.

Siga los enlaces que se enumeran aquí y complete cuidadosamente cada elemento . Cuando termine, tendrá un servidor de correo virtual seguro y en funcionamiento, que luego podrá ser configurado para satisfacer sus necesidades específicas.

DNS, MX Records and Hosts File

In order for your mail server to be found on a wider network, you must correctly configure the DNS and MX records for your host's domain. These records are external to the host itself and so are outside the scope of this article.

In general, you will need to configure the DNS zone file for your domain and create MX records within that zone file which point to your mail server. If your target system is a hosted platform such as a VPS, then the provider will supply the tools and guides for doing so. You must also be sure to provide a PTR record for reverse address lookup, many systems will not receive mail from hosts which they cannot identify.

An internet search will also produce many helpful resources, which I will leave to you as an exercise.

In addition, on the host machine itself, you will need to be sure that the hosts file includes the corresponding lines for your IP address, hostname, FQDN and domain as they are used by postfix and dovecot for resolving the disposition of messages:

cat /etc/hosts
...
127.0.0.1       localhost
127.0.0.1       localhost.localdomain   localhost
xx.xx.xx.xx     darkstar
xx.xx.xx.xx     darkstar.my-domain.com   my-domain.com

Startup and Troubleshooting

After you have completed each of the major tasks listed above from Figure 1, you should be ready to startup your virtual mail server.

You should verify each aspect of the system separately and in order, so that you can resolve any potential problems methodically.

If something seems to not work as expected, take the time to understand why and avoid the urge to just “try this or that” - you will only corrupt and compromise your system by that method!

First, lets start dovecot and postfix and look for any error messages - there really should be none.

chmod +x /etc/rc.d/rc.dovecot
/etc/rc.d/rc.dovecot start
Firing up dovecot

tail /var/log/maillog
...
Feb 16 01:48:45 darkstar dovecot: master: Dovecot v2.2.13 starting up for imap, pop3, lmtp (core dumps disabled)

If you receive any other messages or errors from the shell or the log file, investigate and fix them before continuing!

Next let's do the same for postfix:

chmod +x /etc/rc.d/rc.postfix
/etc/rc.d/rc.postfix start
postfix/postfix-script: starting the Postfix mail system

tail /var/log/maillog
...
Feb 16 01:51:55 darkstar postfix/postfix-script[6931]: starting the Postfix mail system
Feb 16 01:51:55 darkstar postfix/master[6933]: daemon started -- version 2.11.3, configuration /etc/postfix

Same as before, if you receive any other messages or errors from the shell or the log file, investigate and fix them before continuing!

Next, with postfix and dovecot running, use netstat to confirm that things are as expected:

netstat -plntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
...
tcp        0      0 0.0.0.0:587             0.0.0.0:*               LISTEN      6933/master
tcp        0      0 0.0.0.0:465             0.0.0.0:*               LISTEN      6933/master
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN      6933/master
tcp        0      0 0.0.0.0:993             0.0.0.0:*               LISTEN      6843/dovecot
tcp        0      0 0.0.0.0:995             0.0.0.0:*               LISTEN      6843/dovecot

You should see master (the postfix master process) listening on ports 25, 465 and 587, and dovecot on ports 993 and 995.

You should also verify that your firewall rules are in fact loaded - you do not want to run your mail server without the firewall, even briefly!

iptables -L
...

If all looks good so far, check whether you can connect to the mailserver from the outside world. We should use port 25 for this, but many ISPs block port 25 so it is difficult to get a reliable test result. So see if you can connect to port 465 or 587 using telnet.

Type the line “telnet my-domain.com 465” and hit enter key:

telnet my-domain.com 465
Trying xx.xx.xx.xx...
Connected to my-domain.com.
Escape character is '^]'.
220 darkstar.my-domain.com ESMTP Postfix

# Use Ctl-] quit to end the connection

If you do not receive a response similar to that shown then it is likely that your host is not reachable from your location.

Most commonly this will be due to a bad DNS record or incorrect nameserver settings at the domain registrar. Verify that these are correct.

It can also result from incorrect or conflicting firewall rules. Remember that iptables rules are evaluated from top to bottom and the first match determines the fate of each request. Look carefully to see if any pre-existing rules may be dropping your requests before they reach the intended rule!

If it connects then you are ready to set up an inbox in a mail client like Thunderbird and give it a final test!

When you create an inbox in your mail client, remember to use the secure imap and pop3 connections - we are not listening on the insecure service ports. You must use the full mailbox name, name@my-domain.com, as the user name, and the password must be that used in the MySQL INSERT or UPDATE queries which created the virtual user.

And remember - although this configuration is as secure as the machine it is running on, it is still a minimal configuration!

You will also definitely want to install fail2ban (available from SBo). You will also want a spam filtering application and possibly even a virus detection program for incoming and outgoing email.

You should think carefully about your own specific requirements, read the postfix and dovecot documentation thoroughly, subscribe to their mail lists and learn to interpret the logs. Watch the system carefully and take it offline at the first sign of compromise!

Running an email server on the internet is definitely not a click and forget past time!

Sources

 es:howtos:network_services:postfix_dovecot_mysql ()