# Email Security (SPF, DKIM, DMARC)

> Chapter 37 of the Courseiva SECURITY-PLUS curriculum — https://courseiva.com/learn/security-plus/email-security

**Official objective:** 4.4 — Security Operations

## Introduction

SPF, DKIM, and DMARC are the three core email authentication protocols that defend against email spoofing and phishing. For the SY0-701 exam, objective 4.4 (Security Operations) requires you to understand how these controls prevent domain impersonation and ensure email integrity. You'll learn the mechanism of each protocol, how they work together, and common misconfigurations that attackers exploit.

## Email Security as a Package Delivery System

Hundreds of packages arrive at your business each day from various carriers. SPF is like having a list of authorized delivery drivers that your local post office checks. If a driver shows up not on the list, the package is rejected. However, a clever thief can forge a driver's badge and still deliver a package. DKIM is like a tamper-evident seal on the package that is signed by the sender's private key. The recipient can verify the seal using the sender's public key, ensuring the package wasn't opened or swapped. But even with a seal, the thief could use a stolen seal from a legitimate sender. DMARC is the final layer: it tells the recipient what to do if both SPF and DKIM checks fail—either reject the package, quarantine it, or allow it with a warning. It also requires the sender to publish a policy and receive reports on failures. Without DMARC, the recipient might accept a forged package that passes SPF or DKIM individually. Together, they form a defense against email spoofing, just as a delivery system with driver IDs, tamper seals, and clear instructions prevents package fraud.

## Core explanation

### What Are SPF, DKIM, and DMARC?

Email spoofing is a technique where an attacker forges the 'From' address to make an email appear to come from a trusted domain. Without authentication, any mail server can claim any sender. SPF (Sender Policy Framework), DKIM (DomainKeys Identified Mail), and DMARC (Domain-based Message Authentication, Reporting, and Conformance) are DNS-based standards that verify the legitimacy of email senders. They are defined in RFC 7208 (SPF), RFC 6376 (DKIM), and RFC 7489 (DMARC).

### SPF (Sender Policy Framework)

SPF allows a domain owner to publish a list of IP addresses authorized to send email on behalf of that domain. The list is stored as a TXT record in DNS. When a receiving mail server gets an email, it checks the SPF record of the domain in the 'Envelope From' (Return-Path) address. If the sending IP is not in the list, SPF fails.

**How SPF Works Mechanically:**
1. Sender's domain owner creates a TXT record like: `v=spf1 ip4:192.0.2.0/24 include:_spf.google.com ~all`
2. Sender's mail server sends an email with Return-Path: `sender@example.com`.
3. Receiver's mail server looks up the SPF record for `example.com`.
4. Receiver compares the sender's IP against the allowed IPs in the record.
5. Result: pass, fail, softfail, neutral, or none.

**SPF Mechanisms and Qualifiers:**
- `ip4`/`ip6`: specify allowed IP ranges.
- `include`: delegates to another domain's SPF record.
- `a`: allows the domain's A record IP.
- `mx`: allows the domain's MX server IPs.
- `all`: matches any IP (used at end). Qualifiers: `+` (pass), `-` (fail), `~` (softfail), `?` (neutral).

**Common SPF Mistakes:**
- Using `~all` (softfail) instead of `-all` (hardfail) gives attackers leeway.
- Forgetting to include all legitimate sending services (e.g., third-party email marketing).
- Exceeding the 10-DNS-lookup limit (SPF allows a maximum of 10 DNS lookups per evaluation).

### DKIM (DomainKeys Identified Mail)

DKIM adds a digital signature to the email headers. The signature is created using the sender's private key, and the public key is published in DNS. This ensures the email was not tampered with during transit and that the email originated from a domain the sender controls.

**How DKIM Works Mechanically:**
1. Sender's mail server signs the email (headers and body) with a private key. The signature is inserted as a `DKIM-Signature` header.
2. The signature includes fields like `v=1; a=rsa-sha256; d=example.com; s=selector; bh=...; h=...; b=...`
   - `d`: domain of the signer.
   - `s`: selector (used to locate the public key in DNS).
   - `bh`: body hash.
   - `b`: actual signature.
