All posts by Don Matteo

lebt in der Schweiz, ist System Engineer MCP bei A-Enterprise GmbH. Mitglied des UNBLOG Knowledge Network. Author und Blogger zu den Themen, Tutorials für Linux und Open Source.

OpenDKIM Postfix Virtual Domain

Configuring OpenDKIM with Postfix using virtual domains can be confusing, especially for those unfamiliar with the topic. However, with the right approach, you can achieve this easily. This tutorial will walk you through the setup where OpenDKIM and Postfix is used for multiple email domains.

OpenDKIM Postfix Virtual Domain

The OpenDKIM package consists of a library that implements the DKIM service and a milter-based filtering application that integrates a milter for Postfix to provide this service to an MTA that serve multiple virtual domains for email services.

OpenDKIM hosts a data collection facility for Postfix sites and virtual domain that wish to volunteer their data. These data are used as feedback to the Internet Engineering Task Force to develop new reputation standards.

DKIM provides a method to validate an email message with the associated domain name identity through cryptographic authentication. This procedure helps combat email spoofing and thus increases email security. In the context of Postfix, the integration of OpenDKIM offers several key advantages:

  • Improved Email Deliverability: Emails signed with DKIM are less likely to be flagged as spam, ensuring your messages reach the intended recipients.
  • Enhanced Sender Reputation: It boosts your domain’s credibility and reputation by demonstrating that your emails are legitimate and tamper-proof.
  • Increased Trust: It verifies the sender’s identity, reassuring recipients that the emails they receive are authentic.

Step 1: Install OpenDKIM

Here we will deploy OpenDKIM in 5 steps on a Debian 12 server with Postfix already installed. I prefer to gain elevated privileges by running “su -” or “sudo su -“. Choose the preferred method, making sure that the following commands could be executed with sudo if necessary.

$ apt install opendkim -y

Step 2: Configure OpenDKIM

Open the OpenDKIM main configuration file in editor of your choice.

$ vi /etc/opendkim.conf

By default, OpenDKIM is set to verification mode (v), which verifies the DKIM signatures of receiving email messages. Changing the mode to “sv,” will let us activate the signing mode for outgoing emails.

Syslog                  yes
SyslogSuccess           yes
LogWhy                  yes
Canonicalization        relaxed/simple
Mode                    sv
OversignHeaders         From
UserID                  opendkim:opendkim
UMask                   022
Socket                  inet:8899@localhost
PidFile                 /run/opendkim/opendkim.pid
TrustAnchorFile         /usr/share/dns/root.key
AutoRestart             Yes
AutoRestartRate         10/1h
ExternalIgnoreList      refile:/etc/opendkim/TrustedHosts
InternalHosts           refile:/etc/opendkim/TrustedHosts
KeyTable                refile:/etc/opendkim/KeyTable
SigningTable            refile:/etc/opendkim/SigningTable
SignatureAlgorithm      rsa-sha256
TemporaryDirectory      /var/tmp

