/etc/postfix/main.cf
.
mail.falcot.com
. Esta es la única pregunta que se hace de forma predeterminada, pero la configuración que genera no es lo suficientemente completa para las necesidades de Falcot, por lo que los administradores deben ejecutar dpkg-reconfigure
para poder personalizar más parámetros.
localhost
, pero el dominio principal falcot.com
tiene que ser agregado de forma manual. En general se deberían añadir todos los dominios para los que esta máquina debe ejercer como servidor MX; en otras palabras, todos los dominios para los cuales el DNS anuncie que esta máquina aceptará correo. Esta información acaba siendo escrita en la variable mydestination
del archivo de configuración principal de Postfix — /etc/postfix/main.cf
.
192.168.0.0/16
al valor predeterminado. Si no se realiza esta pregunta durante la instalación, la variable de configuración correspondiente es mynetworks
, tal y como puede verse en el ejemplo siguiente.
procmail
. This tool allows users to sort their incoming email according to rules stored in their ~/.procmailrc
file. Both Postfix and Exim4 suggest procmail by default, but there are alternatives like maildrop or Sieve filters.
Ejemplo 11.1. Archivo /etc/postfix/main.cf
inicial
# 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 (Debian/GNU) 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 2 on # fresh installs. compatibility_level = 2 # TLS parameters smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key smtpd_use_tls=yes smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache # See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for # information on enabling SSL in the smtp client. smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination myhostname = mail.falcot.com alias_maps = hash:/etc/aliases alias_database = hash:/etc/aliases myorigin = /etc/mailname mydestination = mail.falcot.com, falcot.com, localhost.localdomain, localhost relayhost = mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 192.168.0.0/16 mailbox_size_limit = 0 recipient_delimiter = + inet_interfaces = all inet_protocols = all
virtual_alias_domains
y establezca un archivo de traducción de direcciones en la variable virtual_alias_maps
.
virtual_alias_domains = falcotsbrand.com virtual_alias_maps = hash:/etc/postfix/virtual
/etc/postfix/virtual
describe la relación con una sintaxis muy sencilla: cada línea contiene dos campos separados por espacios en blanco; el primer campo es el nombre del alias y el segundo es una lista de las direcciones de correo a las que se redirigen. La sintaxis especial @dominio.com
abarca todos los alias pertenecientes a un dominio.
webmaster@falcotsbrand.com jean@falcot.com contact@falcotsbrand.com laure@falcot.com, sophie@falcot.com # The alias below is generic and covers all addresses within # the falcotsbrand.com domain not otherwise covered by this file. # These addresses forward email to the same user name in the # falcot.com domain. @falcotsbrand.com @falcot.com
/etc/postfix/virtual
the postfix table /etc/postfix/virtual.db
needs to be updated using sudo postmap /etc/postfix/virtual
.
virtual_mailbox_domains
y hacer referencia a un archivo de asociación de casillas en virtual_mailbox_maps
. El parámetro virtual_mailbox_base
contiene el directorio en el que se almacenarán todas las casillas.
virtual_mailbox_domains = falcot.org virtual_mailbox_maps = hash:/etc/postfix/vmailbox virtual_mailbox_base = /var/mail/vhosts
virtual_uid_maps
(o virtual_gid_maps
respectivamente) hace referencia al archivo que contiene la asociación entre las direcciones de correo y el usuario de sistema (o grupo respectivamente) «dueño» de la casilla correspondiente. Para lograr que todas las casillas pertenezcan al mismo usuario/grupo, la sintaxis static:5000
asigna un UID/GID fijo (aquí el valor 5000).
/etc/postfix/vmailbox
es bastante directo: dos campos separados con espacios en blanco. El primer campo es una dirección de correo en alguno de los dominios virtuales y el segundo campo es la ubicación de la casilla asociada (relativa al directorio especificado en virtual_mailbox_base). Si el nombre de la casilla finaliza con una barra (/
), se almacenarán los correos en formato maildir; de lo contrario se utilizará el formato mbox tradicional. El formato maildir utiliza un directorio completo para almacenar una casilla, cada mensaje individual es almacenado en un archivo separado. Por el otro lado, en el formato mbox se almacena toda la casilla en un archivo y cada línea que comience con «From
(From
es seguido por un espacio) indica el comienzo de un nuevo mensaje.
# Se almacena el correo de Jean como maildir, con # un archivo por correo en un directorio dedicado jean@falcot.org falcot.org/jean/ # Se almacena el correo de Sophie en un archivo # «mbox» tradicional con todos los correos # en un solo archivo sophie@falcot.org falcot.org/sophie
soft_bounce = yes
directive. By prepending a reject-type directive with warn_if_reject
only a log message will be recorded instead of rejecting the request.
smtpd_client_restrictions
controla qué máquinas pueden comunicarse con el servidor de correo.
Ejemplo 11.2. Restricciones basadas en la dirección del cliente
smtpd_client_restrictions = permit_mynetworks, warn_if_reject reject_unknown_client_hostname, check_client_access hash:/etc/postfix/access_clientip, reject_rhsbl_reverse_client dbl.spamhaus.org, reject_rhsbl_reverse_client rhsbl.sorbs.net, reject_rbl_client zen.spamhaus.org, reject_rbl_client dnsbl.sorbs.net
permit_mynetworks
directive, used as the first rule, accepts all emails coming from a machine in the local network (as defined by the mynetworks
configuration variable).
warn_if_reject
modifier to the reject_unknown_client
directive: this modifier turns the rejection into a simple warning recorded in the logs. The administrators can then keep an eye on the number of messages that would be rejected if the rule were actually enforced, and make an informed decision later if they wish to enable such enforcement.
/etc/postfix/access_clientip
. Se consideran confiables aquellos servidores en la lista blanca y, por lo tanto, sus correos no pasarán por las siguientes reglas de filtrado.
HELO
(or EHLO
) command, followed by the name of the sending email server. Checking the validity of this name can be interesting. To fully enforce the restrictions listed in smtpd_helo_restrictions
the smtpd_helo_required
option needs to be enabled. Otherwise clients could skip the restrictions by not sending any HELO
/EHLO
command.
Ejemplo 11.3. Restricciones en el nombre anunciado con EHLO
smtpd_helo_required = yes smtpd_helo_restrictions = permit_mynetworks, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, warn_if_reject reject_unknown_helo_hostname, check_helo_access hash:/etc/postfix/access_helo, reject_rhsbl_helo multi.surbl.org
permit_my_networks
permite que todas las máquinas en la red local se presenten libremente. Esto es importante ya que algunos programas de correo no respetan esta parte del protocolo SMTP de forma suficientemente correcta y pueden presentarse a sí mismos con nombres sin sentido.
reject_invalid_helo_hostname
rule rejects emails when the EHLO
announce lists a syntactically incorrect hostname. The reject_non_fqdn_helo_hostname
rule rejects messages when the announced hostname is not a fully-qualified domain name (including a domain name as well as a host name). The reject_unknown_helo_hostname
rule rejects messages if the announced name does not exist in the DNS. Since this last rule unfortunately leads to too many rejections, the administrators turned its effect to a simple warning with the warn_if_reject
modifier as a first step; they may decide to remove this modifier at a later stage, after auditing the results of this rule.
reject_rhsbl_helo
allows to specify a black list to check the hostname against an RHSBL.
permit_mynetworks
as the first rule has an interesting side effect: the following rules only apply to hosts outside the local network. This allows blacklisting all hosts that announce themselves as part of the falcot.com
network, for instance by adding a falcot.com REJECT You are not in our network!
line to the /etc/postfix/access_helo
file.
MAIL FROM
del protocolo SMTP; nuevamente, puede validar esta información de varias formas.
Ejemplo 11.4. Verificación de remitente
smtpd_sender_restrictions = check_sender_access hash:/etc/postfix/access_sender, reject_unknown_sender_domain, reject_unlisted_sender, reject_non_fqdn_sender, reject_rhsbl_sender rhsbl.sorbs.net
/etc/postfix/access_sender
asocia algún tratamiento especial a algunos remitentes. Esto generalmente significa enumerar algunos remitentes en una lista negra o blanca.
reject_unknown_sender_domain
requiere un remitente con dominio válido, ya que es necesario en una dirección válida. La regla reject_unlisted_sender
rechaza remitentes locales si la dirección no existe; esto evita que se envíen correos desde una dirección inválida en el dominio falcot.com
y los mensajes de joe.bloggs@falcot.com
sólo son aceptados si existe dicha dirección.
reject_non_fqdn_sender
rechaza los correos que dicen provenir de direcciones sin un nombre de dominio completamente calificado. En la práctica significa rechazar correos que provienen de usuario@equipo
: la dirección debe anunciarse como usuario@equipo.example.com
o usuario@example.com
.
reject_rhsbl_sender
rule reject senders based on a (domain-based) RHSBL service.
RCPT TO
en el protocolo SMTP. Estas direcciones también requieren validación, aún si pueden ser menos relevantes que las verificaciones realizadas en la dirección del remitente.
Ejemplo 11.5. Verificación de receptor
smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination, reject_unlisted_recipient, reject_non_fqdn_recipient, permit
reject_unauth_destination
es la regla básica que requiere que los mensajes externos estén destinados a nosotros; se rechazarán los mensajes que sean enviados a una dirección que no sea gestionada por este servidor. Sin esta regla, el servidor se convierte en una forma abierta de reenvío que permite que los spammers envíen correos no solicitados; por lo tanto esta regla es obligatoria y preferentemente debe estar ubicada cerca del principio de la lista para evitar que otras reglas autoricen el mensaje antes que se verifique su destino.
reject_unlisted_recipient
rechaza los mensajes enviados a usuarios locales que no existen, lo que tiene sentido. Finalmente, la regla reject_non_fqdn_recipient
rechaza direcciones que no sean completamente calificadas; esto hace imposible enviar un correo a jean
o jean@equipo
y necesita, en cambio, utilizar la dirección completa como literal@equipo.falcot.com
o jean@falcot.com
.
permit
directive at the end is not necessary. But it can be useful at the end of a restriction list to make the default policy explicit.
DATA
en SMTP antes del contenido del mensaje. No provee ninguna información en sí misma además de anunciar lo que seguirá. Todavía puede ser sujeta a verificación.
reject_unauth_pipelining
causa que se rechace el mensaje si el remitente envía una orden antes que se envía la respuesta a la orden anterior. Esto previene una optimización común utilizada por los robots de spammers ya que no tienen el menor interés en las respuestas y sólo están interesados en enviar tantos correos como sea posible en el menor tiempo posible.
RCPT TO
command by default.
EHLO
no válida, Postfix conoce el remitente y el receptor cuando anuncia un rechazo. Luego puede registrar un mensaje más explícito de lo que podría si se hubiera interrumpido la transacción al comienzo. Además, una cantidad de clientes SMTP no esperan fallos en las primeras órdenes de SMTP y estos clientes no se molestarán tanto por este rechazo tardío.
smtpd_delay_reject
rule.
Ejemplo 11.7. Habilitación de filtros basados en contenido
header_checks = regexp:/etc/postfix/header_checks body_checks = regexp:/etc/postfix/body_checks
Ejemplo 11.8. Archivo /etc/postfix/header_checks
de ejemplo
/^X-Mailer: GOTO Sarbacane/ REJECT I fight spam (GOTO Sarbacane) /^Subject: *Su email contiene VIRUS/ DESCARTAR notificación de virus
GOTO Sarbacane
(un software en correo masivo), el mensaje es rechazado. La segunda expresión revisa el asunto del mensaje; si menciona una notificación de virus podemos decidir no rechazar el mensaje sino, en cambio, descartarlo inmediatamente.
check_policy_service
como una restricción adicional:
smtpd_recipient_restrictions = permit_mynetworks, [...] check_policy_service inet:127.0.0.1:10023
postgrey
y le enviará la información del mensaje en cuestión. Por su parte, Postgrey considerará la terna compuesta por la dirección IP, el remitente y el receptor y revisará en su base de datos si ésta fue intentada recientemente. En caso que así sea, Postgrey responderá que el mensaje debe ser aceptado; de lo contrario, la respuesta indicará que el mensaje deberá ser rechazado temporalmente y agregará la terna a su base de datos.
smtpd_restriction_classes
de la misma forma que smtpd_recipient_restrictions
. La directiva check_recipient_access
define luego una tabla que asocia un receptor dado con el conjunto de restricciones apropiadas.
Ejemplo 11.9. Definición de clases de restricción en main.cf
smtpd_restriction_classes = greylisting, aggressive, permissive greylisting = check_policy_service inet:127.0.0.1:10023 aggressive = reject_rbl_client sbl-xbl.spamhaus.org, check_policy_service inet:127.0.0.1:10023 permissive = permit smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination, check_recipient_access hash:/etc/postfix/recipient_access
Ejemplo 11.10. El archivo /etc/postfix/recipient_access
# Direcciones sin filtro postmaster@falcot.com permissive support@falcot.com permissive sales-asia@falcot.com permissive # Filtros agresivos para algunos usuarios privilegiados joe@falcot.com aggressive # Regla especial para el administrador de la lista de correos sympa@falcot.com reject_unverified_sender # Listas grises de forma predeterminada falcot.com greylisting
clamav
como su antivirus libre. El paquete principal es clamav, pero tambien instalaron algunos paquetes adicionales como arj, unzoo, unrar y lha ya que son necesarios para que el antivirus analice archivos adjuntos en alguno de estos formatos.
clamav-milter
. Un «milter» (apócope de «filtro de correo»: «mail filter») es un programa de filtrado diseñado especialmente para interactuar con servidores de correo. Un milter utiliza una interfaz de programación de aplicaciones (API: «Application Programming Interface») que provee un rendimiento mucho mejor que los filtros ajenos a los servidores de correo. Sendmail introdujo inicialmente a los milters, pero Postfix los implementó poco después.
dpkg-reconfigure clamav-milter
. Cuando se le pregunte por la «Interfaz de comunicación con Sendmail», responda «inet:10002@127.0.0.1
».
dpkg-reconfigure clamav-base
.
/etc/postfix/main.cf
:
# Revisión de virus con clamav-milter smtpd_milters = inet:[127.0.0.1]:10002
systemctl reload postfix
should be run so that this change is taken into account.
include
directive it must have one.
Name: example.org Type: TXT TTL: 3600 Data: v=spf1 a mx -all
falcot.org
entry.
#
host -t TXT falcot.org
falcot.org descriptive text "v=spf1 ip4:199.127.61.96 +a +mx +ip4:206.221.184.234 +ip4:209.222.96.251 ~all"
postfix
mail server can check the SPF record for incoming emails using the postfix-policyd-spf-python package, a policy agent written in Python. The file /usr/share/doc/postfix-policyd-spf-python/README.Debian
describes the necessary steps to integrate the agent into postfix, so we won't repeat it here.
/etc/postfix-policyd-spf-python/policyd-spf.conf
, which is fully documented in policyd-spf.conf(5) and /usr/share/doc/postfix-policyd-spf-python/policyd-spf.conf.commented.gz
. The main configuration parameters are HELO_reject
and Mail_From_reject
, which configure if emails should be rejected (Fail
) or accepted with a header being appended (False
), if checks fail. The latter is often useful, when the message is further processed by a spam filter.
Header_Type
must be set to AR
.
postfix
, adds a digital signature associated with the domain name to the header of outgoing emails. The receiving party can validate the message body and header fields by checking the signature against a public key, which is retrieved from the senders DNS records.
opendkim-genkey -s SELECTOR -d DOMAIN
. SELECTOR must be a unique name for the key. It can be as simple as "mail" or the date of creation, if you plan to rotate keys.
Ejemplo 11.11. Create a private key for signing E-Mails from falcot.com
#
opendkim-genkey -s mail -d falcot.com -D /etc/dkimkeys
#
chown opendkim.opendkim /etc/dkimkeys/mail.*
/etc/dkimkeys/mail.private
and /etc/dkimkeys/mail.txt
and set the appropriate ownership. The first file contains the private key and the latter the public key, that needs to be added to the DNS:
Name: mail._domainkey Type: TXT TTL: 3600 Data: "v=DKIM1; h=sha256; k=rsa; s=email; p=[...]"
-b 1024
to chose a smaller keysize. If opendkim-testkey
succeeds, the entry has been successfully set up. The syntax of the entry is explained here:
SOCKET
and RUNDIR
must be chosen in /etc/default/opendkim
. Please note that SOCKET
must be accessible from postfix
in its chrooted environment. The further configuration is done in /etc/opendkim.conf
. The following is a configuration excerpt, which makes sure that the Domain
"falcot.com" and all subdomains (SubDomain
) are signed by the Selector
"mail" and the single private key (KeyFile
) /etc/dkimkeys/mail.private
. The "relaxed" Canonicalization
for both the header and the body tolerates mild modification (by a mailing list software, for example). The filter runs both in signing ("s") and verification ("v") Mode
. If a signature fails to validate (On-BadSignature
), the mail should be quarantined ("q").
[...] Domain falcot.com KeyFile /etc/dkimkeys/mail.private Selector mail [...] Canonicalization relaxed/relaxed Mode sv On-BadSignature q SubDomains yes [...] Socket inet:12345@localhost [...] UserID opendkim
KeyTable
), domains (SigningTable
) and to specify internal or trusted hosts (InternalHosts
, ExternalIgnoreList
), which may send mail through the server as one of the signing domains without credentials.
/etc/postfix/main.cf
make postfix
use the filter:
milter_default_action = accept non_smtpd_milters = inet:localhost:12345 smtpd_milters = inet:localhost:12345
/etc/postfix/master.cf
instead.
/usr/share/doc/opendkim/
directory and the manual pages opendkim(8) and opendkim.conf(5).
_dmarc
and the action, that should be taken, when emails, which contain your domain as sending host, fail to validate using DKIM and SPF.
#
host -t TXT _dmarc.gmail.com
_dmarc.gmail.com descriptive text "v=DMARC1; p=none; sp=quarantine; rua=mailto:mailauth-reports@google.com"
#
host -t TXT _dmarc.yahoo.com
_dmarc.yahoo.com descriptive text "v=DMARC1; p=reject; pct=100; rua=mailto:dmarc_y_rua@yahoo.com;"
reject
all emails pretending to be sent from a Yahoo account but missing or failing DKIM and SPF checks. Google Mail (Gmail) propagates a very relaxed policy, in which such messages from the main domain should still be accepted (p=none
). For subdomains they should be marked as spam (sp=quarantine
). The addresses given in the rua
key can be used to send aggregated DMARC reports to. The full syntax is explained here:
postfix
mail server can use this information too. The opendmarc package contains the necessary milter. Similar to opendkim SOCKET
and RUNDIR
must be chosen in /etc/default/opendmarc
(for Unix sockets you must make sure, that they are inside the postfix chroot to be found). The configuration file /etc/opendmarc.conf
contains detailed comments and is also explained in opendmarc.conf(5). By default, emails failing the DMARC validation are not rejected but flagged, by adding an appropriate header field. To change this, use RejectFailures true
.
smtpd_milters
and non_smtpd_milters
. If we configured the opendkim and opendmarc milters to run on ports 12345 and 54321, the entry in /etc/postfix/main.cf
looks like this:
non_smtpd_milters = inet:localhost:12345,inet:localhost:54321 smtpd_milters = inet:localhost:12345,inet:localhost:54321
/etc/postfix/master.cf
instead.
saslpasswd2
que toma varios parámetros. La opción -u
define el dominio de autenticación, que debe coincidir con el parámetro smtpd_sasl_local_domain
en la configuración de Postfix. La opción -c
permite crear un usuario y la opción -f
permite especificar el archivo a utilizar si necesita almacenar la base de datos SALS en una ubicación diferente a la predeterminada (/etc/sasldb2
).
#
saslpasswd2 -u `postconf -h myservidor` -f /var/spool/postfix/etc/sasldb2 -c jean
[... ingrese la contraseña de jean dos veces ...]
/etc/sasldb2
en un enlace simbólico que apunta a la base de datos utilizada por Postfix con ln -sf /var/spool/postfix/etc/sasldb2 /etc/sasldb2
.
postfix
al grupo sasl
para que pueda acceder a la base de datos SASL. También necesitará agregar algunos parámetros nuevos para activar SASL y necesita configurar el parámetro smtpd_recipient_restrictions
para permitir que los clientes autenticados por SASL puedan enviar correos libremente.
Ejemplo 11.12. Activación de SASL en /etc/postfix/main.cf
# Enable SASL authentication smtpd_sasl_auth_enable = yes # Define the SASL authentication domain to use smtpd_sasl_local_domain = $myhostname [...] # Adding permit_sasl_authenticated before reject_unauth_destination # allows relaying mail sent by SASL-authenticated users smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination, [...]
/etc/postfix/master.cf
file. To turn off authentication at all for port 25 (smtpd
service) add the following directive:
smtp inet n - y - - smtpd [..] -o smtpd_sasl_auth_enable=no [..]
AUTH
command (some very old mail clients do), interoperability with them can be enabled using the broken_sasl_auth_clients
directive.