3. Receiver extracts the domain (`d`) and selector (`s`) from the header.
4. Receiver constructs the DNS TXT record: `selector._domainkey.example.com` and retrieves the public key.
5. Receiver verifies the signature using the public key. If the body or headers changed, verification fails.

**DKIM Key Points:**
- The signature covers specific headers (default: From, Date, Subject, etc.) and the body.
- Algorithms: RSA (1024-2048 bits) and newer Ed25519 (RFC 8463).
- Selector allows multiple keys for rotation (e.g., `google._domainkey.example.com`).
- DKIM does not prevent spoofing of the visible 'From' address; it only verifies the signing domain.

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

DMARC builds on SPF and DKIM. It tells the receiver what to do if both SPF and DKIM checks fail. It also provides reporting so domain owners can see authentication failures.

**How DMARC Works Mechanically:**
1. Domain owner publishes a DMARC policy in DNS as a TXT record at `_dmarc.example.com`.
2. Record format: `v=DMARC1; p=reject; rua=mailto:dmarc@example.com; pct=100`
   - `p`: policy (none, quarantine, reject).
   - `rua`: aggregate report URI.
   - `ruf`: forensic report URI (optional).
   - `pct`: percentage of emails to apply policy to.
   - `sp`: policy for subdomains.
   - `adkim`/`aspf`: strict or relaxed alignment for DKIM/SPF.
3. Receiver checks SPF and DKIM. For DMARC to pass, at least one must pass AND the domain in the 'From' header must align with the domain used in SPF (Return-Path) or DKIM (d=).
   - **Alignment:** For SPF, the domain in the 'From' header must match the domain in the Return-Path (or be a subdomain). For DKIM, the 'd=' domain must match the 'From' domain.
4. If both fail, the receiver applies the DMARC policy: `none` (no action, but reports sent), `quarantine` (mark as spam), or `reject` (drop the email).

**DMARC Alignment Modes:**
- Relaxed (`aspf:r`): allows subdomain matches (e.g., From: user@example.com, SPF domain: sub.example.com passes).
- Strict (`aspf:s`): must be exact match.

### How Attackers Exploit Weak Email Authentication

Without SPF, attackers can send emails with a forged 'From' address and no one checks. Without DKIM, they can alter email content. Without DMARC, even if SPF or DKIM fails, the email may still be delivered. Attackers also exploit:
- **SPF bypass:** If SPF uses `~all` (softfail), many servers treat it as fail but still deliver. Attackers can send from a non-listed IP and the email might get through.
- **DKIM domain mismatch:** An attacker can sign with their own domain's DKIM key, but the 'From' address is a victim domain. Without DMARC alignment, this can pass DKIM but the 'From' domain is not verified.
- **Missing DMARC policy:** If no DMARC record exists, receivers may accept spoofed emails.
- **Lookup limits:** SPF with too many includes can hit the 10-lookup limit, causing a permerror that may result in 'neutral' (no action).

### Defenders' Deployment

To deploy these protocols:
1. **SPF:** Publish a TXT record with all legitimate sending IPs. Use `-all` for hard fail. Example:
   ```
   v=spf1 ip4:203.0.113.0/24 include:_spf.google.com -all
   ```
2. **DKIM:** Generate a key pair (e.g., using OpenSSL):
   ```
   openssl genrsa -out private.key 2048
   openssl rsa -in private.key -pubout -out public.key
   ```
   Publish the public key in DNS as `selector._domainkey.example.com`:
   ```
   v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC...
   ```
   Configure your mail server to sign outgoing emails.
3. **DMARC:** Publish a policy record. Start with `p=none` to monitor, then move to `p=quarantine` or `p=reject`. Example:
   ```
   v=DMARC1; p=reject; rua=mailto:dmarc-reports@example.com; pct=100
   ```
4. **Monitor reports:** Use tools like `opendmarc` or third-party services to analyze aggregate reports (XML) sent to `rua` address.

