Enterprise Email Security: SPF, DKIM, and DMARC Setup on Postfix & DNS

Security tutorial - IT technology blog
Security tutorial - IT technology blog

The Anatomy of Domain Spoofing

SMTP dates back to 1982 (RFC 821). It was built for ARPANET researchers who trusted one another implicitly. Because of that legacy, the protocol has zero native verification. It cannot confirm whether an outbound message actually came from the sender listed in the From: header.

Anyone who can open a raw TCP socket on port 25 can test this flaw in seconds:

telnet mail.target-company.com 25
HELO attacker.local
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>

Without authentication layers, the receiving server accepts that envelope at face value. Attackers exploit this gap for BEC (business email compromise), CEO fraud, and spear phishing. When scammers abuse your domain name, receiving providers like Gmail and Microsoft 365 dock your sender reputation. That means your real invoices and password reset emails end up in the spam folder.

Securing an enterprise mail flow requires three complementary protocols: SPF, DKIM, and DMARC. Working together, they verify server identity, protect message integrity in transit, and enforce strict delivery policies across the internet.

Core Concepts: How the Three Standards Interact

Each standard addresses a distinct blind spot in the SMTP delivery pipeline. Understanding how they interact prevents common deployment mistakes, such as domain alignment failures or broken DNS syntax.

1. SPF (Sender Policy Framework)

SPF is a DNS TXT record on your apex domain. It defines which IP addresses, subnets, and third-party relays are authorized to send mail under your name. When a receiving Mail Transfer Agent (MTA) accepts a connection, it inspects the RFC 5321 Return-Path address (the envelope sender), queries DNS for that domain’s SPF record, and checks if the connecting IP matches.

  • Mechanisms: ip4, ip6, a, mx, and include (delegates lookup to another domain’s SPF record).
  • Qualifiers: + (Pass, default), ~ (SoftFail, accept but tag as suspicious), - (HardFail, reject outright with SMTP code 550), and ? (Neutral).
  • The 10-Lookup Limit: RFC 7208 caps DNS mechanisms at 10 to protect servers against amplification attacks. If your record chains too many SaaS tools (Google Workspace, Zendesk, HubSpot, SendGrid), lookups stop abruptly. Receivers then return a PermError and route your mail to spam.

2. DKIM (DomainKeys Identified Mail)

SPF has a major limitation: it fails whenever an email is forwarded through an intermediary server, such as a mailing list or alias. Furthermore, SPF does nothing to protect email bodies or headers from being modified in transit. DKIM solves both issues using asymmetric cryptography.

Your outgoing server hashes selected email headers alongside the message body. It signs that hash with an RSA private key and embeds the output into a DKIM-Signature header. The recipient MTA grabs your public key from a DNS TXT record under a selector prefix (such as mail._domainkey.example.com) and checks the signature. If a single byte was altered in transit, the signature breaks.

3. DMARC (Domain-based Message Authentication, Reporting, and Conformance)

SPF and DKIM operate independently. Crucially, both authenticate envelope data that everyday users never see. An attacker can send an email that passes SPF via a throwaway server under evil-domain.com while forging [email protected] inside the visible From: header. Most email clients display only the visible From: field, which blinds users to the spoof.

DMARC bridges this gap through Domain Alignment. It requires that the domain shown in the visible From: header match either:

  • The SPF-authenticated envelope domain (Return-Path), or
  • The DKIM signing domain (the d= tag in the DKIM header).

DMARC gives domain owners real enforcement power. You publish a policy telling recipient servers how to handle unaligned messages: monitor only (p=none), divert to spam (p=quarantine), or block the connection during the SMTP handshake (p=reject). Receivers also return daily XML reports (rua) detailing who is sending mail from your domain worldwide.

Hands-on Practice: Hardening Postfix with OpenDKIM

This deployment guide configures OpenDKIM on an Ubuntu 22.04/24.04 server running Postfix. It wraps up with the exact DNS TXT records needed to authenticate example.com.

Step 1: Install and Configure OpenDKIM

First, install OpenDKIM and its command-line utilities:

sudo apt update
sudo apt install opendkim opendkim-tools -y

Back up the default configuration file before editing:

sudo cp /etc/opendkim.conf /etc/opendkim.conf.orig
sudo nano /etc/opendkim.conf

Replace the file contents with these hardened parameters:

AutoRestart             Yes
AutoRestartRate         10/1h
UMask                   002
Syslog                  yes
SyslogSuccess           Yes
LogWhy                  Yes

Canonicalization        relaxed/simple
Mode                    sv
SubDomains              no

# Key and table configuration
KeyTable                refile:/etc/opendkim/key.table
SigningTable            refile:/etc/opendkim/signing.table
ExternalIgnoreList      refile:/etc/opendkim/trusted.hosts
InternalHosts           refile:/etc/opendkim/trusted.hosts

# Milter socket for Postfix (TCP loopback avoids chroot permission issues)
Socket                  inet:[email protected]

Step 2: Generate Cryptographic Keys

Organize keys into dedicated domain directories and lock down permissions:

sudo mkdir -p /etc/opendkim/keys/example.com
sudo chown -R opendkim:opendkim /etc/opendkim
sudo chmod -R 750 /etc/opendkim/keys

Generate a 2048-bit RSA key pair using the selector mail. Stick with 2048-bit keys; 4096-bit keys frequently push DNS responses beyond the standard 512-byte UDP packet limit, causing query timeouts.

sudo opendkim-genkey -b 2048 -d example.com -s mail -D /etc/opendkim/keys/example.com
sudo chown opendkim:opendkim /etc/opendkim/keys/example.com/mail.private
sudo chmod 600 /etc/opendkim/keys/example.com/mail.private

Step 3: Define Tables and Trusted Hosts

Map your signing selector to the private key path in /etc/opendkim/key.table:

echo "mail._domainkey.example.com example.com:mail:/etc/opendkim/keys/example.com/mail.private" | sudo tee /etc/opendkim/key.table

Specify which outbound senders must be signed in /etc/opendkim/signing.table:

echo "*@example.com mail._domainkey.example.com" | sudo tee /etc/opendkim/signing.table

Declare local network addresses that are authorized to request signatures in /etc/opendkim/trusted.hosts:

cat << 'EOF' | sudo tee /etc/opendkim/trusted.hosts
127.0.0.1
localhost
::1
203.0.113.10
*.example.com
example.com
EOF

Start and enable the OpenDKIM service:

sudo systemctl restart opendkim
sudo systemctl enable opendkim

Step 4: Connect OpenDKIM Milter to Postfix

Configure Postfix to route all inbound and outbound email through OpenDKIM via the local TCP socket. Add these directives to /etc/postfix/main.cf:

# Milter filter configuration
milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:127.0.0.1:12301
non_smtpd_milters = inet:127.0.0.1:12301

Verify Postfix syntax and restart the service:

sudo postfix check && sudo systemctl restart postfix

Step 5: Publish DNS Records

Log in to your DNS management console and add the following three TXT records. Replace 203.0.113.10 with your public server IP and example.com with your production domain.

1. SPF Record

Add a TXT record at the apex domain (@):

Type:  TXT
Host:  @
TTL:   3600
Value: v=spf1 ip4:203.0.113.10 ~all

2. DKIM Public Key Record

Read the public key record generated by opendkim-genkey:

sudo cat /etc/opendkim/keys/example.com/mail.txt

Copy the value inside parentheses and publish it at your selector subdomain:

Type:  TXT
Host:  mail._domainkey
TTL:   3600
Value: v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0r...IDAQAB

3. DMARC Policy Record

Always launch DMARC in monitoring mode (p=none). This lets you collect telemetry without accidentally bouncing legitimate emails:

Type:  TXT
Host:  _dmarc
TTL:   3600
Value: v=DMARC1; p=none; sp=none; rua=mailto:[email protected]; pct=100; adkim=r; aspf=r

Step 6: End-to-End Verification

Confirm that your DNS records have propagated using dig:

# Verify SPF
dig +short TXT example.com

# Verify DKIM
dig +short TXT mail._domainkey.example.com

# Test key matching locally
sudo opendkim-testkey -d example.com -s mail -vvv

Note: If opendkim-testkey reports key not secure, do not panic. This simply means your domain does not use DNSSEC. As long as the command outputs key OK, your configuration is sound.

Send a real test message to an external mailbox or an automated header validation tool like Mail-Tester:

echo "Authentication check" | mail -s "Security Test $(date +%s)" [email protected]

Open the raw email headers on the receiving end. Look for these three positive verification lines:

Received-SPF: pass (mymail.example.com: domain of [email protected] designates 203.0.113.10 as permitted sender)
Authentication-Results: dkim=pass (good signature) header.d=example.com header.s=mail;
Authentication-Results: dmarc=pass (p=none dis=none) header.from=example.com

Strategic Implementation Tips

Follow these operational best practices to keep delivery rates high:

  • Roll out DMARC in three stages: Never start with p=reject. Keep your policy at p=none for 3 to 4 weeks while parsing your aggregate XML reports through tools like Postmark or Valimail. You will quickly uncover forgotten SaaS tools, CRM relays, or internal payroll systems sending unauthenticated mail. Once all legitimate senders are aligned, advance to p=quarantine for two weeks. If delivery holds steady, switch to p=reject.
  • Keep SPF lookups under the threshold: If marketing and transactional services push your record past 8 lookups, consolidate them. Move marketing automation to a dedicated subdomain like news.example.com. This gives marketing their own SPF and DKIM profiles without risking your root domain’s limits.
  • Rotate DKIM keys annually: Cryptographic best practices call for rotating 2048-bit keys every 12 months. When rotating, create a new selector (such as mail2026) and publish its public key to DNS first. Wait 24 to 48 hours for DNS caches to refresh before pointing OpenDKIM to the new private key. Keep the old selector record active for another 72 hours so in-flight messages can still be verified.

Deploying this defensive stack turns email authentication from guesswork into verifiable cryptographic proof. Attackers lose the ability to impersonate your staff, and your transactional mail lands reliably in your users’ inboxes.

Share: