DKIM with OpenDKIM¶
Your Postfix signs outgoing mail. Receiving systems need the public DNS key. The private key and public TXT record serve different purposes.
Setup¶
Prerequisite: your values and Debian packages. Run as root; personal signing keys belong in the signing user's account. Merge changes into existing server configuration.
set -euo pipefail
. /root/mailserver.env
apt-get install -y --no-install-recommends opendkim opendkim-tools
install -d -o opendkim -g opendkim -m 0750 "/etc/opendkim/keys/$DOMAIN"
if test ! -s "/etc/opendkim/keys/$DOMAIN/mail.private"; then
opendkim-genkey -b 2048 -d "$DOMAIN" -s mail -D "/etc/opendkim/keys/$DOMAIN"
fi
chown opendkim:opendkim "/etc/opendkim/keys/$DOMAIN/mail.private"
chmod 0600 "/etc/opendkim/keys/$DOMAIN/mail.private"
cat > /etc/opendkim/mailserver.conf <<EOF
Syslog yes
Mode sv
UserID opendkim
UMask 007
Socket inet:8891@127.0.0.1
Domain $DOMAIN
Selector mail
KeyFile /etc/opendkim/keys/$DOMAIN/mail.private
InternalHosts 127.0.0.1,::1
Canonicalization relaxed/relaxed
SignatureAlgorithm rsa-sha256
SignHeaders From,To,Cc,Subject,Date,Message-ID,Reply-To,Sender,MIME-Version,Content-Type,Content-Transfer-Encoding
OversignHeaders From,To,Cc,Subject,Date,Message-ID,Reply-To,Sender,MIME-Version,Content-Type,Content-Transfer-Encoding
EOF
install -d /etc/systemd/system/opendkim.service.d
cat > /etc/systemd/system/opendkim.service.d/mailserver.conf <<'EOF'
[Service]
Type=simple
PIDFile=
ExecStart=
ExecStart=/usr/sbin/opendkim -f -x /etc/opendkim/mailserver.conf
EOF
opendkim -n -x /etc/opendkim/mailserver.conf
systemctl daemon-reload
systemctl enable --now opendkim
systemctl restart opendkim
python3 - <<'PY'
import subprocess
for name in ("smtpd_milters", "non_smtpd_milters"):
parts = [p.strip() for p in subprocess.check_output(["postconf", "-h", name], text=True).split(",") if p.strip()]
endpoint = "inet:127.0.0.1:8891"
if endpoint not in parts:
parts.append(endpoint)
subprocess.run(["postconf", "-e", name + "=" + ", ".join(parts)], check=True)
PY
postconf -e 'milter_protocol=6' 'milter_default_action=tempfail'
postfix check
systemctl reload postfix
cat "/etc/opendkim/keys/$DOMAIN/mail.txt"
Publish the printed record as TXT under mail._domainkey at your DNS provider. Many providers expect only the quoted content joined into one string. A prepared DNS file is not a publication. Coordinate SPF and DMARC with every sending route.
Test¶
set -euo pipefail
. /root/mailserver.env
opendkim -n -x /etc/opendkim/mailserver.conf
systemctl is-active opendkim postfix
postconf -h smtpd_milters | grep -F 'inet:127.0.0.1:8891'
install -d -m 0700 /root/mail-tests
swaks --server 127.0.0.1 --port 25 --from "$MAILBOX" --to "root@$DOMAIN" \
--header "Subject: DKIM milter test" --body "Local DKIM test message" --timeout 30
for attempt in {1..30}; do
if find /root/Maildir/new -type f 2>/dev/null | grep -q .; then break; fi
sleep 1
done
python3 - <<'PY'
from pathlib import Path
import dkim, os, re
domain = os.environ["DOMAIN"]
mails = sorted(Path("/root/Maildir/new").glob("*"), key=lambda p: p.stat().st_mtime)
assert mails, "No local test message delivered"
raw = mails[-1].read_bytes()
assert b"DKIM-Signature:" in raw, "Postfix did not add a DKIM signature"
record = Path("/etc/opendkim/keys/" + domain + "/mail.txt").read_text()
key = "".join(re.findall(r'"([^"]*)"', record)).encode()
def local_key(name, **kwargs):
assert name.rstrip(b".") == ("mail._domainkey." + domain).encode()
return key
assert dkim.verify(raw, dnsfunc=local_key), "Signature invalid with your public key"
altered = raw.replace(b"Local DKIM test message", b"Tampered test message")
assert altered != raw and not dkim.verify(altered, dnsfunc=local_key)
Path("/root/mail-tests/dkim.eml").write_bytes(raw)
print("PASS: actual Postfix milter signs messages; original valid, modified body invalid.")
PY
After publishing DNS, also run:
. /root/mailserver.env
dig "mail._domainkey.$DOMAIN" TXT +short
python3 - <<'PY'
from pathlib import Path
import dkim
assert dkim.verify(Path('/root/mail-tests/dkim.eml').read_bytes()), 'Signature cannot be verified using DNS'
print('PASS: the published DNS key verifies the Postfix test message.')
PY
Expected: successful DNS-based signature verification. The first test proves Milter signing and cryptography using the local public key; the second proves DNS availability. Check DNSSEC separately on its page.
Test mailbox headers stay on your server. Preserve existing DKIM signatures and additional Milters.