Tuesday, 24 April 2012

Install DKIM in Postfix using openDKIM

1. Install prerequisites

===========
yum install sendmail-devel openssl-devel
===========

2. Install OpenDKIM

Download then extract OpenDKIM. Change to the extracted directory and run configure, make and then, as root, make install.

===========
wget http://downloads.sourceforge.net/project/opendkim/opendkim-2.4.2.tar.gz
tar -zxf opendkim-2.4.2.tar.gz
cd opendkim*
./configure
make && make install
===========

3. Post install steps

Create a Linux user for OpenDKIM, then make some directories to store your keys and config files in.

============
useradd -s /sbin/nologin -b /var/run/opendkim opendkim-milt
mkdir /etc/mail/dkim
mkdir /etc/mail/dkim/keys
chown -R opendkim-milt:opendkim-milt /etc/mail/dkim
chmod -R go-wrx /etc/mail/dkim/keys
============

4.Check for startup script (/etc/init.d/opendkim). If not present, use this:

==============
    #!/bin/bash
    #
    # opendkim    Start and stop opendkim.

    # chkconfig: - 41 61
    # description: opendkim
    # processname: opendkim
    # pidfile: /var/run/opendkim/dkim-milter.pid

    ### BEGIN INIT INFO
    # Provides: opendkim
    # Required-Start: opendkim
    # Required-Stop: opendkim
    # Short-Description: Start and stop OpenDKIM
    # Description: DKIM milter
    ### END INIT INFO

    # Adapted from Andrew Colin Kissa's <topdog-software[dot]com> script for dkim-milter - 28-05-2009

    . /etc/rc.d/init.d/functions

    DAEMON=/usr/local/sbin/opendkim
    RETVAL=0
    PID_FILE=/var/run/opendkim/dkim-milter.pid

    start() {
    echo -n $"Starting DKIM milter: "
    daemon $DAEMON -x /etc/opendkim.conf
    RETVAL=$?
    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/opendkim
    echo
    return $RETVAL
    }

    stop() {
    echo -n $"Stopping DKIM milter: "
    killproc -p $PID_FILE
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/opendkim
    return $RETVAL
    }

    restart() {
    stop
    start
    }

    case "$1" in
    start)
    start
    ;;
    stop)
    stop
    ;;
    restart)
    restart
    ;;
    status)
    status -p $PID_FILE
    ;;
    condrestart)
    [ -f /var/lock/subsys/opendkim ] && restart || :
    ;;
    *)
    echo $"Usage: $0 {start|stop|status|reload|restart|condrestart}"
    exit 1
    esac

    exit $?
==============

4. Generating keys for DKIM signing

You will need to generate a pair of keys for each domain you want to sign mail for, a public and a private key. OpenDKIM has a script included that will help do this. Where the keys are kept is up to you but here we create a directory inside /etc/mail/dkim/keys…

============
mkdir /etc/mail/dkim/keys/example.com
opendkim-genkey.sh -D /etc/mail/dkim/keys/example.com/ -d example.com -s default
chown -R opendkim-milt:opendkim-milt /etc/mail/dkim/example.com
mv /etc/mail/dkim/keys/example.com/default.private /etc/mail/dkim/keys/example.com/default
============



    * Reply with quote
    * Report this post

OpenDKIM with Postfix

Postby Bimlendu on Thu Oct 06, 2011 10:11 am
Reference ticket: DPZ-639288

1. Install prerequisites

===========
    yum install sendmail-devel openssl-devel
===========


2. Install OpenDKIM

Download then extract OpenDKIM. Change to the extracted directory and run configure, make and then, as root, make install

============
    wget http://downloads.sourceforge.net/project/opendkim/opendkim-2.4.2.tar.gz
    tar -zxf opendkim-2.4.2.tar.gz
    cd opendkim*
    ./configure
    make && make install
============


3. Post install steps

Create a Linux user for OpenDKIM, then make some directories to store your keys and config files in.

==========
    useradd -s /sbin/nologin -b /var/run/opendkim opendkim-milt
    mkdir /etc/mail/dkim
    mkdir /etc/mail/dkim/keys
    chown -R opendkim-milt:opendkim-milt /etc/mail/dkim
    chmod -R go-wrx /etc/mail/dkim/keys
==========



Check for startup script (/etc/init.d/opendkim). If not present, use this:

============
    #!/bin/bash
    #
    # opendkim    Start and stop opendkim.

    # chkconfig: - 41 61
    # description: opendkim
    # processname: opendkim
    # pidfile: /var/run/opendkim/dkim-milter.pid

    ### BEGIN INIT INFO
    # Provides: opendkim
    # Required-Start: opendkim
    # Required-Stop: opendkim
    # Short-Description: Start and stop OpenDKIM
    # Description: DKIM milter
    ### END INIT INFO

    # Adapted from Andrew Colin Kissa's <topdog-software[dot]com> script for dkim-milter - 28-05-2009

    . /etc/rc.d/init.d/functions

    DAEMON=/usr/local/sbin/opendkim
    RETVAL=0
    PID_FILE=/var/run/opendkim/dkim-milter.pid

    start() {
    echo -n $"Starting DKIM milter: "
    daemon $DAEMON -x /etc/opendkim.conf
    RETVAL=$?
    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/opendkim
    echo
    return $RETVAL
    }

    stop() {
    echo -n $"Stopping DKIM milter: "
    killproc -p $PID_FILE
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/opendkim
    return $RETVAL
    }

    restart() {
    stop
    start
    }

    case "$1" in
    start)
    start
    ;;
    stop)
    stop
    ;;
    restart)
    restart
    ;;
    status)
    status -p $PID_FILE
    ;;
    condrestart)
    [ -f /var/lock/subsys/opendkim ] && restart || :
    ;;
    *)
    echo $"Usage: $0 {start|stop|status|reload|restart|condrestart}"
    exit 1
    esac

    exit $?
============


4. Generating keys for DKIM signing

You will need to generate a pair of keys for each domain you want to sign mail for, a public and a private key. OpenDKIM has a script included that will help do this. Where the keys are kept is up to you but here we create a directory inside /etc/mail/dkim/keys…

===========
mkdir /etc/mail/dkim/keys/example.com
opendkim-genkey.sh -D /etc/mail/dkim/keys/example.com/ -d example.com -s default
chown -R opendkim-milt:opendkim-milt /etc/mail/dkim/example.com
mv /etc/mail/dkim/keys/example.com/default.private /etc/mail/dkim/keys/example.com/default
===========

‘-s’ is the selector, here I have used default, you can use anything like mail or dk or dkim or sample.

5. OpenDKIM configuration

We need to edit one config file and create two ‘table’ files that the OpenDKIM milter will use to know what to do with the mails.

Edit /etc/opendkim.conf

These options should work:

==================
##
## opendkim.conf -- configuration file for OpenDKIM filter
##
## $Id: opendkim.conf.sample,v 1.5 2010/03/05 03:32:12 mmarkley Exp $
##
#ADSPDiscard             Yes
ADSPNoSuchDomain        Yes
AutoRestart             Yes
AutoRestartRate         10/1h
Canonicalization        relaxed/relaxed
KeyTable                refile:/etc/mail/opendkim/keyTable
LogWhy                  Yes
On-Default              reject
On-BadSignature         reject
On-DNSError             tempfail
On-InternalError        accept
On-NoSignature          accept
On-Security             discard
PidFile                 /var/run/opendkim/dkim-milter.pid
SignatureAlgorithm      rsa-sha256
SigningTable            refile:/etc/mail/opendkim/signingTable
Socket                  inet:20209@localhost
Syslog                  Yes
SyslogSuccess           Yes
TemporaryDirectory      /var/tmp
UMask                   022
UserID                  opendkim-milt:opendkim-milt
X-Header                Yes
==================

ii) /etc/mail/opendkim/signingTable

This table is used to select one or more signatures to apply to a message based on the address found in the From: header field. Keys in this table vary depending on the type of table used; values in this data set should include one field that contains a name found in the KeyTable that identifies which key should be used in generating the signature, and an optional second field naming the signer of the message that will be included in the "i=" tag in the generated signature.

If the first field contains only a "%" character, it will be replaced by the domain found in the From: header field. Similarly, within the optional second field, any "%" character will be replaced by the domain found in the From: header field.

If this table specifies a regular expression file ("refile"), then the keys are wildcard patterns that are matched against the address found in the From: header field. Entries are checked in the order in which they appear in the file.

For all other database types, the full user@host is checked first, then simply host, then user@.domain (with all superdomains checked in sequence, so "foo.example.com" would first check "user@foo.example.com", then "user@.example.com", then "user@.com"), then .domain, then user@*, and finally *.

In any case, only the first match is applied, unless MultipleSignatures is enabled in which case all matches are applied.

A working signingTable will look like this:

--------------
$ cat /etc/mail/opendkim/signingTable
*@espserv.com mail._domainkey.example.com
*@joseairosa.com mail._domainkey.example1.com
*@porvocacao.com mail._domainkey.example2.com
--------------

6. Postfix configuration

Add these to postfix's main.cf file:

============
smtpd_milters           = inet:localhost:20209
non_smtpd_milters       = inet:localhost:20209
milter_protocol         = 2
milter_default_action   = accept
============

You can change the port if required. Reload postfix.

7. DKIM DNS entries

When you created the keys few steps back, you should have got two files, one the private key and the other a public key. Open the public key file and add the contents to your domain's DNS.

=============
$ cat mail.txt
mail._domainkey IN TXT "v=DKIM1; r=postmaster; g=*; k=rsa; t=y; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNSFbbde/56vjZfTYRXe0w8J44fPmBwZgoIZsGfYFgQxCFKJ50NL2EVWGey9pWw+YrJEfec3nTlbcquxnmm92y7vsWM9B7sCyoYQIweepJBdkJ3boJXBlm3eXMqrOMJfYmqjn51Y5B0kuErgu/N41S1Cr3/BtQU3/QZL0qnXi+6wIDAQAB"
=============

While adding make sure that you remove the "r=postmaster" tag. This tag is still experimental and is not supported globally.

Finally add a DKIM ADSP record which should look something like this:

----------
_adsp._domainkey.example.com    IN    TXT    "dkim=unknown"
----------

8. Start OpenDKIM

=======
service opendkim start
=======

9. Add it to chkconfig so that openDKIM starts automatically on boot.

=======
chkconfig --level 2345 opendkim on
=======

10. Test. Send a mail to check-auth-username=gmail.com@verifier.port25.com. You will get the authentication results in username@gmail's inbox.

Use the following command to test and check if opendkim is being called by postfix or not.

==========
echo Test | mail -s test check-auth-username=gmail.com@verifier.port25.com ;tail -fn0 /var/log/maillog
==========

---------------------------------
Oct  6 00:31:59 smtp01 sendmail[4579]: p964Vw7R004579: from=root, size=82, class=0, nrcpts=1, msgid=<201110060431.p964Vw7R004579@servername.com>, relay=root@localhost
Oct  6 00:31:59 smtp01 postfix/smtpd[4581]: connect from localhost.localdomain[127.0.0.1]
Oct  6 00:31:59 smtp01 postfix/smtpd[4581]: setting up TLS connection from localhost.localdomain[127.0.0.1]
Oct  6 00:31:59 smtp01 postfix/smtpd[4581]: Anonymous TLS connection established from localhost.localdomain[127.0.0.1]: TLSv1 with cipher DHE-RSA-AES256-SHA (256/256 bits)
Oct  6 00:31:59 smtp01 sendmail[4579]: STARTTLS=client, relay=[127.0.0.1], version=TLSv1/SSLv3, verify=FAIL, cipher=DHE-RSA-AES256-SHA, bits=256/256
Oct  6 00:31:59 smtp01 postfix/smtpd[4581]: 36AD1B103: client=localhost.localdomain[127.0.0.1], sasl_sender=root@servername.com
Oct  6 00:31:59 smtp01 postfix/cleanup[4584]: 36AD1B103: message-id=<201110060431.p964Vw7R004579@servername.com>
[b]Oct  6 00:31:59 smtp01 opendkim[4486]: 36AD1B103: DKIM-Signature header added (s=mail, d=domainname.com)[/b]
Oct  6 00:31:59 smtp01 postfix/qmgr[3136]: 36AD1B103: from=<root@servername.com>, size=788, nrcpt=1 (queue active)
Oct  6 00:31:59 smtp01 sendmail[4579]: p964Vw7R004579: to=check-auth-username=gmail.com@verifier.port25.com, ctladdr=root (0/0), delay=00:00:01, xdelay=00:00:00, mailer=relay, pri=30082, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (Ok: queued as 36AD1B103)
Oct  6 00:31:59 smtp01 postfix/smtpd[4581]: disconnect from localhost.localdomain[127.0.0.1]
Oct  6 00:32:01 smtp01 postfix/smtp[4585]: 36AD1B103: to=<check-auth-username=gmail.com@verifier.port25.com>, relay=verifier.port25.com[96.244.219.19]:25, delay=2, delays=0.09/0.01/1.5/0.3, dsn=2.6.0, status=sent (250 2.6.0 message received)
Oct  6 00:32:01 smtp01 postfix/qmgr[3136]: 36AD1B103: removed
---------------------------------

