Blackhold

DKIM en un servidor de correo

Posted on febrer 5th, 2015 by admin

Administro algunos servidores de listas de correo y aúnque configure los dns inversos no hay forma de que los mails no entren como spam en algunos proveedores de correo, así que otra cosa que podemos hacer es añadir una firma dkim a los mails que mandamos desde nuestro servidor de correo, de esta forma le estamos diciendo al servidor de correo receptor que no somos spammers, una vez mas!

Tengo el servidor de listas de correo con mailman lists.capa8.cat, así que vamos a trabajar sobre éste.

Lo primero será instalar opendkim

root@lists:~# apt-get install opendkim opendkim-tools

Habilitamos opendkim en /etc/default/opendkim

# Command-line options specified here will override the contents of
# /etc/opendkim.conf. See opendkim(8) for a complete list of options.
#DAEMON_OPTS=""
#
# Uncomment to specify an alternate socket
# Note that setting this will override any Socket value in opendkim.conf
#SOCKET="local:/var/run/opendkim/opendkim.sock" # default
#SOCKET="inet:54321" # listen on all interfaces on port 54321
#SOCKET="inet:12345@localhost" # listen on loopback on port 12345
#SOCKET="inet:12345@192.0.2.1" # listen on 192.0.2.1 on port 12345

SOCKET="inet:8891@localhost"

Modificamos el fichero /etc/opendkim.conf para que quede así

# This is a basic configuration that can easily be adapted to suit a standard
# installation. For more advanced options, see opendkim.conf(5) and/or
# /usr/share/doc/opendkim/examples/opendkim.conf.sample.

# Nota: Usats:
#  https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-dkim-with-postfix-on-debian-wheezy
#  https://help.ubuntu.com/community/Postfix/DKIM

# Log to syslog
Syslog                  yes
SyslogSuccess           Yes
LogWhy                  Yes

# Required to use local socket with MTAs that access the socket as a non-
# privileged user (e.g. Postfix)
UMask                   002

# Auto restart the filter on failures
AutoRestart             Yes

# Specifies the filter's maximum restart rate, if restarts begin to happen
# faster than this rate, the filter will terminate; 10/1h - 10 restarts/hour are allowed at most
AutoRestartRate         10/1h

# Sign for cooperativa.cat with key in /etc/mail/dkim.key using
# selector '2007' (e.g. 2007._domainkey.cooperativa.cat)
#Domain                  capa8.net
#KeyFile                /etc/mail/dkim/dkim.key
#Selector                lists

# Associem dominis amb claus i declarem hosts i IPs internes
ExternalIgnoreList      refile:/etc/mail/dkim/TrustedHosts.txt
InternalHosts           refile:/etc/mail/dkim/TrustedHosts.txt
KeyTable                refile:/etc/mail/dkim/KeyTable.txt
SigningTable            refile:/etc/mail/dkim/SigningTable.txt

# Commonly-used options; the commented-out versions show the defaults.
#Canonicalization        relaxed/simple
Canonicalization        relaxed/relaxed
Mode                    sv
#SubDomains             no
#ADSPDiscard            no
DNSTimeout              5
Background              yes
# The contents of /etc/mail/dkim-InternalHosts.txt should be
#   127.0.0.1/8
#   192.168.1.0/24
#   other.internal.host.domain.tld
# You need InternalHosts if you are signing e-mails on a gateway mail server
# for each of the computers on your LAN.
InternalHosts          /etc/mail/dkim/InternalHosts.txt


# Always oversign From (sign using actual From and a null From to prevent
# malicious signatures header fields (From and/or others) between the signer
# and the verifier.  From is oversigned by default in the Debian pacakge
# because it is often the identity key used by reputation systems and thus
# somewhat security sensitive.
#OversignHeaders         From
# Podem provar aixo per a la llista
OversignHeaders         From

# List domains to use for RFC 6541 DKIM Authorized Third-Party Signatures
# (ATPS) (experimental)

#ATPSDomains            capa8.net

Vamos a modificar algunos ficheros mas. El server tiene las ips 10.90.224.204 y 109.69.10.135

/etc/mail/dkim/InternalHosts.txt

127.0.0.1
127.0.0.0/8
192.168.2.16
10.90.224.204
109.69.10.135
fe80::20c:29ff:fee5:d6bc/64
fe80::20c:29ff:fee5:d6c6/64
10.0.0.0/8
2a00:1508:6000::/40
::1

y /etc/mail/dkim/TrustedHosts.txt

127.0.0.1
127.0.0.0/8
localhost
192.168.2.16
10.90.224.204
109.69.10.135
fe80::20c:29ff:fee5:d6bc/64
fe80::20c:29ff:fee5:d6c6/64
lists.capa8.net
lists.capa8.cat
::1