**Common Tools:**
- `dig` to query DNS records: `dig TXT _dmarc.example.com`
- `nslookup` or `host` for SPF: `host -t TXT example.com`
- Online checkers: MXToolbox, DMARC Analyzer

### Real-World Vulnerabilities (CVEs)

- **CVE-2023-xxxx:** Some mail servers mishandle SPF `redirect` and cause bypass.
- **DMARC bypass via subdomains:** If DMARC `sp` policy is not set, subdomains may not be protected.
- **DKIM key compromise:** Weak RSA keys (512-bit) can be factored (CVE-2021-3449).

### Exam Relevance

SY0-701 tests your ability to identify which protocol addresses which threat. For example:
- SPF prevents spoofing of the envelope sender.
- DKIM ensures message integrity and authenticity.
- DMARC ties them together and provides policy enforcement.

Key acronyms: SPF, DKIM, DMARC, RFC 7208/6376/7489, TXT record, alignment, selector, Return-Path.

## Real-world context

**Scenario 1: Phishing Attack Using Spoofed CEO Email**
A security analyst at a mid-size company notices an email from the CEO requesting an urgent wire transfer. The email passes SPF and DKIM checks but the 'From' address is ceo@company.com, while the SPF check was based on a different domain (e.g., attacker.com). Without DMARC alignment, the email was delivered. The analyst checks the DMARC record and finds it is missing. The correct response is to implement DMARC with `p=reject` and ensure alignment. A common mistake is to only look at SPF/DKIM pass/fail and ignore the 'From' domain mismatch. Tools: Email header analysis in Outlook or Thunderbird, `dig` for DMARC record.

**Scenario 2: Third-Party Email Service Misconfiguration**
An e-commerce company uses a third-party email service for order confirmations. After implementing DMARC `p=reject`, customers stop receiving order emails. The analyst discovers that the third-party's sending IPs are not in the company's SPF record, and the emails are not DKIM-signed. The analyst adds the third-party's IPs to SPF and requests DKIM signing. The correct response is to update SPF and configure DKIM for the third-party. A common mistake is to change DMARC to `p=none` instead of fixing the underlying authentication. Tools: DMARC aggregate reports showing SPF failures from the third-party IPs.

**Scenario 3: Subdomain Spoofing**
A social media platform has DMARC `p=reject` on its main domain, but subdomains like `mail.example.com` are not protected. Attackers send spoofed emails from `sub.example.com` that pass SPF (because the subdomain's SPF record allows any IP) and DKIM (signed with attacker's key). The main domain's DMARC policy does not apply to subdomains unless `sp` is set. The correct response is to add `sp=reject` to the DMARC record and ensure subdomains have proper SPF/DKIM. A common mistake is assuming DMARC protects all subdomains automatically. Tools: DNS lookup for `_dmarc.example.com` shows no `sp` tag.

## Exam focus

**What SY0-701 Tests on This Objective:**
Objective 4.4 (Security Operations) includes email security controls like SPF, DKIM, and DMARC. You need to know:
- The purpose of each protocol: SPF authorizes sending IPs, DKIM provides digital signatures, DMARC enforces policy.
- How they work together: DMARC uses SPF and DKIM results and checks alignment.
- Common misconfigurations: using `~all` instead of `-all`, missing DKIM selector, DMARC `p=none`.
- The role of DNS TXT records.

**Most Common Wrong Answers and Why:**
1. **Selecting SPF to prevent email content tampering.** Wrong because SPF only checks IP authorization. DKIM ensures integrity.
2. **Thinking DMARC replaces SPF and DKIM.** Wrong because DMARC relies on them; it doesn't replace them.
3. **Confusing DKIM with S/MIME.** Both use digital signatures, but DKIM is for domain-level authentication, not user-level encryption.
4. **Believing SPF `-all` is optional.** Candidates think `~all` is acceptable, but the exam expects `-all` for strict security.

**Specific Terms and Values:**
- RFC numbers: 7208 (SPF), 6376 (DKIM), 7489 (DMARC).
- Record types: TXT.
- SPF mechanisms: `ip4`, `include`, `a`, `mx`, `all`.
- DKIM algorithms: rsa-sha256, rsa-sha1 (deprecated), ed25519.
- DMARC tags: `p`, `sp`, `rua`, `ruf`, `pct`, `adkim`, `aspf`.
- Lookup limit: 10 DNS lookups for SPF.

**Common Trick Questions:**
- A question may describe a scenario where an email passes SPF but still spoofs the 'From' domain. The answer is DMARC alignment.
- A question about email integrity points to DKIM, not SPF.
- A question about a domain owner wanting to monitor without blocking: DMARC `p=none`.

**Decision Rule for Eliminating Wrong Answers:**
On scenario questions, first identify the threat: spoofing (SPF), tampering (DKIM), or policy enforcement (DMARC). If the scenario mentions 'prevent unauthorized servers from sending email', choose SPF. If it mentions 'verify email hasn't been altered', choose DKIM. If it mentions 'what to do when authentication fails', choose DMARC. Eliminate options that don't match the primary function.

## Step by step

1. **Configure SPF Record** — Identify all legitimate IP addresses and mail servers that send email for your domain. Create a TXT record in your DNS zone with the format `v=spf1 ip4:192.0.2.0/24 include:_spf.google.com -all`. Use `ip4`/`ip6` for specific ranges, `include` to delegate to third-party services, and end with `-all` for hard fail. Test with `dig TXT example.com`. Common mistake: using `~all` (softfail) which allows spoofed emails to pass. After publishing, verify that legitimate emails still pass and spoofed ones are flagged.
2. **Generate DKIM Keys and Publish** — Generate a 2048-bit RSA key pair using OpenSSL: `openssl genrsa -out private.key 2048` and extract public key: `openssl rsa -in private.key -pubout -out public.key`. Create a DNS TXT record at `selector._domainkey.example.com` containing the public key in proper format: `v=DKIM1; k=rsa; p=<base64>`. Configure your mail server (e.g., Postfix, Exchange) to sign outgoing emails with the private key. Verify with `dig TXT selector._domainkey.example.com`. Common mistake: using a weak key (1024-bit or less) or forgetting to rotate keys periodically.
3. **Publish DMARC Policy** — Create a TXT record at `_dmarc.example.com` with policy: `v=DMARC1; p=none; rua=mailto:dmarc@example.com`. Start with `p=none` to monitor traffic without affecting delivery. Analyze aggregate reports (XML) to identify legitimate senders and spoofing attempts. After a few weeks, tighten policy to `p=quarantine` then `p=reject`. Set `pct=100` to apply to all emails. Ensure SPF and DKIM alignment is correct. Common mistake: publishing `p=reject` without first verifying that all legitimate emails pass authentication.
4. **Monitor and Analyze Reports** — Set up an email address to receive DMARC aggregate reports (rua). Use tools like `opendmarc` or online services (e.g., DMARC Analyzer) to parse the XML reports. Look for failures: SPF fails (IP not authorized), DKIM fails (signature invalid), alignment failures (domain mismatch). Identify legitimate senders that are failing and update SPF/DKIM accordingly. Monitor for spoofing attempts. Adjust DMARC policy gradually. Common mistake: ignoring reports or not parsing them regularly.
5. **Troubleshoot and Adjust** — If legitimate emails are being rejected or quarantined, check SPF include statements for missing IPs, DKIM selector correctness, and DMARC alignment. Use online tools like MXToolbox to test records. Verify that all third-party senders (e.g., marketing platforms) are included in SPF and have DKIM configured. If using subdomains, set DMARC `sp` policy. After adjustments, monitor reports for improvements. Common mistake: making changes without testing, causing email delivery failures.

## Comparisons

### SPF vs DKIM

**SPF:**
- Authorizes sending IP addresses
- Uses DNS TXT records with IP ranges
- Checks envelope sender (Return-Path)
- Prevents IP-based spoofing
- No encryption or signing