Uncomment the SigningTable and KeyTable option by removing the hash (#) and add the additional lines to /etc/opendkim.conf.

Save and close the OpenDKIM main configuration file.

Next make shure the SigningTable and KeyTable file and also the keys directory exists with the required rights under /etc/opendkim.

$ ls -Al /etc/opendkim
drwxr-x--- 17 opendkim opendkim 4096 Jan 30 keys
-rw-r-----  1 opendkim opendkim 1883 Jan 30 KeyTable
-rw-r-----  1 opendkim opendkim 1988 Jan 30 SigningTable
-rw-r-----  1 opendkim opendkim  460 Jan 30 TrustedHosts

The “/etc/opendkim/TrustedHosts” file contains the internal hosts and a list of addresses and/or hostnames they want to ignore from verification. The localhost IP (127.0.0.1) should always be the first entry in this file.

127.0.0.1
::1
*.example.tld

Step 3: Generate Private and Public Keys

Now let’s generate private and public keys. The command to generate a new key pair performs as follows.

$ opendkim-genkey -b 2048 -d example.tld -D /etc/opendkim/keys/example.tld -s mail -r -h sha256 -v

A key pair with a size of 2048 bits is generated, for the domain “example.tld” and saved in to “/etc/opendkim/keys/example.tld” file with the selector “mail” using for mail with the -r option, with -h tells sha256 hash algorithm, the -v option is for verbose outbut.

Generate new Key for Postfix virtual domain

Save the next lines to a file, for example as /usr/bin/adddkim.

#!/bin/bash
if [ $# -lt 2 ]; then
    echo "No argument supplied"
    echo "use: selector domain"
    exit 1
fi
mkdir /etc/opendkim/keys/$2
opendkim-genkey -D /etc/opendkim/keys/$2/ -d $2 -h sha256 -s $1 -r
chown -R opendkim:opendkim /etc/opendkim/keys/$2
chmod 640 /etc/opendkim/keys/$2/*
mv /etc/opendkim/keys/$2/$1.private /etc/opendkim/keys/$2/$1
echo "$1._domainkey.$2 $2:$1:/etc/opendkim/keys/$2/$1" >> /etc/opendkim/KeyTable
echo "*@$2 $1._domainkey.$2" >> /etc/opendkim/SigningTable
cat /etc/opendkim/keys/$2/$1.txt

Save and close the file and make this script executable.

$ chmod 755 /usr/bin/adddkim

Finish, now simply use the command to generate a new DKIM for each desired domain by running this command.

$ adddkim selector example.tld

The command generates a private and public key and adds the entries to the SigningTable and KeyTable file.

Note: “default” is the DKIM selector. A domain might have multiple DKIM Signatures. The DKIM selector allows you to choose a particular DKIM Key. You can use any name of your choice, but make sure you don’t have a DKIM Signature already implemented with the same selector name.

Step 4: Connect Postfix to OpenDKIM

Now that you’ve configured OpenDKIM, it’s time to implement Postfix DKIM. Let’s follow the Postfix OpenDKIM configuration process.

Edit Postfix main configuration file.

$ vi /etc/postfix/main.cf

Add the following lines to the end of the “main.cf” file.

smtpd_milters = inet:127.0.0.1:8899
non_smtpd_milters = $smtpd_milters
milter_default_action = accept
milter_protocol = 2

Finally, now restart the services to apply changes.

$ systemctl restart opendkim
$ systemctl restart postfix

Step 5: Publish the Public DKIM to DNS

Implement the public DKIM to the corresponding DNS zone.

$ cat /etc/opendkim/keys/example.tld/mail.txt

The content of mail.txt is the public key that will add to the DNS zone.

mail._domainkey IN      TXT     ( "v=DKIM1; h=sha256; k=rsa; s=email;"
    "p=MIIBIjHNBgkqhkiG9w0BAQEFAAOCAZ8AMGGBCgKCZQEB62eXljmnXSeW8V8pgCgeWuQp+IOmYrN6Y8+VFqglw8PHfgL9mhJeA+Kn83VeBfRjVHUt8z5NnTgcEhzb9GQ4lX0eAxQ7J2uwlmJdREh8WWM5QsDwP80L3tsCvyAsVqXZNzZOJ9odFccgvPAAClwBW6Z2ZZkQSzQkS2hw0ma+CVTAPRI6LqJ7GNGo79qSwRmssLZHf01+CBaIL"
    "LQaZKVVTF4CxKrJpnsypjnAexpg4Ti9bQYnENXNHfCaogTDD86SC3E7Zkdt2YYrB0CA4F5B+3nKq3w6ioooiwT2yznKPWE4oi0QXI7MOJJ53oJyVGtKtZcq4ZLfn4KW0z5gpHgDvIDAQAA" )  ; ----- DKIM key mail for example.tld

Important Notes: Name/Target: mail._domainkey, Make sure to remove any spaces or double-quotes if your DNS provider using UI managed zone editor like Cloudflare.

Check OpenDKIM Record

You can test the DKIM TXT record with lookup using dig on linux.

$ dig TXT mail._domainkey.example.tld +short

Windows systems provide the command as follows.

$ nslookup -type=TXT mail._domainkey.example.tld

You can also try DKIM check by MxToolbox here. The DKIM Check tool will perform a DKIM record test against a domain name and selector for a valid published DKIM key record.

OpenDKIM help!

You can use the following commands for help!

$ man opendkim-genkey
and
$ opendkim-genkey --help
opendkim-genkey: usage: opendkim-genkey [options]
        --append-domain        include domain name in zone file stub
        --bits=n               use n bits to generate the key
        --directory=path       leave output in the named directory
        --domain=name          generate data for the named domain [localhost]
        --hash-algorithms=list limit to use of the named algorithm(s)
        --help                 print help and exit
        --note=string          include specified note in zone data
        --restrict             restrict key to email use only
        --selector=name        selector name [default]
        --subdomains           allow signing of subdomains
        --testmode             indicate key is in test mode
        --verbose              increased output
        --version              print version and exit

Source:

Amavis Install for Postfix on Debian 12 Ubuntu 22.04

In this tutorial you learn how to install Amavis with Postfix on Debian 12 and Ubuntu 22.04.

AMaViS stands for A MAil Virus Scanner and is a server-side virus scanner that is used on Unix/Linux mail servers like Postfix. The function has now been expanded to include a spam filter.

Install Amavis Postfix ClamAV SpamAssassin

Firt of all, elevate to root with ‘su -‘ or ‘sudo su -‘ and install Amavis-new with Postfix and the additional packages on Debian 12 or Ubuntu 22.04.

$ apt -y update
$ apt -y install clamav-daemon amavisd-new spamassassin postfix

Get Amavis ready

Next enable the antivirus checking mode and the SPAM checking mode.

$ vi /etc/amavis/conf.d/15-content_filter_mode

# uncomment to enable virus scanning
@bypass_virus_checks_maps = (
   \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);

# uncomment to enable spam checking
@bypass_spam_checks_maps = (
   \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);

Add your own domain name to the mailname for amavis configuration.

$ echo 'example.tld' > /etc/mailname

Get Postfix ready

Now add the smtp amavis content filter to postfix main configuration.

$ vi /etc/postfix/main.cf
# add to the end
content_filter=smtp-amavis:[127.0.0.1]:10024

Add the amavis content filter to postfix master configuration.

$ vi /etc/postfix/master.cf

# add to the end
smtp-amavis unix  -    -    n    -    2 smtp
    -o smtp_data_done_timeout=1200
    -o smtp_send_xforward_command=yes
    -o disable_dns_lookups=yes
    -o max_use=20

127.0.0.1:10025 inet  n    -    n    -    - smtpd
    -o content_filter=
    -o local_recipient_maps=
    -o relay_recipient_maps=
    -o smtpd_restriction_classes=
    -o smtpd_client_restrictions=
    -o smtpd_helo_restrictions=
    -o smtpd_sender_restrictions=
    -o smtpd_recipient_restrictions=permit_mynetworks,reject
    -o mynetworks=127.0.0.0/8
    -o strict_rfc821_envelopes=yes
    -o smtpd_error_sleep_time=0
    -o smtpd_soft_error_limit=1001
    -o smtpd_hard_error_limit=1000

Add service users to group clamav and amavis.

$ usermod -a -G clamav amavis
$ usermod -a -G amavis clamav

Restart clamav-daemon, amavis, spamd and postfix to take changes.

$ systemctl restart clamav-daemon spamd amavis postfix

You have now installed Amavis with Postfix and SpamAssassin on Debian or Ubuntu and there is nothing else to do. It is worth checking the settings to tweak spam thresholds.

Amavis and Postfix install tweak on Debian

Check out the configuration files and documentation include example files here through installing Amavis on Debian or Ubuntu.

$ ls -Al /etc/amavis/conf.d
-rw-r--r-- 1 root root  1610 Feb 23  2023 01-debian
-rw-r--r-- 1 root root   927 Jan 16 21:52 05-domain_id
-rw-r--r-- 1 root root   429 Feb 23  2023 05-node_id
-rw-r--r-- 1 root root 20791 Feb 23  2023 15-av_scanners
-rw-r--r-- 1 root root   713 Jan 17 15:13 15-content_filter_mode
-rw-r--r-- 1 root root  9542 Jan 18 15:11 20-debian_defaults
-rw-r--r-- 1 root root   573 Feb 23  2023 25-amavis_helpers
-rw-r--r-- 1 root root  2130 Feb 23  2023 30-template_localization
-rw-r--r-- 1 root root  1076 Jan 18 15:07 50-user

Note. if you’re not familiar with Vim, use your favorite editor such as Nano.

Set headers X-Spam-Flag X-Spam-Status

$sa_tag_level_deflt is the level at which Amavisd-new will write spam info headers such as X-Spam-Flag, X-Spam-Score and X-Spam-Status. If you would always like header info to be written to all messages, set this value to -999.

$ vi /etc/amavis/conf.d/50-user

$sa_tag_level_deflt  = -999;

Place your configuration directives here in this file. It’s worthwhile being aware of them as this is the most convenient place to tweak spam thresholds. The Amavis setting must be applied after each adjusting.

$ amavisd reload

How does Amavis and Postfix work?

Let’s check Amavis and Postfix services whether they up and running.

$ systemctl status clamav-daemon spamd amavis postfix

Amavisd listen on localhost port 10024 and Postfix (master) listen on port 10025, also spamd (perl) listen on port 783.

$ netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:8899          0.0.0.0:*               LISTEN      2895/opendkim
tcp        0      0 127.0.0.1:783           0.0.0.0:*               LISTEN      6227/perl
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN      4208/master
tcp        0      0 127.0.0.1:10024         0.0.0.0:*               LISTEN      7250/amavisd (maste
tcp        0      0 127.0.0.1:10025         0.0.0.0:*               LISTEN      4208/master
tcp6       0      0 ::1:783                 :::*                    LISTEN      6227/perl
tcp6       0      0 ::1:10024               :::*                    LISTEN      7250/amavisd (maste
udp        0      0 0.0.0.0:49041           0.0.0.0:*                           7268/amavisd (ch1-a
udp        0      0 0.0.0.0:34142           0.0.0.0:*                           7269/amavisd (ch1-a

Now test that the amavisd service is listening on localhost:10024 using telnet.

$ telnet localhost 10024
Trying ::1...
Connected to localhost.
Escape character is.
220 [::1] ESMTP amavis service ready
ehlo localhost
250-[::1]
250-VRFY
250-PIPELINING
250-SIZE
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-SMTPUTF8
250-DSN
250 XFORWARD NAME ADDR PORT PROTO HELO IDENT SOURCE
quit
221 2.0.0 [::1] amavis closing transmission channel
Connection closed by foreign host.

If everything is working then you should see a successful connection similar to above.

Next to test the postfix smtpd is listening on 127.0.0.1:10025.

$ telnet 127.0.0.1 10025
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is.
220 mail.example.tld ESMTP Postfix (Debian/GNU)
ehlo localhost
250-mail.example.tld
250-PIPELINING
250-SIZE 10240000
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-SMTPUTF8
250 CHUNKING
quit
221 2.0.0 Bye
Connection closed by foreign host.

Again we should see a successful connection as shown above.

Now it’s time to send an email preferably to yourself.

$ echo "Subject: hello" | sendmail myself@example.tld

These action can be tracked in mail.log so you should see Passed CLEAN.

2024-01-17T16:00:57.552234+01:00 mail amavis[7269]: (07269-01) Passed CLEAN {RelayedInbound}, [127.0.0.1] <root@mail.example.tld> -> <myself@example.tld>, Message-ID: <20240117150056.7C599807BB@mail.example.tld>, mail_id: auFXC0ferXjU, Hits: 2.106, size: 674, queued_as: 7493F807B5, dkim_sd=example.tld:example.tld, 943 ms

Now we can test if everything is working by sending special strings to test the scanning. To do this, download the test-messages and run the command to extract the sample test messages.

$ perl -pe 's/./chr(ord($&)^255)/sge' <sample.tar.gz.compl | zcat | tar xvf -

Use these two commands to send a sample spam and virus message.

$ sendmail -i myself@example.tld < sample-spam-GTUBE-junk.txt
$ sendmail -i myself@example.tld < sample-virus-simple.txt

Please replace “myself@example.tld” with your actual address. Check your /var/log/mail.log for the scan result from amavis and you should see something like “Passed SPAMMY” or “Blocked INFECTED (Eicar-Test-Signature)”. You can now verify your settings match your delivery expectations.

Task of AMaViS-New

AMaViS is not a virus scanner in the true sense, but rather software that was developed to integrate virus scanners into mail servers. It provides a standard interface between the Mail Transfer Agents (MTA) and the content filters so that manufacturers of mail servers and antivirus programs do not have to constantly develop new interfaces. For example, it is compatible with Postfix, sendmail or Exim. Antivirus programs that work with Amavis include AntiVir Unix, ClamAV and many more. The newer amavisd-new also offers the option of integrating SpamAssassin and other filter programs.