Importante no dejarse ::1 ni todas las IPs locales del server!!!

Modificamos el fichero /etc/postfix/main.cf y añadimos los milters al final del fichero

# Filtres de missatges (Milters) externs: DKIM, DomainKeys IM
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891
milter_default_action = accept

Ahora vamos a /root y creamos un script que se llame crea_dkim.sh

root@lists:~# cd
root@lists:~# vi crea_dkim.sh

Con éste contenido

#!/bin/bash

DOMAIN="$1"
SUB="$2"

if [ "$DOMAIN" = "" ]
then
   echo "El primer argument ha de ser un domini"
   exit 1
fi

if [ "$SUB" = "" ]
then
   echo "El segon argument ha de ser un subdomini (llistes, lists o el que sigui)"
   exit 1
fi

# Creem el directori de claus i les claus
DIR="/etc/mail/dkim/keys/$DOMAIN"
mkdir -p "$DIR"
opendkim-genkey -r -d $DOMAIN -D "$DIR"
ln -s "$DIR/default.private" "$DIR/$SUB"

# Afegim la clau del domini a la llista de claus
echo "$SUB._domainkey.$DOMAIN $DOMAIN:$SUB:/etc/mail/dkim/keys/$DOMAIN/default.private" >> /etc/mail/dkim/KeyTable.txt
echo "*@$SUB.$DOMAIN $SUB._domainkey.$DOMAIN" >> /etc/mail/dkim/SigningTable.txt

# Reiniciem DKIM-filter
#/etc/init.d/dkim-filter restart

# Mostrem el que s'hauria d'afegir al DNS
#  * Canviem selector (subdomini) de 'default' per '$SUB'
#  * Eliminem el comentari final
#  * Posem contrabarra abans dels punt-i-coma ';'
echo "Aquests son els registres a afegir al DNS de $DOMAIN:"
cat "$DIR/default.txt" | sed -e "s/^default/${SUB}/" -e 's/ ; ----- .*//' -e 's/;/\;/g'
echo "_dmarc    IN      TXT     "v=DMARC1; p=none; rua=mailto:abuse@capa8.cat""
echo ""

Y le damos permisos de ejecución y lo ejecutamos con éste formato (dominio subdominio)

root@lists:~# chmod +x crea_dkim.sh 
root@lists:~# ./crea_dkim.sh capa8.net lists
Aquests son els registres a afegir al DNS de capa8.net:
lists._domainkey IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBA************************"
_dmarc    IN      TXT     "v=DMARC1; p=none; rua=mailto:abuse@capa8.net"

Ahora vamos a nuestro servidor de DNS y añadimos la clave DKIM y el dmarc en nuestro fichero de zona de bind

@                               IN      TXT     "v=spf1 a:capa8.net a mx ~all"
lists                           IN      TXT     "v=spf1 a:lists.capa8.net a mx ~all"
lists._domainkey                IN      TXT     "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBA************************"
_dmarc                          IN      TXT     "v=DMARC1; p=none; rua=mailto:abuse@capa8.net"

Reiniciamos bind

root@dns1:~# service bind9 restart

Volvemos al servidor de correo y arrancamos opendkim y reiniciamos postfix

root@lists:/etc/postfix# /etc/init.d/opendkim start
Starting OpenDKIM: opendkim.
root@lists:/etc/default# /etc/init.d/postfix restart
[ ok ] Stopping Postfix Mail Transport Agent: postfix.
[ ok ] Starting Postfix Mail Transport Agent: postfix.

Verificamos que opendkim está escuchando

root@lists:/etc/default# netstat -lanp |grep 8891
tcp        0      0 127.0.0.1:8891          0.0.0.0:*               LISTEN      25414/opendkim 

Y Ahora tenemos que esperar a la propagación de los DNS y probar de mandar un mail a ver que nos cuentan las cabeceras.

Para que mailman deje pasar las cabeceras DKIM correctamente deberemos modificar el fichero de configuración que está en /etc/mailman/mm_cfg.py y añadimos ésta línea al final

REMOVE_DKIM_HEADERS = Yes

Si nos aparece un error tipo

can't load key from /etc/mail/dkim/keys/capa8.cat/default.private: Permission denied

Deberemos asignarle los permisos de lectura a opendkim:opendkim en /etc/mail/dkim

# cd /etc/mail
# chown opendkim:opendkim dkim -R

Os pego un ls recursivo de como tienen que quedar los permisos para que no de errores

root@lists:/etc# ls -lR mail
mail:
total 4
drwxr-xr-x 3 opendkim opendkim 4096 Feb  6  2015 dkim

mail/dkim:
total 20
-rw-r--r-- 1 opendkim opendkim  154 Feb  6  2015 InternalHosts.txt
drwxr-xr-x 4 opendkim opendkim 4096 Feb  6  2015 keys
-rw-r--r-- 1 opendkim opendkim  178 Feb  6  2015 KeyTable.txt
-rw-r--r-- 1 opendkim opendkim   90 Feb  6  2015 SigningTable.txt
-rw-r--r-- 1 opendkim opendkim  165 Feb  6  2015 TrustedHosts.txt

mail/dkim/keys:
total 8
drwxr-xr-x 2 opendkim opendkim 4096 Feb  6  2015 capa8.cat
drwxr-xr-x 2 opendkim opendkim 4096 Feb  6  2015 capa8.net

mail/dkim/keys/capa8.cat:
total 8
-rw------- 1 opendkim opendkim 887 Feb  6  2015 default.private
-rw------- 1 opendkim opendkim 302 Feb  6  2015 default.txt
lrwxrwxrwx 1 opendkim opendkim  45 Feb  6  2015 lists -> /etc/mail/dkim/keys/capa8.cat/default.private

mail/dkim/keys/capa8.net:
total 8
-rw------- 1 opendkim opendkim 891 Feb  6  2015 default.private
-rw------- 1 opendkim opendkim 302 Feb  6  2015 default.txt
lrwxrwxrwx 1 opendkim opendkim  45 Feb  6  2015 lists -> /etc/mail/dkim/keys/capa8.net/default.private

Addicionalmente si queremos, podemos añadir los adsp, que es la forma de decirle qué hacer con los mails que no vienen firmados.

_adsp._domainkey      IN      TXT     "dkim=all\;"
_adsp._domainkey.lists      IN      TXT     "dkim=all\;"
_adsp._domainkey.nombreserver       IN      TXT     "dkim=all\;"

Como aún no puedo demostrar que esto funciona os dejo un par de mensajes que podemos encontrar en las cabeceras para saber si la cosa está funcionando o no:

KO
Received-SPF: none (google.com: al@blogmail.cc does not designate permitted sender hosts) client-ip=109.69.10.249;

KO – pero va a medias
Received-SPF: pass (google.com: domain of marsupi-bounces@marsupi.org designates 109.69.10.252 as permitted sender) client-ip=109.69.10.252;
Authentication-Results: mx.google.com;
spf=pass (google.com: domain of marsupi-bounces@marsupi.org designates 109.69.10.252 as permitted sender) smtp.mail=marsupi-bounces@marsupi.org;
dkim=neutral (body hash did not verify) header.i=@;
dmarc=fail (p=NONE dis=NONE) header.from=gmail.com

KO – problema con el TXT o la clave o DNS no actualizados
Received-SPF: none (google.com: capa8-tech-bounces@lists.capa8.net does not designate permitted sender hosts) client-ip=109.69.10.135;
Authentication-Results: mx.google.com;
spf=none (google.com: capa8-tech-bounces@lists.capa8.net does not designate permitted sender hosts) smtp.mail=capa8-tech-bounces@lists.capa8.net;
dkim=neutral (body hash did not verify) header.i=@;
dmarc=fail (p=NONE dis=NONE) header.from=gmail.com

OK
Received-SPF: pass (google.com: domain of marsupi-bounces@marsupi.org designates 109.69.10.252 as permitted sender) client-ip=109.69.10.252;

OK
Received-SPF: pass (google.com: domain of ecoxarxes-bounces@llistes.ecoxarxes.cat designates 109.69.10.252 as permitted sender) client-ip=109.69.10.252;
Authentication-Results: mx.google.com;
spf=pass (google.com: domain of ecoxarxes-bounces@llistes.ecoxarxes.cat designates 109.69.10.252 as permitted sender) smtp.mailfrom=ecoxarxes-bounces@llistes.ecoxarxes.cat;
dkim=pass header.i=@ecoxarxes.cat;
dmarc=pass (p=NONE dis=NONE) header.from=llistes.ecoxarxes.cat
Received: from tesla.marsupi.org (unknown [127.0.0.1])
by tesla.marsupi.org (Postfix) with ESMTP id A680F12226F
for ; Mon, 19 Oct 2015 13:05:14 +0200 (CEST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=ecoxarxes.cat;
s=llistes; t=1445252714;
bh=BYEU089oQnIplHFH3jQeBCljiVSq0BDujYCM/qjCyYo=;
h=Subject:From:To:Date:List-Id:From;
b=tPbpuaIWW******************************

Muchas gracias a emi! :)

This entry was posted on dijous, febrer 5th, 2015 at 00:43 and is filed under Linux. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

« »

guy fawkes