**DKIM:**
- Provides digital signature for email
- Uses DNS TXT records with public keys
- Signs email headers and body
- Prevents tampering and authenticates domain
- No IP authorization

## Common misconceptions

- **Misconception:** SPF verifies the 'From' header address. **Reality:** SPF checks the 'Envelope From' (Return-Path), not the visible 'From' header. Attackers can set a legitimate Return-Path and spoof the 'From' address.
- **Misconception:** DKIM encrypts the email body. **Reality:** DKIM signs the email for integrity and authentication, but does not encrypt it. The body and headers are readable.
- **Misconception:** DMARC alone prevents email spoofing. **Reality:** DMARC requires SPF and/or DKIM to be configured. Without them, DMARC has no authentication results to evaluate.
- **Misconception:** SPF '~all' (softfail) is as secure as '-all' (hardfail). **Reality:** Softfail instructs receivers to accept the email but mark it as suspicious. Many servers still deliver it. Hardfail rejects it outright.
- **Misconception:** DKIM selector is optional. **Reality:** The selector is mandatory because it tells the receiver which public key to retrieve from DNS. Without it, verification cannot occur.

## Key takeaways

- SPF uses DNS TXT records to list authorized sending IPs; always end with `-all` for hard fail.
- DKIM signs emails with a private key; public key is published via DNS selector record.
- DMARC uses SPF and DKIM results and checks alignment of the 'From' domain.
- DMARC policy options: `none`, `quarantine`, `reject`; start with `none` to monitor.
- SPF has a 10-DNS-lookup limit; exceeding it causes a permerror.
- DKIM selectors allow multiple keys; rotate keys periodically.
- DMARC aggregate reports (rua) provide XML feedback on authentication failures.

## FAQ

**What is the difference between SPF, DKIM, and DMARC?**

SPF (Sender Policy Framework) authorizes which IP addresses can send email for a domain. DKIM (DomainKeys Identified Mail) adds a digital signature to verify email integrity and authenticity. DMARC (Domain-based Message Authentication, Reporting, and Conformance) uses SPF and DKIM results to enforce a policy (none, quarantine, or reject) and provides reporting. The exam tests your ability to match each to its specific function.

**How does DMARC alignment work?**

DMARC alignment checks that the domain in the 'From' header matches the domain used in SPF (Return-Path) or DKIM (d= tag). For SPF alignment, the 'From' domain must match the Return-Path domain (or be a subdomain in relaxed mode). For DKIM alignment, the 'd=' domain must match the 'From' domain. Alignment ensures that the sender domain is consistent across authentication checks.

**What is a DMARC aggregate report?**

An aggregate report is an XML file sent to the email address specified in the DMARC `rua` tag. It contains data on how many emails passed or failed SPF, DKIM, and alignment, along with the source IPs. Domain owners use these reports to monitor authentication results and identify misconfigurations or spoofing attempts.

**What does SPF '~all' vs '-all' mean?**

`~all` (softfail) indicates that emails from unauthorized IPs should be accepted but marked as suspicious (e.g., spam). `-all` (hardfail) tells receivers to reject such emails outright. For strong security, use `-all`. The exam expects you to know that `-all` is stricter.

**Can DMARC work without SPF or DKIM?**

No. DMARC requires at least one of SPF or DKIM to be configured. If both are absent, DMARC has no authentication result to evaluate, and the policy cannot be applied. The exam may present a scenario where DMARC is implemented but SPF/DKIM are missing, leading to no protection.

**What is a DKIM selector?**

A DKIM selector is a string (e.g., 'google' or 's1') used to locate the public key in DNS. The full DNS record is `selector._domainkey.example.com`. Selectors allow multiple keys for different mail streams or key rotation. The exam may ask about the format of the DKIM DNS record.

**How do I test my SPF, DKIM, and DMARC records?**

Use `dig TXT example.com` for SPF, `dig TXT selector._domainkey.example.com` for DKIM, and `dig TXT _dmarc.example.com` for DMARC. Online tools like MXToolbox can also test and provide pass/fail results. The exam may ask about command-line tools for DNS lookups.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/security-plus/email-security