Check you inbox for the authentication results. You should get the following:

==========================================================
Summary of Results
==========================================================
...
DKIM check:         pass
...
==========================================================
Details:
==========================================================
...
----------------------------------------------------------
DKIM check details:
----------------------------------------------------------
Result:         pass (signature verifies; identity doesn't match any headers)
ID(s) verified: header.d=domainname.com
Canonicalized Headers:
   date:Thu,'20'6'20'Oct'20'2011'20'00:31:58'20'-0400'0D''0A'
   from:root'20'<root@servername.com>'0D''0A'
   message-id:<201110060431.p964Vw7R004579@servername.com>'0D''0A'
   to:check-auth-username=gmail.com@verifier.port25.com'0D''0A'
   subject:test'0D''0A'
   dkim-signature:v=1;'20'a=rsa-sha256;'20'c=relaxed/relaxed;'20'd=domainname.com;'20's=mail;'20't=1317875519;'20'bh=fdkeB/A0FkbVP2k4J4pNPoeWH6vqBm9+b0C3OY87Cw8=;'20'h=Date:From:Message-Id:To:Subject;'20'b=

Canonicalized Body:
   Test'0D''0A'


DNS record(s):
   mail._domainkey.domainname.com. 1800 IN TXT "v=DKIM1; g=*; k=rsa; t=y; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA1X6GKfaUhV3jthv32C5lo/V3/4yOys9CsZZByYId2NJnfRWiZroEozl6/4XyQhdb2JPNMRT8xcWd+RqSRfyszb9DzlEhfk4q0PpP7QFhtEzpUVSGrsNiSutkY56JkoQRblrrbrKUNgu5U0GTaFuNUnpj2/kHmEeIGcCk9we9eQIDAQAB"

NOTE: DKIM checking has been performed based on the latest DKIM specs
(RFC 4871 or draft-ietf-dkim-base-10) and verification may fail for
older versions.  If you are using Port25's PowerMTA, you need to use
version 3.2r11 or later to get a compatible version of DKIM.

----------------------------------------------------------

If you receive the above results, all is good.

11. You can automate the key generation and setting up permissions on keys using this script.

==================
    #!/bin/bash
    read -p "Enter your domain name : " domain_name
    if [ -f $domain_name ];
    then
    echo "Enter valid domain name"
    else
    if [ -d /etc/mail/opendkim/keys/$domain_name ];
    then
       echo "Domain already added"
    else
    mkdir /etc/mail/opendkim/keys/$domain_name
    echo -e "Generating key......\n"


    opendkim-genkey -d $domain_name -s mail -t -D /etc/mail/opendkim/keys/$domain_name/
    chown -R opendkim-milt /etc/mail/opendkim/keys/$domain_name
    cp /etc/mail/opendkim/keyTable /etc/mail/opendkim/keyTable_bak_before_$domain_name
    echo "mail._domainkey.$domain_name $domain_name:mail:/etc/mail/opendkim/keys/$domain_name/mail.private" >> /etc/mail/opendkim/keyTable
    echo "*@$domain_name mail._domainkey.$domain_name" >> /etc/mail/opendkim/signingTable
    echo -e "Restarting opendkim.........\n"
    /etc/init.d/opendkim restart
    echo -e "\nAdd the following public key in the domains DNS zone file \n"
    echo -e "\n============================="
    echo `cat /etc/mail/opendkim/keys/$domain_name/mail.txt|sed 's/r\=postmaster\;//g'`
    echo "============================="
    fi
    fi
==================

No comments: