DKIM: Cryptographic Email Authentication
What is it?
DomainKeys Identified Mail (DKIM) is an email authentication method that uses cryptographic signatures to verify that an email message was actually sent by the domain it claims to be from and that the message hasn't been altered in transit. While SPF verifies the sending server, DKIM verifies the message content itself through digital signatures.
DKIM operates on public key cryptography, the same fundamental technology underlying HTTPS and secure communications across the internet. The sending mail server signs outgoing messages with a private key, and receiving servers verify those signatures using a public key published in DNS. This creates a cryptographic proof that the message is authentic and unmodified.
Here's how the basic flow works:
Sending Process:
- Your mail server prepares an outgoing message
- It selects specific email headers and the message body to sign
- It generates a cryptographic hash of this content
- It encrypts this hash with a private key kept secret on your server
- It adds a DKIM-Signature header to the message containing this encrypted signature
Receiving Process:
- The recipient's mail server receives the message with the DKIM-Signature header
- It extracts the signature and identifies which domain and selector to use
- It queries DNS for the public key:
selector._domainkey.example.com - It recreates the hash from the same headers and body content
- It decrypts the signature using the public key
- If the decrypted signature matches the recreated hash, the signature is valid
A DKIM-Signature header looks like this:
DKIM-Signature: v=1; a=rsa-sha256; d=example.com; s=2024-02;
c=relaxed/relaxed; q=dns/txt; t=1707667200;
h=from:to:subject:date:message-id;
bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn/nPQzxNWZOQ=;
b=QpLGy5dFjXP8qPHPM7I+mV7G8PzL9xEimPPqNs1234567890abcdef...
This signature indicates:
v=1: DKIM version 1a=rsa-sha256: RSA encryption with SHA-256 hashingd=example.com: Signing domains=2024-02: Selector (identifies which key to use)h=from:to:subject...: Which headers were signedbh=...: Hash of the message bodyb=...: The actual encrypted signature
The corresponding public key is published in DNS as a TXT record at:
2024-02._domainkey.example.com TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ..."
Why does it matter?
DKIM addresses fundamental weaknesses in email that SPF alone cannot solve, providing critical security and trust benefits for your email infrastructure.
Content Integrity Verification
SPF only verifies the sending server - it doesn't protect against message modification. An email could pass SPF validation but be altered by a compromised mail relay, malicious intermediary, or man-in-the-middle attacker. DKIM's cryptographic signature ensures that the message content hasn't been tampered with since leaving the sender's mail server.
Consider this attack scenario: An attacker intercepts an email from your finance department containing wire transfer instructions. They modify the account number to their own while leaving everything else intact. Without DKIM, there's no way for the recipient to detect this tampering. With DKIM, any modification to signed headers or body content invalidates the signature, alerting the recipient that something is wrong.
Stronger Authentication than SPF Alone
SPF has a significant limitation: it only authenticates the envelope sender (MAIL FROM), not the header From address that users actually see. This creates an opportunity for attackers to exploit misalignment:
MAIL FROM: <[email protected]> # Passes SPF
From: CEO <[email protected]> # What the user sees
DKIM signs the header From address, making this type of spoofing detectable. When combined with DMARC's alignment requirements, DKIM provides much stronger protection against sophisticated spoofing attacks.
Email Deliverability
Major email providers use DKIM as a key signal in their spam filtering and sender reputation systems. Gmail, Outlook, Yahoo, and others give preferential treatment to DKIM-signed messages:
- Higher likelihood of inbox placement
- Better sender reputation scores
- Reduced false positive spam classification
- Improved deliverability for marketing emails
Google and Yahoo's 2024 requirements for bulk senders specifically mandate both SPF and DKIM authentication. Without DKIM, your messages may be rejected entirely or heavily penalized in spam scoring.
Long-term Reputation Building
DKIM signatures contribute to sender reputation in ways that persist beyond individual IP addresses. If you change hosting providers or email service providers, your SPF record changes (new IPs), but your DKIM signature domain remains consistent. This allows you to maintain accumulated sender reputation across infrastructure changes.
Non-repudiation
DKIM provides cryptographic proof that a message was sent by a specific domain at a specific time. This creates a form of non-repudiation - the sender cannot later deny having sent the message (assuming their private key remains secure). This is valuable for:
- Legal and compliance requirements
- Audit trails for transactional emails
- Dispute resolution
- Forensic investigation of email-based attacks
Protection Against Forwarding Issues
SPF breaks when messages are forwarded because the forwarding server's IP address doesn't match the original domain's SPF record. DKIM signatures, however, typically survive forwarding intact (assuming the forwarder doesn't modify signed content). This makes DKIM more resilient for legitimate email flows involving forwarding and mailing lists.
Phishing Prevention
While attackers can still send phishing emails from domains they control (and sign them with DKIM), they cannot forge valid DKIM signatures for domains they don't control. When combined with DMARC, this prevents attackers from sending convincing phishing emails that appear to come from your domain.
How attacks work
Understanding attack methodologies helps illustrate DKIM's protective mechanisms and its limitations.
Phase 1: Reconnaissance
Attackers identify targets lacking DKIM or with weak DKIM implementation:
Checking for DKIM presence:
# Send a test email and examine headers
# Look for DKIM-Signature headers
# Query common selector names
dig 20230101._domainkey.example.com TXT
dig selector1._domainkey.example.com TXT
dig default._domainkey.example.com TXT
dig google._domainkey.example.com TXT
Attackers look for:
- Domains with no DKIM signatures
- Weak key lengths (512-bit RSA, easily factored)
- Subdomains without DKIM configuration
- Inconsistent DKIM implementation (some servers sign, others don't)
Phase 2: DKIM Bypass Techniques
Even with DKIM implemented, sophisticated attackers may attempt various bypass techniques:
Exploiting Non-Aligned Signatures
DKIM can sign messages from any domain. An attacker controlling attacker.com can create valid DKIM signatures for their domain while spoofing your domain in ways users will see:
DKIM-Signature: v=1; d=attacker.com; s=key1; ...
From: "Customer Support" <[email protected]>
Reply-To: [email protected]
The DKIM signature is valid (for attacker.com), but users see targetcompany.com in the From field. This is why DMARC alignment is critical - it requires the DKIM signing domain to match the header From domain.
Signature Stripping
Some misconfigured mail servers or email security gateways strip DKIM signatures when they modify message content (adding disclaimers, scanning for malware, etc.). If a mail server doesn't properly resign messages after modification, the original DKIM signature becomes invalid. Attackers might exploit this by:
- Routing emails through known signature-stripping intermediaries
- Social engineering to get victims to use email clients or forwarding rules that strip signatures
- Leveraging compromised mail servers that strip security headers
Replay Attacks
If an attacker intercepts a validly signed email, they could theoretically replay it to different recipients. While the signature remains valid, the attack succeeds because the message appears legitimate. DKIM includes timestamps (t= tag) to mitigate this, but not all receiving servers enforce timestamp validation.
Private Key Compromise
The most serious DKIM attack involves compromising the private key:
- Server breach exposing the key file
- Weak key storage permissions
- Social engineering targeting administrators
- Exploiting vulnerabilities in key management systems
With the private key, an attacker can generate valid DKIM signatures for any message claiming to be from your domain. This is why key security and rotation are critical.
Phase 3: Signature Invalidation Attacks
Attackers might try to invalidate legitimate DKIM signatures to disrupt your email:
Header Modification: If mailing lists or forwarders add headers that were included in the original signature, the signature becomes invalid. Attackers operating compromised mail relays could:
- Add headers that break signatures
- Modify subject lines (common in mailing lists:
[LISTNAME] Subject) - Alter recipient addresses
Body Modification: Similarly, modifying message bodies invalidates signatures:
- Appending disclaimers or advertisements
- Converting text formats
- Adding reply markers (">") in forwarded messages
- Modifying attachments
While these modifications might be benign, they break DKIM validation and could be exploited maliciously.
Phase 4: Subdomain Exploitation
If your main domain has DKIM but subdomains don't, attackers can send emails from subdomains:
From: [email protected]
If mail.targetcompany.com doesn't sign messages with DKIM, attackers can send convincing phishing emails that appear to come from your organization without cryptographic authentication.
Phase 5: Weak Cryptography Exploitation
Older DKIM implementations using 512-bit or 768-bit RSA keys are vulnerable to factorization attacks. With sufficient computational resources, attackers can:
- Collect the public key from DNS
- Factor the modulus to derive the private key
- Generate valid signatures for forged messages
While this requires significant resources, it's within reach of well-funded attackers, nation-state actors, or attackers with access to cloud computing resources.
Real-world incidents
DKIM-related security incidents demonstrate both the importance of proper implementation and the consequences of weak or missing authentication.
Google Gmail DKIM Implementation (2004-2007)
When Google first implemented DKIM for Gmail, they used 512-bit RSA keys. Researchers demonstrated that these keys could be factored with reasonable computational effort, allowing attackers to forge validly signed emails appearing to come from Gmail users. Google promptly upgraded to 1024-bit keys and eventually to 2048-bit keys. This incident established best practices for DKIM key strength.
The 2016 DKIM Key Factorization Study
Security researchers analyzed DKIM keys across millions of domains and found that approximately 1% used weak 512-bit RSA keys. They successfully factored several of these keys and demonstrated the ability to forge emails. The study prompted widespread adoption of stronger key lengths and influenced recommendations that DKIM keys should be at least 1024 bits, preferably 2048 bits.
Business Email Compromise Evolution
Early BEC attacks exploited the absence of any email authentication. As organizations adopted SPF, attackers evolved to exploit SPF's envelope/header mismatch. When organizations added DKIM but not DMARC, attackers sent emails with valid DKIM signatures for their own domains while spoofing the victim's domain in the visible From address. This evolution demonstrates that DKIM must be paired with DMARC alignment to be fully effective.
Mailing List DKIM Breakage
Many organizations discovered DKIM compatibility issues when subscribers to mailing lists stopped receiving their emails. Mailing list software often modifies subject lines (adding [LISTNAME]) and appends footer content, which invalidates DKIM signatures. This led to development of more sophisticated signing practices:
- Signing only essential headers
- Using
relaxedcanonicalization - Implementing list software that properly resigns messages
- Creating special selectors and policies for list-originated mail
Forwarding and DKIM Signature Invalidation
Organizations using email forwarding rules discovered that forwarded messages often failed DKIM validation at the final destination. Some forwarding services modify messages in ways that break signatures, while others preserve them. This issue contributed to the development of ARC (Authenticated Received Chain), an extension to DKIM that preserves authentication results across forwarding hops.
Targeted Attacks Against Key Infrastructure
While specific incidents aren't widely publicized (for obvious security reasons), security researchers have documented cases where attackers specifically targeted DKIM key infrastructure:
- Attempts to compromise servers storing private keys
- Social engineering targeting DNS administrators to modify public key records
- Malware designed to exfiltrate private key files
- Exploitation of vulnerabilities in key management systems
These attacks highlight that DKIM security depends not just on cryptographic strength but also on the security of key storage, access controls, and DNS infrastructure.
What Nyambush detects
Nyambush provides comprehensive DKIM analysis to ensure your email authentication is properly configured and secure.
DKIM Selector Discovery
DKIM public keys are stored in DNS using selectors, and there's no standard way to discover which selectors a domain uses. Nyambush employs multiple techniques:
- Tests common selector names (
default,selector1,selector2,google, current year/month) - Analyzes DMARC reports if available to identify active selectors
- Examines sample emails to extract selectors from DKIM-Signature headers
- Uses Certificate Transparency logs and other public data sources
Public Key Validation
For each discovered selector, Nyambush validates the public key:
# Example DNS query
dig 2024-02._domainkey.example.com TXT
# Expected format
"v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC..."
We check:
- Record exists and is properly formatted
- Version tag
v=DKIM1is present - Key type
k=rsaork=ed25519is specified - Public key
p=is present and valid base64 - Service type
s=emailors=*(if specified) - Flags
t=y(testing mode) ort=s(strict mode)
Key Strength Analysis
Nyambush evaluates cryptographic strength:
-
RSA Key Length: We extract and measure the public key length
- 512-bit: CRITICAL - Easily factored, immediate replacement required
- 768-bit: HIGH - Vulnerable to factorization, upgrade urgently
- 1024-bit: MEDIUM - Acceptable minimum, but 2048-bit recommended
- 2048-bit or higher: GOOD - Industry standard, cryptographically strong
-
Algorithm Assessment: We identify the signing algorithm
rsa-sha1: Deprecated, vulnerable to collision attacksrsa-sha256: Current standard, recommendeded25519-sha256: Modern, efficient, excellent choice
DKIM Signature Testing
Where possible, Nyambush tests actual DKIM signing:
- Analyzes sample emails to verify DKIM signatures are present
- Validates signature cryptographic validity
- Checks which headers are included in signatures
- Verifies body hash matches actual content
- Tests signature alignment with the header From domain
Selector Configuration Issues
We identify common configuration problems:
Multiple selectors with inconsistent policies:
selector1._domainkey.example.com: 2048-bit RSA key
selector2._domainkey.example.com: 512-bit RSA key (weak!)
Inconsistent key strengths across selectors can create vulnerabilities if attackers can influence which selector is used.
Testing mode flags:
v=DKIM1; k=rsa; t=y; p=...
The t=y flag indicates testing mode, where signature failures may be treated leniently. Production selectors should not have this flag.
Overly permissive service types:
v=DKIM1; k=rsa; s=*; p=...
The s=* allows the key to be used for any service. Best practice is s=email to restrict usage.
Subdomain Coverage
Nyambush checks DKIM implementation across subdomains:
- Identifies subdomains that send email but lack DKIM signatures
- Tests whether subdomain selectors exist
- Verifies organizational policies are consistently applied
- Recommends DKIM implementation for discovered subdomains
Key Rotation Analysis
Proper DKIM key management includes regular rotation. Nyambush helps by:
- Identifying selectors that appear to use date-based naming (e.g.,
2024-02) - Flagging keys that haven't been rotated in extended periods
- Checking for obsolete selectors still published in DNS
- Recommending key rotation schedules based on your risk profile
Integration with SPF and DMARC
DKIM is most effective as part of a complete email authentication strategy. Nyambush analyzes:
- Whether DMARC policy is configured
- DMARC alignment mode (strict
svs relaxedr) - Whether DKIM signatures align with the header From domain
- SPF and DKIM coverage gaps
- Recommendations for cohesive email authentication policy
Detailed Reporting
Our DKIM analysis reports include:
- List of all discovered selectors and their security status
- Key strength assessment with specific recommendations
- Configuration issues requiring attention
- Best practice guidance
- Comparison against industry standards
- AI-powered contextual analysis of your specific configuration
How to fix it
Implementing DKIM requires generating key pairs, configuring your mail server to sign messages, and publishing public keys in DNS.
Step 1: Choose Key Parameters
Select cryptographic parameters for your DKIM key:
Key Type:
- RSA: Most widely supported, industry standard
- Ed25519: Modern, efficient, excellent security, but newer and potentially less compatible with older mail servers
Key Length (RSA):
- 2048-bit: Recommended standard
- 4096-bit: Maximum security, but some DNS resolvers may have issues with the large TXT record size
Selector Naming:
- Use descriptive names that facilitate rotation:
2024-02,feb2024,key-2024-02 - Avoid generic names like
defaultorselector1which don't convey versioning information
Step 2: Generate Key Pair
Generate your DKIM key pair using OpenSSL or your mail server's tools:
Using OpenSSL (2048-bit RSA):
# Generate private key
openssl genrsa -out dkim_private.pem 2048
# Extract public key
openssl rsa -in dkim_private.pem -pubout -out dkim_public.pem
# Convert public key to DNS format
# Remove header, footer, and newlines
grep -v "^-" dkim_public.pem | tr -d '\n'
Using opendkim-genkey tool:
# Generate key pair with selector name
opendkim-genkey -t -s 2024-02 -d example.com -b 2048
# This creates two files:
# 2024-02.private - Private key (keep secure!)
# 2024-02.txt - DNS record ready to publish
The generated DNS record format:
2024-02._domainkey.example.com. IN TXT "v=DKIM1; k=rsa; t=y; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA..."
Step 3: Secure the Private Key
The private key must be kept secure:
# Set restrictive permissions (readable only by mail server process)
chmod 600 dkim_private.pem
chown mail:mail dkim_private.pem
# Store in protected directory
mv dkim_private.pem /etc/dkimkeys/
Security best practices:
- Never commit private keys to version control
- Use filesystem encryption for key storage
- Implement access logging for key files
- Consider hardware security modules (HSM) for high-security environments
- Document key locations and access procedures
Step 4: Configure Your Mail Server
Configuration varies by mail server software:
Postfix with OpenDKIM:
Install OpenDKIM:
apt-get install opendkim opendkim-tools
Configure /etc/opendkim.conf:
# Core configuration
Mode sv
Canonicalization relaxed/relaxed
Domain example.com
Selector 2024-02
KeyFile /etc/dkimkeys/dkim_private.pem
Socket inet:8891@localhost
# Security
RequireSafeKeys true
MinimumKeyBits 1024
# Signing options
OversignHeaders From
Configure Postfix /etc/postfix/main.cf:
# DKIM
milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891
Exim:
Configure in /etc/exim/exim.conf:
remote_smtp:
driver = smtp
dkim_domain = example.com
dkim_selector = 2024-02
dkim_private_key = /etc/dkimkeys/dkim_private.pem
dkim_canon = relaxed
dkim_sign_headers = from:to:subject:date:message-id
Microsoft 365:
DKIM for Microsoft 365 is managed through the admin center:
- Sign in to Microsoft 365 admin center
- Navigate to Settings > Domains
- Select your domain
- Click "Enable DKIM signing"
- Microsoft generates keys and provides CNAME records to add to your DNS
- Add the two CNAME records:
selector1._domainkey.example.com CNAME selector1-example-com._domainkey.tenant.onmicrosoft.com
selector2._domainkey.example.com CNAME selector2-example-com._domainkey.tenant.onmicrosoft.com
- Wait for DNS propagation
- Return to Microsoft 365 admin center and complete enablement
Google Workspace:
- Sign in to Google Admin console
- Navigate to Apps > Google Workspace > Gmail > Authenticate email
- Click "Generate new record"
- Google provides a DNS TXT record to publish
- Add the record to your DNS:
google._domainkey.example.com TXT "v=DKIM1; k=rsa; p=MIIBIjAN..."
- Wait for DNS propagation
- Return to Admin console and click "Start authentication"
Step 5: Publish Public Key in DNS
Add the public key as a TXT record in your DNS zone:
Cloudflare:
- Log in to Cloudflare dashboard
- Select your domain
- Navigate to DNS > Records
- Click "Add record"
- Type: TXT
- Name:
2024-02._domainkey - Content:
v=DKIM1; k=rsa; p=MIIBIjAN...(your full public key) - TTL: 3600 (1 hour)
- Click "Save"
AWS Route 53 (CLI):
aws route53 change-resource-record-sets \
--hosted-zone-id Z1234567890ABC \
--change-batch '{
"Changes": [{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "2024-02._domainkey.example.com",
"Type": "TXT",
"TTL": 3600,
"ResourceRecords": [{
"Value": "\"v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...\""
}]
}
}]
}'
Important: If your public key is longer than 255 characters, you must split it into multiple strings:
"v=DKIM1; k=rsa; " "p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA..." "remaining_key_data..."
Step 6: Start in Testing Mode
When first implementing DKIM, use testing mode:
v=DKIM1; k=rsa; t=y; p=...
The t=y flag tells receiving servers that you're testing and they should be lenient with validation failures.
Step 7: Test DKIM Signing
Verify your implementation:
Check DNS propagation:
dig 2024-02._domainkey.example.com TXT
nslookup -type=TXT 2024-02._domainkey.example.com
Send test emails:
Send emails to test addresses and examine headers:
DKIM-Signature: v=1; a=rsa-sha256; d=example.com; s=2024-02;
c=relaxed/relaxed; q=dns/txt; t=1707667200;
h=from:to:subject:date:message-id;
bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn/nPQzxNWZOQ=;
b=QpLGy5dFjXP8qPHPM7I+mV7G8PzL9xEimPPqNs...
Authentication-Results: gmail.com;
dkim=pass header.d=example.com header.s=2024-02 header.b=QpLGy5dF;
Use online validators:
- Send email to [email protected] (automated reply with full analysis)
- Use MXToolbox: https://mxtoolbox.com/dkim.aspx
- Google Admin Toolbox: https://toolbox.googleapps.com/apps/checkmx/
- Nyambush scan results
Step 8: Monitor and Transition to Production
Monitor DKIM performance:
- Check mail server logs for signing errors
- Analyze DMARC aggregate reports for DKIM statistics
- Monitor deliverability metrics
- Verify signatures on outbound emails
After successful testing (1-2 weeks), transition to production by removing testing flag:
v=DKIM1; k=rsa; p=...
(Remove t=y)
Step 9: Implement Key Rotation
Establish a key rotation schedule:
Rotation frequency recommendations:
- Standard risk: Annually
- High-security environments: Quarterly
- After suspected compromise: Immediately
Rotation process:
- Generate new key pair with new selector (
2024-03) - Publish new public key in DNS
- Configure mail server to sign with new key
- Keep old public key published for 1-2 weeks (to verify delayed emails)
- Remove old public key from DNS
- Securely delete old private key
Step 10: Protect Subdomains
Configure DKIM for all subdomains that send email:
2024-02._domainkey.mail.example.com TXT "v=DKIM1; k=rsa; p=..."
For subdomains that never send email, publish a null DKIM policy (preventing spoofing):
*._domainkey.cdn.example.com TXT "v=DKIM1; p="
The empty p= indicates no valid public key exists, so any DKIM signature claiming to be from this subdomain is invalid.
Summary
DomainKeys Identified Mail (DKIM) provides cryptographic authentication for email messages through digital signatures. Unlike SPF, which only verifies the sending server, DKIM signs the actual message content with a private key and allows receiving servers to verify authenticity and integrity using a public key published in DNS. This protects against message tampering, provides stronger authentication than SPF alone, improves deliverability, and enables non-repudiation.
DKIM works through public key cryptography. Sending servers sign outgoing messages, adding a DKIM-Signature header containing the cryptographic signature. Receiving servers retrieve the public key from DNS (using the domain and selector specified in the signature), recreate the hash from message content, and verify it matches the decrypted signature. A valid signature proves the message is authentic and unmodified.
The technology addresses critical security gaps. Email content can be tampered with in transit, SPF's envelope/header mismatch allows sophisticated spoofing, and modern email providers require DKIM for optimal deliverability. Real-world incidents have demonstrated the consequences of weak DKIM implementation, including factored 512-bit keys, BEC attacks exploiting missing authentication, and mailing list compatibility issues.
Implementation requires generating cryptographically strong key pairs (2048-bit RSA or Ed25519), securing the private key with restrictive permissions and access controls, configuring your mail server to sign outbound messages, and publishing the public key in DNS using selector-based naming. Start with testing mode, validate implementation thoroughly, monitor DKIM results in DMARC reports, and establish regular key rotation schedules.
Nyambush automates DKIM validation through selector discovery, public key retrieval and validation, cryptographic strength analysis, configuration issue identification, subdomain coverage checks, and integration with SPF/DMARC analysis. We identify weak keys requiring immediate replacement, detect configuration problems, and provide specific remediation guidance.
DKIM is most effective when combined with SPF and DMARC to create comprehensive email authentication. SPF validates sending servers, DKIM validates message content, and DMARC enforces alignment between these mechanisms while providing visibility through aggregate reports. Together, they transform email from an easily spoofable protocol into a cryptographically authenticated communication channel.
Don't leave your email authentication incomplete. Implement DKIM to protect message integrity, strengthen your sender reputation, improve deliverability, and defend against sophisticated email-based attacks. Use Nyambush to validate your DKIM configuration and ensure your cryptographic signatures provide maximum protection.