Email Authenticationยถ
Understanding how SPF, DKIM, and DMARC work together to secure email.
Overviewยถ
Email authentication is a collection of techniques designed to prove that emails are genuinely from who they claim to be. It protects against:
- Phishing - Fraudulent emails impersonating trusted senders
- Spoofing - Forging sender addresses
- Spam - Unsolicited bulk email
- Business Email Compromise (BEC) - Impersonating executives or vendors
The three core protocols - SPF, DKIM, and DMARC - work together to provide comprehensive email security.
The Email Security Triadยถ
graph TB
A[Email Authentication] --> B[SPF]
A --> C[DKIM]
A --> D[DMARC]
B --> E[Validates<br/>Sending Server]
C --> F[Validates<br/>Message Integrity]
D --> G[Enforces Policy &<br/>Provides Reports]
E --> H[Complete<br/>Email Security]
F --> H
G --> H
SPF (Sender Policy Framework)ยถ
What it does: Verifies the sending mail server is authorized
How it works: DNS TXT record lists authorized IP addresses
Example:
Learn more: SPF Deep Dive
DKIM (DomainKeys Identified Mail)ยถ
What it does: Cryptographically signs emails to prove authenticity
How it works: Private key signs email, public key in DNS verifies signature
Example:
Learn more: DKIM Deep Dive
DMARC (Domain-based Message Authentication, Reporting & Conformance)ยถ
What it does: Enforces SPF/DKIM policies and provides reporting
How it works: DNS TXT record tells receivers what to do with failed authentication
Example:
Learn more: DMARC Deep Dive
How They Work Togetherยถ
The Complete Authentication Flowยถ
sequenceDiagram
participant Sender as Sending Server
participant DNS as DNS Servers
participant Receiver as Receiving Server
participant User as End User
Note over Sender: 1. Email Preparation
Sender->>Sender: Create email
Sender->>Sender: Sign with DKIM<br/>(private key)
Note over Sender,Receiver: 2. Email Transmission
Sender->>Receiver: Send email via SMTP
Note over Sender,Receiver: From: user@example.com
Note over Receiver,DNS: 3. SPF Verification
Receiver->>DNS: Query SPF record<br/>example.com TXT
DNS->>Receiver: v=spf1 ip4:192.0.2.1 -all
Receiver->>Receiver: Check sender IP<br/>192.0.2.1 matches? โ SPF PASS
Note over Receiver,DNS: 4. DKIM Verification
Receiver->>DNS: Query DKIM key<br/>selector._domainkey.example.com
DNS->>Receiver: v=DKIM1; k=rsa; p=PUBLIC_KEY
Receiver->>Receiver: Verify signature<br/>with public key โ DKIM PASS
Note over Receiver,DNS: 5. DMARC Policy Check
Receiver->>DNS: Query DMARC policy<br/>_dmarc.example.com
DNS->>Receiver: v=DMARC1; p=reject
Receiver->>Receiver: Check alignment:<br/>SPF domain = From domain โ<br/>DKIM domain = From domain โ<br/>โ DMARC PASS
Note over Receiver,User: 6. Delivery Decision
Receiver->>User: Deliver to inbox
Note over Receiver,Sender: 7. Reporting
Receiver->>Sender: Send DMARC report<br/>(aggregate/forensic)
Authentication Decision Treeยถ
graph TD
A[Email Arrives] --> B{SPF Check}
B -->|Pass| C{SPF Aligned?}
B -->|Fail| D{DKIM Check}
C -->|Yes| E[SPF Aligned โ]
C -->|No| D
D -->|Pass| F{DKIM Aligned?}
D -->|Fail| G[Both Failed]
F -->|Yes| H[DKIM Aligned โ]
F -->|No| G
E --> I{DMARC Policy}
H --> I
G --> I
I -->|Pass + p=any| J[Deliver to Inbox]
I -->|Fail + p=none| K[Deliver + Report]
I -->|Fail + p=quarantine| L[Send to Spam]
I -->|Fail + p=reject| M[Reject Email]
Why All Three Are Neededยถ
SPF Alone is Not Enoughยถ
Problem 1: No integrity checking
Attacker modifies email subject/body in transit
SPF: PASS (came from authorized server)
Result: Tampered email delivered โ
Problem 2: Envelope vs Header mismatch
MAIL FROM: legitimate@example.com (SPF checks this)
From: attacker@evil.com (User sees this)
Result: SPF passes but user sees fake sender โ
Problem 3: No policy enforcement
SPF: FAIL
Receiver: "SPF failed, but what should I do?" ๐คท
Result: Inconsistent handling across receivers
DKIM Alone is Not Enoughยถ
Problem 1: Domain mismatch allowed
From: victim@example.com
DKIM d=: attacker.com (signs with own domain)
Result: DKIM passes but domains don't match โ
Problem 2: No sending server validation
Email comes from unauthorized server
DKIM: PASS (signature valid)
Result: Phishing email with valid signature โ
Problem 3: No policy guidance
DMARC Ties It All Togetherยถ
Solution 1: Alignment requirement
From: user@example.com
SPF domain: example.com โ Aligned
DKIM d=: example.com โ Aligned
Result: Both must match From header
Solution 2: Policy enforcement
Solution 3: Visibility
DMARC aggregate reports show:
- Who's sending email for your domain
- Authentication pass/fail rates
- Which receivers are applying policy
Result: Complete visibility โ
Real-World Scenariosยถ
Scenario 1: Legitimate Email (All Pass)ยถ
Email Details:
From: support@example.com
MAIL FROM: bounce@mail.example.com
Sending IP: 192.0.2.1
DNS Configuration:
SPF: v=spf1 ip4:192.0.2.0/24 -all
DKIM: selector._domainkey.example.com (2048-bit key)
DMARC: v=DMARC1; p=reject
Authentication Results:
โ SPF PASS (IP matches)
โ SPF Aligned (mail.example.com โ example.com)
โ DKIM PASS (signature valid)
โ DKIM Aligned (d=example.com)
โ DMARC PASS
Action: Deliver to inbox
Scenario 2: Phishing Attempt (All Fail)ยถ
Email Details:
From: ceo@yourcompany.com (spoofed)
MAIL FROM: attacker@evil.com
Sending IP: 203.0.113.1 (attacker's server)
DNS Configuration (yourcompany.com):
SPF: v=spf1 include:_spf.google.com -all
DKIM: google._domainkey.yourcompany.com
DMARC: v=DMARC1; p=reject
Authentication Results:
โ SPF FAIL (IP not authorized)
โ SPF NOT Aligned (evil.com โ yourcompany.com)
โ DKIM FAIL (no signature or invalid)
โ DMARC FAIL
Action: Reject email (p=reject)
Report: Send aggregate report to yourcompany.com
Scenario 3: Mailing List (Forwarding Challenge)ยถ
Original Email:
From: user@example.com
MAIL FROM: user@example.com
Sending IP: 192.0.2.1
After Mailing List Forward:
From: user@example.com (unchanged)
MAIL FROM: list@mailinglist.com (changed by list)
Sending IP: 198.51.100.1 (mailing list server)
Subject: [List] Original subject (modified)
Authentication Results:
โ SPF FAIL (new IP not in example.com SPF)
โ SPF NOT Aligned (list domain โ example.com)
โ DKIM PASS (signature survives if body not modified)
โ DKIM Aligned (d=example.com)
โ DMARC PASS (DKIM alignment sufficient!)
Action: Deliver to inbox
Note: DKIM saves forwarded emails
Scenario 4: Legitimate Third-Party Serviceยถ
Email Details:
From: newsletter@company.com
MAIL FROM: bounce@sendgrid.net
Sending IP: 198.51.100.1 (SendGrid)
DKIM: d=company.com (SendGrid signs with customer domain)
DNS Configuration (company.com):
SPF: v=spf1 include:_spf.google.com include:sendgrid.net -all
DKIM: em123._domainkey.company.com (SendGrid key)
DMARC: v=DMARC1; p=quarantine
Authentication Results:
โ SPF PASS (SendGrid in SPF include)
โ SPF NOT Aligned (sendgrid.net โ company.com)
โ DKIM PASS (valid SendGrid signature)
โ DKIM Aligned (d=company.com)
โ DMARC PASS (DKIM alignment sufficient)
Action: Deliver to inbox
Alignment: The Key Conceptยถ
Alignment is what makes DMARC powerful - it ensures the authenticated domain matches what users see.
Why Alignment Mattersยถ
Without alignment:
From: victim@bank.com (what user sees)
SPF domain: attacker.com (passes SPF)
DKIM domain: attacker.com (passes DKIM)
Problem: Authentication passes but domains don't match!
With alignment:
From: victim@bank.com
SPF domain: must be bank.com or *.bank.com
DKIM domain: must be bank.com or *.bank.com
Result: At least one must align with From header
Relaxed vs Strict Alignmentยถ
Relaxed Alignment (Default)ยถ
Organizational domains match:
From: user@example.com
SPF: mail.example.com โ โ Aligned
DKIM d=: email.example.com โ โ Aligned
Rule: example.com = example.com (base domain matches)
Configuration:
Strict Alignmentยถ
Exact domains match:
From: user@example.com
SPF: mail.example.com โ โ NOT Aligned
DKIM d=: example.com โ โ Aligned
Rule: example.com โ mail.example.com (exact match required)
Configuration:
Recommendation: Use relaxed (default) for better compatibility with email services.
Progressive Implementation Strategyยถ
Phase 1: Foundation (Week 1-2)ยถ
Goal: Establish basic authentication
Steps: 1. Configure SPF
-
Generate and publish DKIM keys
-
Add DMARC in monitoring mode
-
Validate with ReputeAPI
Expected score: 55-65 (Fair)
Phase 2: Monitoring (Week 3-4)ยถ
Goal: Gather data and identify issues
Steps: 1. Review DMARC aggregate reports - Identify all legitimate sending sources - Check authentication pass rates - Look for unauthorized senders
- Fix any issues found
- Add missing IPs to SPF
- Configure DKIM for all services
-
Update third-party service settings
-
Achieve 100% pass rate
- All legitimate email passes SPF or DKIM
- No false positives
Expected score: Still 55-65 (p=none gives no enforcement points)
Phase 3: Enforcement - Quarantine (Week 5-6)ยถ
Goal: Begin policy enforcement safely
Steps: 1. Upgrade to quarantine policy
- Monitor for issues
- Check spam folders for legitimate email
- Review user complaints
-
Monitor DMARC reports
-
Adjust if needed
- Add missed sources to SPF
- Fix DKIM signatures
- Temporary rollback if critical issues
Expected score: 70-80 (Good)
Phase 4: Maximum Protection (Week 7+)ยถ
Goal: Achieve full protection
Steps: 1. Upgrade to reject policy
-
Optional: Gradual rollout
-
Continuous monitoring
- Weekly report review
- Monthly configuration audit
- Investigate all failures
Expected score: 90-100 (Excellent)
Email Authentication for Different Use Casesยถ
Small Business (Google Workspace)ยถ
Configuration:
# SPF
example.com. IN TXT "v=spf1 include:_spf.google.com -all"
# DKIM (configured in Google Admin Console)
google._domainkey.example.com. IN TXT "v=DKIM1; k=rsa; p=KEY..."
# DMARC
_dmarc.example.com. IN TXT "v=DMARC1; p=reject; rua=mailto:dmarc@example.com"
Timeline: 2-3 weeks to full deployment
Enterprise (Multiple Email Services)ยถ
Configuration:
# SPF - Multiple providers
example.com. IN TXT "v=spf1 include:_spf.google.com include:sendgrid.net include:_spf.salesforce.com -all"
# DKIM - Multiple selectors
google._domainkey.example.com. IN TXT "v=DKIM1; p=KEY1..."
em123._domainkey.example.com. IN TXT "v=DKIM1; p=KEY2..."
salesforce._domainkey.example.com. IN TXT "v=DKIM1; p=KEY3..."
# DMARC - Comprehensive reporting
_dmarc.example.com. IN TXT "v=DMARC1; p=reject; rua=mailto:dmarc@example.com,mailto:reports@dmarcanalyzer.com; ruf=mailto:forensic@example.com"
Timeline: 6-8 weeks with extensive testing
E-commerce (High Volume Transactional)ยถ
Configuration:
# SPF - Transactional ESP
example.com. IN TXT "v=spf1 include:sendgrid.net -all"
# DKIM - Dedicated selector
transactions._domainkey.example.com. IN TXT "v=DKIM1; k=rsa; p=KEY..."
# DMARC - Strict policy
_dmarc.example.com. IN TXT "v=DMARC1; p=reject; pct=100; adkim=s; rua=mailto:dmarc@example.com"
# Subdomain for marketing
_dmarc.marketing.example.com. IN TXT "v=DMARC1; p=quarantine; rua=mailto:dmarc@example.com"
Timeline: 4-6 weeks with phased rollout
No Email Sent (Domain Parking)ยถ
Configuration:
# SPF - Reject all
example.com. IN TXT "v=spf1 -all"
# DMARC - Reject policy
_dmarc.example.com. IN TXT "v=DMARC1; p=reject"
Timeline: Immediate deployment
Common Challenges and Solutionsยถ
Challenge 1: Email Forwardingยถ
Problem: Forwarded emails fail SPF alignment
Solution: - Use DKIM (survives forwarding better) - Implement ARC (Authenticated Received Chain) - Use relaxed alignment (default)
Example:
Challenge 2: Mailing Listsยถ
Problem: Lists modify emails, breaking signatures
Solution: - Configure list to preserve DKIM - List adds its own DKIM signature - ARC support preserves original authentication
Best practice:
List should:
1. Not modify From header
2. Add own DKIM signature
3. Support ARC
4. Use VERP for bounces
Challenge 3: Third-Party Servicesยถ
Problem: Marketing/transactional email services need authentication
Solution:
- Add to SPF with include:
- Delegate DKIM to service
- Verify alignment regularly
Example (SendGrid):
# SPF
example.com. IN TXT "v=spf1 include:sendgrid.net -all"
# DKIM (provided by SendGrid)
em123._domainkey.example.com. IN TXT "v=DKIM1; k=rsa; p=KEY..."
# DMARC
_dmarc.example.com. IN TXT "v=DMARC1; p=reject"
Challenge 4: SPF 10 Lookup Limitยถ
Problem: Too many includes exceed DNS lookup limit
Solution: - Use IP addresses instead of includes - SPF flattening service - Separate subdomains for different services
Example:
# Instead of many includes
v=spf1 include:provider1 include:provider2 include:provider3 -all
# Use IP ranges
v=spf1 ip4:192.0.2.0/24 ip4:198.51.100.0/24 -all
# Or subdomains
marketing.example.com. โ separate SPF
transactional.example.com. โ separate SPF
Challenge 5: Multiple Domainsยถ
Problem: Managing authentication for many domains
Solution: - Infrastructure as Code (Terraform) - Centralized monitoring - Automated testing
Example Terraform:
# domains.tf
locals {
domains = ["example1.com", "example2.com", "example3.com"]
}
resource "cloudflare_record" "spf" {
for_each = toset(local.domains)
zone_id = var.zone_ids[each.key]
name = "@"
type = "TXT"
value = "v=spf1 include:_spf.google.com -all"
}
Monitoring and Maintenanceยถ
Daily Monitoringยถ
Automated checks:
import requests
def daily_check(domain):
"""Daily email security check"""
response = requests.get(
f"https://api.reputeapi.com/api/v1/check",
params={"domain": domain, "refresh": True},
headers={"X-API-Key": "your-api-key"}
)
result = response.json()
# Alert on score drop
if result['score'] < 90:
send_alert(f"Email security score: {result['score']}")
# Alert on critical issues
critical = [i for i in result['issues'] if i['severity'] == 'critical']
if critical:
send_alert(f"Critical issues: {critical}")
Weekly Tasksยถ
- [ ] Review DMARC aggregate reports
- [ ] Check for new unauthorized senders
- [ ] Verify authentication pass rates
- [ ] Investigate failures
Monthly Tasksยถ
- [ ] Audit complete configuration
- [ ] Review SPF includes for changes
- [ ] Test DKIM signatures
- [ ] Update documentation
Quarterly Tasksยถ
- [ ] Rotate DKIM keys (if policy requires)
- [ ] Security audit
- [ ] Compliance review
- [ ] Update disaster recovery plan
Testing Your Configurationยถ
Comprehensive Testยถ
#!/bin/bash
DOMAIN="example.com"
API_KEY="your-api-key"
echo "==================================="
echo "Email Authentication Test"
echo "Domain: $DOMAIN"
echo "==================================="
# 1. ReputeAPI validation
echo -e "\n1. Running ReputeAPI check..."
curl -s "https://api.reputeapi.com/api/v1/check?domain=$DOMAIN" \
-H "X-API-Key: $API_KEY" | jq '{score, spf, dkim, dmarc, issues}'
# 2. DNS queries
echo -e "\n2. Checking DNS records..."
echo "SPF:"
dig +short $DOMAIN TXT | grep spf
echo -e "\nDKIM (google selector):"
dig +short google._domainkey.$DOMAIN TXT
echo -e "\nDMARC:"
dig +short _dmarc.$DOMAIN TXT
# 3. Send test email
echo -e "\n3. Send test email to: test@mail-tester.com"
echo "Then check score at: https://www.mail-tester.com"
echo -e "\n==================================="
echo "Test complete!"
Validation Checklistยถ
SPF Validationยถ
- [ ] Record exists at root domain
- [ ] Only ONE SPF record
- [ ] All sending sources included
- [ ] Ends with
-all(hard fail) - [ ] Less than 10 DNS lookups
- [ ] No syntax errors
DKIM Validationยถ
- [ ] Keys published for all selectors
- [ ] Key size โฅ 2048 bits
- [ ] Mail server signing emails
- [ ] Signatures include From header
- [ ] Public key matches private key
- [ ] No syntax errors
DMARC Validationยถ
- [ ] Record exists at _dmarc subdomain
- [ ] Policy set (p=none/quarantine/reject)
- [ ] Aggregate reports configured (rua=)
- [ ] Percentage at 100% (pct=100)
- [ ] Alignment mode appropriate
- [ ] No syntax errors
Measuring Successยถ
Key Performance Indicatorsยถ
Authentication Pass Rateยถ
Email Deliverabilityยถ
Security Scoreยถ
Spoofing Preventionยถ
ReputeAPI Monitoringยถ
import requests
from datetime import datetime, timedelta
def track_score_trend(domain, days=30):
"""Track email security score over time"""
response = requests.get(
"https://api.reputeapi.com/api/v1/history",
params={"domain": domain, "days": days},
headers={"X-API-Key": "your-api-key"}
)
history = response.json()
print(f"Score trend for {domain} (last {days} days):\n")
print(f"{'Date':<12} {'Score':<6} {'Grade':<10}")
print("-" * 30)
for snapshot in history['snapshots']:
date = datetime.fromisoformat(snapshot['timestamp']).strftime('%Y-%m-%d')
score = snapshot['score']
grade = snapshot['grade']
print(f"{date:<12} {score:<6} {grade:<10}")
# Calculate improvement
if len(history['snapshots']) >= 2:
first = history['snapshots'][0]['score']
last = history['snapshots'][-1]['score']
improvement = last - first
print(f"\nImprovement: {improvement:+d} points")
Best Practices Summaryยถ
โ Do'sยถ
- Start with p=none - Monitor before enforcing
- Use both SPF and DKIM - Redundancy is critical
- Enable DMARC reports - Essential for visibility
- Set pct=100 - Full protection, not partial
- Use -all for SPF - Hard fail for security
- 2048-bit DKIM keys - Minimum key size
- Regular monitoring - Check reports weekly
- Document everything - Configuration and changes
- Test thoroughly - Before production deployment
- Automate - Use IaC and monitoring tools
โ Don'tsยถ
- Don't skip monitoring - p=none phase is critical
- Don't use +all or ?all - Provides no protection
- Don't exceed 10 SPF lookups - Causes PermError
- Don't forget subdomains - Protect all domains
- Don't ignore reports - They contain critical data
- Don't use weak DKIM keys - <2048 bits is insecure
- Don't make uncoordinated changes - Test first
- Don't set and forget - Requires ongoing maintenance
- Don't rely on SPF alone - Forwarding breaks it
- Don't rush to p=reject - Follow progressive rollout
Getting Helpยถ
ReputeAPI Resourcesยถ
- API Documentation - Complete API reference
- Quick Start Guide - Get started in 5 minutes
- Integration Examples - Code samples
External Resourcesยถ
Standards & RFCs: - RFC 7208 - SPF - RFC 6376 - DKIM - RFC 7489 - DMARC
Testing Tools: - MXToolbox - Mail Tester - Google Admin Toolbox
DMARC Report Analyzers: - DMARC Analyzer - Postmark DMARC - EasyDMARC
Related Documentationยถ
Core Conceptsยถ
- SPF Explained - Deep dive into SPF
- DKIM Explained - Deep dive into DKIM
- DMARC Explained - Deep dive into DMARC
- DNS Configuration - Provider-specific DNS setup
- Mailflow Security Score - Understanding the scoring system
Getting Startedยถ
- Quick Start - 5-minute setup
- Authentication Guide - API keys
- Common Errors - Troubleshooting
API Referenceยถ
- GET /api/v1/check - Comprehensive validation
- POST /api/v1/recommendations - Get recommendations
- GET /api/v1/history - Historical trends
Summaryยถ
Email authentication with SPF, DKIM, and DMARC provides comprehensive protection against phishing, spoofing, and email fraud. By working together, these protocols:
- โ Verify sender identity (SPF)
- โ Ensure message integrity (DKIM)
- โ Enforce security policies (DMARC)
- โ Provide visibility (DMARC reports)
- โ Build sender reputation (all three)
Implementation timeline: 2-8 weeks depending on complexity
Maintenance: Ongoing monitoring and regular audits
ReputeAPI helps with validation, scoring, recommendations, and monitoring throughout your email authentication journey.
Ready to improve your email security? Get started with ReputeAPI today.