> "The Internet was built on trust... [it] was not designed with security in mind."
Prerequisites
- 6
- 7
Learning Objectives
- Explain how DNS resolution works and how attackers abuse it through poisoning, tunneling, and exfiltration — and harden it with DNSSEC, sinkholes, and monitoring.
- Distinguish phishing, spear-phishing, and business email compromise, and trace how each defeats naive email trust.
- Deploy SPF, DKIM, and DMARC step by step to authenticate a domain's mail and stop spoofing, and read a DMARC aggregate report.
- Harden web delivery with HTTP security headers, HSTS, and secure cookie attributes.
- Recognize DNS and email telemetry as a primary detection goldmine and write basic detections over it.
In This Chapter
- Overview
- Learning Paths
- 9.1 DNS: the phone book attackers love
- 9.2 DNSSEC, sinkholes, and DNS monitoring
- 9.3 Email threats: phishing, BEC, and spoofing
- 9.4 SPF, DKIM, and DMARC, step by step
- 9.5 Web protocol hardening: headers, HSTS, and cookies
- 9.6 Catching DNS and email abuse in telemetry
- Project Checkpoint
- Summary
- Spaced Review
- What's Next
Chapter 9: DNS, Email, and Web Security: Securing the Protocols Everyone Uses Every Day
"The Internet was built on trust... [it] was not designed with security in mind." — Vinton G. Cerf
Overview
Return to the morning the phishing email nearly took down Meridian Regional Bank — the cold open of Chapter 1. We watched it from the inside: a message that looked like a DocuSign request, a pixel-perfect fake portal, a loan officer who typed her password, and a hardware security key that refused to be fooled. We told that story to make a point about layered defense. Now we are going to take it apart at the protocol level, because almost every move in that attack — and almost every move in the next one — happened inside three protocols that every organization on Earth runs and almost nobody hardens: the Domain Name System, email, and the web.
Consider what the attacker actually had to do. They registered a look-alike domain (DNS). They sent a message that claimed to come from a title company (email — and the claim was a lie no protocol checked). They pointed the link at a server they controlled and dressed it in a stolen login page served over HTTPS (the web). At every step they exploited the same design flaw: these protocols were built in an era of mutual trust, when the question "is this sender really who they say they are?" had no technical answer because nobody had thought to ask it. DNS will cheerfully tell you the address of meridianbank.example and the address of merid1anbank.example with equal confidence. Classic email lets anyone write any name in the From: line, the way you can write any return address on an envelope. A web browser, left to its own defaults, will happily downgrade to unencrypted HTTP if an attacker nudges it.
This chapter is about closing those gaps. The good news — and it is genuinely good news — is that over the last fifteen years the industry built authentication and hardening layers that bolt onto these legacy protocols: DNSSEC for DNS integrity, SPF, DKIM, and DMARC for email authenticity, and a suite of HTTP security headers including HSTS for the web. None of them is exotic. All of them are deployable this quarter. Most organizations have deployed them halfway, badly, which is its own kind of danger. By the end of this chapter you will know how each one works, how an attacker tries to slip past it, how to deploy it correctly for Meridian, and — because you are a defender, not just an administrator — how to turn DNS and email logs into one of the richest detection sources you have.
In this chapter, you will learn to:
- Describe DNS resolution end to end and recognize its abuse — cache poisoning, tunneling, exfiltration, and the algorithmically generated domains that malware uses to find its way home.
- Harden DNS with DNSSEC, sinkholing, and resolver logging, and explain what each does and does not protect.
- Tell phishing, spear-phishing, and business email compromise (BEC) apart, and explain why BEC steals more money than ransomware while carrying no malware at all.
- Deploy SPF, DKIM, and DMARC in the correct order, write each record by hand, and read a DMARC aggregate report to find both attackers and your own broken mail streams.
- Harden web delivery with HSTS, a content-security baseline, and secure cookie flags.
- Treat DNS and email as detection goldmines, and write the queries that catch abuse in telemetry.
Learning Paths
This chapter sits at the center of three roles. Email and DNS are where attackers get in and where defenders get their earliest, cheapest warning.
🛡️ SOC Analyst: This is one of your home chapters. Live in §9.3 (recognizing phishing and BEC), §9.6 (hunting abuse in DNS and email telemetry), and the DMARC-report reading in §9.4. Most intrusions you investigate will begin here. 🏗️ Security Engineer: §9.2 (DNSSEC, sinkholes), §9.4 (deploying SPF/DKIM/DMARC the right way), and §9.5 (web hardening) are deployment work you will own. The Project Checkpoint builds the records you will actually publish. 📋 GRC: Skim §9.4 — DMARC and email authentication increasingly appear in regulatory and customer-trust requirements, and "we publish DMARC at enforcement" is a board-legible control. 📜 Certification Prep: Every reserved term here is exam-relevant. SPF/DKIM/DMARC, DNSSEC, DNS poisoning, HSTS, and BEC appear on Security+ and CISSP; the
key-takeaways.mdfile maps them.
This chapter builds on the network fundamentals of Chapter 6 (ports, protocols, where attacks live) and the perimeter controls of Chapter 7 (firewalls, IDS/IPS, the secure-gateway idea). It sets up Chapter 13 (web application security, where we go deep on the attacks the headers in §9.5 mitigate) and Chapter 30 (security awareness, which turns the human side of phishing defense into a program).
9.1 DNS: the phone book attackers love
Start with a question you have answered ten thousand times without noticing. You type meridianbank.example into a browser. Your computer needs to turn that human-friendly name into the numeric address a packet can be routed to — something like 203.0.113.10. The system that performs this translation is the Domain Name System (DNS): a globally distributed, hierarchical database that maps domain names to IP addresses (and to other records), and the single most load-bearing piece of infrastructure on the internet that most people never think about. Nearly every connection your organization makes begins with a DNS lookup. That ubiquity is exactly why attackers love it.
Here is the resolution, walked end to end, because you cannot defend a process you cannot trace. When your machine needs the address for www.meridianbank.example, it asks a resolver (usually run by your organization or your ISP, or a public one like 8.8.8.8 or 1.1.1.1). The resolver, if it does not already have the answer cached, walks the hierarchy from the top:
Your laptop Recursive resolver Authoritative servers
─────────── ────────────────── ─────────────────────
│ "A record for Root servers (.)
│ www.meridianbank.example?" │
│ ─────────────────────────► ┌──────────┐ "ask .example" │
│ │ resolver │ ───────────────► (1)
│ │ cache? │ ◄───────────────
│ │ miss │ "ask meridianbank.example NS"
│ │ │ ───────────────► .example TLD (2)
│ │ │ ◄───────────────
│ │ │ "A = 203.0.113.10"
│ │ │ ───────────────► authoritative (3)
│ "203.0.113.10" │ cache │ ◄───────────────
│ ◄───────────────────────── └──────────┘ (answer cached for its TTL)
▼
connect to 203.0.113.10
Figure 9.1 — Recursive DNS resolution. The resolver walks from the root (.) to the top-level domain (.example) to the authoritative server for the zone, then caches the answer for its time-to-live (TTL). Every arrow is a place an attacker might lie.
Several DNS facts become security facts the moment you see this diagram. First, the protocol is, by default, unauthenticated and runs over UDP (port 53) — a connectionless transport with no handshake. Classic DNS has no built-in way for the resolver to verify that the answer it received actually came from the legitimate authoritative server and was not forged or modified in flight. Second, answers are cached for a duration set by the record's TTL (time to live). Caching makes the internet fast, but it also means that a single poisoned answer can be served to many victims until the TTL expires. Third, the records themselves come in types you will see constantly: an A record maps a name to an IPv4 address, AAAA to IPv6, MX designates a domain's mail servers, TXT holds arbitrary text (this is where SPF, DKIM, and DMARC live — remember that), CNAME is an alias, and NS delegates a zone to its authoritative servers.
How attackers abuse DNS
DNS abuse comes in several distinct shapes, and conflating them is a common beginner error. Let us separate them.
DNS spoofing and cache poisoning. Because classic DNS answers are unauthenticated, an attacker who can inject a forged response — by being on the network path, or by guessing the transaction ID and source port of an in-flight query before the real answer arrives — can convince a resolver to accept a lie. DNS poisoning (cache poisoning) is the act of inserting a fraudulent record into a resolver's cache so that subsequent lookups return the attacker's chosen address. Poison the cache for www.meridianbank.example and point it at an attacker-controlled server, and every user of that resolver who visits the bank is silently redirected — to a phishing page, to a malware drop, to a machine-in-the-middle. The classic large-scale version was the Kaminsky technique disclosed in 2008, which made poisoning dramatically more practical and triggered an industry-wide scramble to add source-port randomization and, eventually, to deploy DNSSEC (§9.2).
Typosquatting and look-alike domains. This is the lowest-tech DNS attack and the one that nearly hit Meridian. The attacker does not poison anything — they simply register a domain that resembles the target: merid1anbank.example (digit one for the letter L), meridian-bank.example, meridianbank.example.co, or a homoglyph using look-alike Unicode characters. Then they host a convincing copy of the real site and lure victims with a link. DNS faithfully resolves the malicious domain because, as far as DNS is concerned, it is a perfectly legitimate name that someone paid to register.
DNS tunneling and exfiltration. This one surprises people. DNS tunneling is the technique of encoding non-DNS data inside DNS queries and responses to smuggle traffic through a network that allows DNS but blocks other outbound protocols. Because almost every firewall permits outbound DNS (you have to — nothing works without it), DNS becomes a covert channel. An attacker encodes data into the subdomain portion of a query: a lookup for aGVsbG8gd29ybGQ.exfil.example carries the base64-encoded string "hello world" in the label, and the attacker's authoritative server for exfil.example decodes it. Run in reverse, the server's responses carry instructions back to the malware — a command-and-control (C2) channel hiding in plain sight. DNS exfiltration is the data-theft application of the same trick: an attacker who has compromised a host but cannot move large files out over blocked ports dribbles them out, one DNS query at a time, in the subdomain labels. It is slow, but a determined adversary will happily exfiltrate a customer database at a few hundred bytes per query if every other door is shut.
Domain generation algorithms (DGAs). Modern malware rarely hard-codes the address of its command server, because a hard-coded domain is a single point the defender can block. Instead it runs a domain generation algorithm: a function, seeded by the date or some shared secret, that produces a stream of pseudo-random domain names like kq3v9xz2pl.example or xkjfhqwebz.example. The malware tries to resolve them in sequence; the attacker registers just one of the day's thousands of candidates and waits for the call. To a human, DGA domains are obvious — they look like a cat walked across the keyboard. To a firewall blocklist, they are a moving target. We will build a small detector for exactly this pattern in the Project Checkpoint.
🛡️ Defender's Lens: Notice that every one of these attacks leaves a fingerprint in DNS logs, which is precisely why DNS telemetry is a detection goldmine (§9.6). Tunneling produces abnormally long, high-entropy subdomain labels and a high volume of queries to a single domain. DGAs produce a flood of failed lookups (NXDOMAIN responses) as the malware cycles through unregistered candidates. Poisoning shows up as answers that disagree with the authoritative source. The attacker's cleverness on the wire becomes your evidence in the logs — if, and only if, you are logging DNS. Most organizations are not, which is the real vulnerability.
⚠️ Common Pitfall: Treating DNS as plumbing that "just works" and therefore not logging or monitoring it. DNS is involved in nearly every attack — initial redirect, malware callback, exfiltration — and an organization with no DNS visibility is blind to all three. The fix is not expensive: enable query logging on your resolvers and ship it to the SIEM (Chapter 21). You will be astonished what you see.
🔄 Check Your Understanding: 1. Why does the lack of authentication in classic DNS make cache poisoning possible, and how does the caching of answers make a single successful poisoning more damaging? 2. Distinguish DNS tunneling from typosquatting. Which one requires the attacker to register a look-alike domain, and which one abuses the fact that firewalls permit outbound DNS?
Answers
- Classic DNS answers carry no cryptographic proof of origin, so a forged response that arrives before the real one (and matches the query's transaction ID and port) is accepted as genuine; because resolvers cache answers for the TTL, that one forged record is then served to every client that queries during the TTL, multiplying the harm. 2. Typosquatting requires registering a look-alike domain and relies on a human clicking it; DNS tunneling needs no look-alike — it abuses the universally permitted outbound DNS channel to smuggle data inside query labels.
9.2 DNSSEC, sinkholes, and DNS monitoring
If the core problem with classic DNS is that answers are unauthenticated, the structural fix is to authenticate them — and that is exactly what DNSSEC (DNS Security Extensions) does. DNSSEC adds cryptographic signatures to DNS records so that a resolver can verify an answer genuinely came from the zone's owner and was not tampered with in transit. It does not encrypt anything (DNS data stays public) and it does not stop typosquatting (a malicious domain is still legitimately registered). What it does, and the only thing it does, is provide integrity and origin authentication — which is precisely the gap that makes cache poisoning possible.
The mechanism is a chain of trust that parallels the resolution hierarchy itself. Each zone signs its records with a private key, publishing the corresponding public key in a DNSKEY record and the signatures in RRSIG records. The parent zone vouches for the child's key by publishing a DS (Delegation Signer) record — a hash of the child's key — in its signed zone. So .example signs a DS record for meridianbank.example's key, the root signs the DS for .example, and the root's key is the one trust anchor a resolver is configured to trust absolutely. A validating resolver walks this chain from the root down; if every signature checks out, the answer is authentic. If a poisoner injects a forged record, it cannot produce a valid signature (it does not have the zone's private key), so the validating resolver rejects it.
Root zone (.) signs the DS record for ─► .example
│ trust anchor │ signs the DS for ─►
│ (configured │
▼ in resolver) ▼
.example zone signs the DS record for ─► meridianbank.example
│ signs its own
▼ A/MX/TXT records
RRSIG over each record set
A resolver validates: root ► .example ► meridianbank.example.
Any link with a bad/absent signature ⇒ answer is rejected (SERVFAIL).
Figure 9.2 — The DNSSEC chain of trust. Each parent signs a hash of its child's key, anchoring all the way to the root. A forged record cannot be signed by the real zone key, so a validating resolver detects and rejects it.
⚠️ Common Pitfall: Believing DNSSEC encrypts DNS or hides your lookups. It does neither. DNSSEC is integrity, not confidentiality. If you want to keep the content of DNS queries private from network observers, that is a different technology — DNS over HTTPS (DoH) or DNS over TLS (DoT), which encrypt the query channel. DNSSEC and DoH/DoT solve different problems and are complementary: DNSSEC proves the answer is genuine; DoH/DoT hides which questions you asked. Confusing the two is one of the most common DNS misconceptions on certification exams and in real architecture meetings.
DNSSEC has real operational costs — key management, signing, and the unforgiving reality that a misconfigured or expired signature does not degrade gracefully; it breaks resolution outright with a SERVFAIL. Adoption is therefore uneven. But for a regulated organization like Meridian, signing your own zones (so that others can validate your records) and enabling validation on your resolvers (so you reject forged answers for the domains you visit) are both well-understood, achievable controls.
Sinkholing: turning the attacker's own DNS against them
DNSSEC stops forged answers. A DNS sinkhole does something almost opposite and equally useful: it deliberately returns a false answer — but for a good reason, and under your control. A DNS sinkhole is a DNS server (or a policy on your resolver) configured to return a controlled, non-routable or internal address for domains you have decided are malicious, so that any host trying to reach them is redirected to a safe destination instead of the attacker. Think of it as a blocklist enforced at the resolution layer.
The defensive power of this is considerable. Suppose threat intelligence (Chapter 22 builds this capability) tells you that evil-c2.example is a known command-and-control domain. You add it to your sinkhole, and now any infected host inside Meridian that tries to call home gets pointed at an internal logging server instead — which both prevents the callback and detects the infection, because the only machines querying that domain are compromised ones. A sinkhole is one of the rare controls that is simultaneously preventive and detective (a distinction from Chapter 3): it stops the bad connection and it lights up your dashboard with the identity of every infected host. Sinkholing is also how Response Policy Zones (RPZ) work — a standardized way to apply such policies on a resolver — and it is the mechanism behind "protective DNS" services.
📟 War Story: A constructed but representative incident. A mid-size firm subscribed to a threat-intelligence feed of malicious domains and pushed it into a DNS sinkhole on their internal resolvers. Three days later the sinkhole's logs showed a single workstation repeatedly querying a domain on the list — a known information-stealer's C2. No malware alert had fired; the endpoint agent had missed the infection entirely. But the malware still needed DNS to find its master, and the moment it asked, the sinkhole both blocked the call and named the patient. The lesson: even when prevention on the endpoint fails, the attacker's dependence on DNS gives the defender another shot. Make the adversary ask permission to resolve, and you have turned their own infrastructure into your tripwire.
DNS monitoring: the goldmine
The third pillar is simply watching. Because every attack phase touches DNS, resolver query logs are one of the highest-value, lowest-cost telemetry sources a SOC can collect. We treat detection in depth in §9.6, but the principle belongs here with the other DNS defenses: collect DNS query logs from your resolvers and analyze them. The signals are well known — unusually long or high-entropy subdomains (tunneling), bursts of NXDOMAIN responses (DGAs failing to resolve), queries to newly registered or low-reputation domains, and any host talking to a sinkholed domain. None of this works if the logs are not collected, which loops back to the pitfall in §9.1: the most common DNS vulnerability is not a missing cryptographic control, it is missing visibility.
🔗 Connection: A DNS sinkhole is conceptually a sibling of the firewall default-deny posture from Chapter 7 (§7.2): instead of allowing everything and blocking known-bad by IP at the network layer, you block known-bad by name at the resolution layer — earlier in the kill chain, before a packet is even sent. The two layers reinforce each other, which is defense in depth applied to a single connection attempt.
🔄 Check Your Understanding: 1. A colleague says, "We deployed DNSSEC, so our DNS lookups are now private and encrypted." Correct them precisely — what does DNSSEC actually provide, and what technology would they need for the property they described? 2. Explain how a DNS sinkhole can be both a preventive and a detective control in a single action.
Answers
- DNSSEC provides integrity and origin authentication — it lets a resolver verify an answer genuinely came from the zone owner and was not forged — but it does not encrypt anything; DNS data remains public. For confidentiality of the query channel they would need DNS over HTTPS (DoH) or DNS over TLS (DoT). 2. It is preventive because it redirects an infected host's connection away from the real C2 to a safe address, stopping the callback; it is detective because the only hosts that query a known-malicious sinkholed domain are compromised ones, so the query itself identifies the infected machine.
9.3 Email threats: phishing, BEC, and spoofing
Now to the protocol that delivers the majority of intrusions. Email's foundational protocol, the Simple Mail Transfer Protocol (SMTP), was designed in 1982 among a small community of mutually trusting research institutions. Its defining security property — the one that haunts us four decades later — is that the sender is whoever they say they are. SMTP lets the sending server assert any address in the From: header, with no verification at all. This is email spoofing: forging the sender address of an email so it appears to come from someone it did not. It is not a clever exploit; it is the default behavior of a protocol that never asked the question. Writing From: ceo@meridianbank.example on a message you send from your own server is as easy, and as truthful, as writing a celebrity's name as the return address on a postcard.
Spoofing is the enabling weakness. The attacks built on top of it form a spectrum:
Phishing is a social-engineering attack delivered (most often) by email, in which the attacker impersonates a trusted entity to trick the recipient into revealing credentials, transferring money, or running malware. (Social engineering as a category — manipulating people rather than machines — was defined in Chapter 2; here we focus on its email-borne form and, crucially, its defenses.) Ordinary phishing is a numbers game: send the same lure — a fake DocuSign request, a "your account is locked" warning, a bogus invoice — to thousands of recipients and profit from the small fraction who click. It is high-volume and low-customization.
Spear-phishing is targeted phishing: the attacker researches a specific individual or organization and crafts a message tailored to them — referencing a real project, a real colleague, a real vendor — to dramatically raise the success rate. The Meridian email that opened this book was a spear-phish in spirit: it was shaped to look like exactly the kind of title-company DocuSign request a loan officer receives daily. A generic "you have a fax" lure would have been deleted; a message that fit the target's actual workflow got a click.
Business email compromise (BEC) is the most financially devastating of the family and, tellingly, often involves no malware and no malicious link at all. BEC is a fraud in which an attacker impersonates a trusted party — an executive, a vendor, a lawyer — usually over email, to induce an employee to transfer funds or sensitive data to the attacker. The attacker might spoof the CFO's address (or, worse, actually compromise the CFO's real mailbox and send from it), then email the accounts-payable clerk: "We're closing the Henderson acquisition today, it's confidential, wire $480,000 to these new instructions before 4 p.m." There is nothing for an antivirus to catch. There is no attachment, no exploit, no payload — only a lie, told with authority and urgency, exploiting a human and a business process. BEC's defining feature is that it weaponizes trust and hierarchy, not technology, which is exactly why purely technical defenses are necessary but not sufficient.
📟 War Story: Constructed, but it mirrors a pattern reported across the industry. A real-estate title company's email account is compromised through a months-earlier phishing attack. The attacker reads quietly for weeks, learning the cadence of closings, the names of the parties, the tone of the staff. Then, on the morning of a $310,000 home-purchase closing, the attacker — sending from the title company's genuine account, so every authentication check passes — emails the buyer: "Last-minute change, please wire the closing funds to the updated account below." The buyer, who has been corresponding with this same real address for weeks, complies. The money is gone in hours. This is BEC at its most effective: no spoofing to detect, because the mailbox is real; the only defense is a process (verify wire changes through a second, out-of-band channel) and a culture that treats "urgent change to payment details" as a red flag regardless of who appears to be asking. We return to building that culture in Chapter 30.
The attacker's email toolkit, then, ranges from the purely technical (spoof the From: line) to the purely human (compromise a real account and abuse trust). A complete defense must therefore work on both fronts: technical authentication to kill spoofing — SPF, DKIM, and DMARC, which are the whole of §9.4 — and a secure email gateway plus human program to catch what authentication cannot.
The secure email gateway
A secure email gateway (SEG) is a security control — appliance or cloud service — that filters inbound and outbound email for spam, malware, malicious URLs, and policy violations before messages reach users' inboxes. It is the email equivalent of the firewall: a chokepoint where you inspect traffic. A modern SEG does several jobs at once: it checks sender reputation and the SPF/DKIM/DMARC results we are about to build; it detonates attachments in a sandbox to catch malware; it rewrites URLs so that links are re-checked at click time, not just at delivery (because attackers weaponize a link after it passes the initial scan); it strips or flags dangerous attachment types; and increasingly it applies machine-learning models to spot the linguistic fingerprints of BEC ("urgent," "wire," "confidential," "gift cards"). The SEG is a powerful, necessary layer — and, like every layer in this book, it is designed on the assumption that the layer behind it will sometimes fail. Some phishing always gets through, which is why authentication, user reporting, and detection (§9.6) all matter too.
🛡️ Defender's Lens: The single most valuable email control most organizations under-invest in is not a filter at all — it is a one-click report-phish button wired into the mail client, feeding the SOC. The Meridian near-miss was caught in part because one employee reported the suspicious message, generating an alert. Every reported phish is free threat intelligence: it tells you what lures are hitting your people right now, lets you search who else received the same message, and lets you pull it from other inboxes before they click. Trained, alert humans catch what automation misses — Theme 3 of this book, made operational. Encourage reporting relentlessly; never punish a false report.
🔄 Check Your Understanding: 1. Why is business email compromise often invisible to antivirus and malicious-URL filters, and what kind of control — technical or procedural — is the primary defense against the variant where the attacker sends from a genuinely compromised mailbox? 2. What does it mean that "the sender is whoever they say they are" in SMTP, and which single property of the protocol makes spoofing trivial?
Answers
- BEC frequently contains no attachment, no link, and no exploit — only a fraudulent request in plain text — so there is nothing for malware or URL scanners to detect; when the attacker sends from a real compromised mailbox, even sender authentication passes, so the primary defense is procedural: out-of-band verification of payment/data changes and a culture that flags urgency around money. 2. SMTP performs no verification of the asserted sender address, so a sending server can put any address in the
From:header; that lack of sender authentication is what makes spoofing trivial.
9.4 SPF, DKIM, and DMARC, step by step
Here is the heart of the chapter and the heart of email defense. Three standards, layered, close the spoofing gap that SMTP left open. They are frequently deployed wrong — half-configured, in the permissive mode that does nothing, or with the records subtly broken — so we will build each one deliberately, by hand, and then show how they combine. All three live in DNS TXT records, which is why we spent §9.1 making sure you knew where TXT records sit.
SPF — who is allowed to send
SPF (Sender Policy Framework) is an email-authentication standard that lets a domain owner publish, in DNS, the list of IP addresses and servers authorized to send mail on the domain's behalf; a receiving server checks whether the message arrived from a listed source. It answers one question: did this mail come from a server the domain says is allowed to send for it? You publish a single TXT record at your domain. Here is Meridian's:
meridianbank.example. IN TXT "v=spf1 ip4:203.0.113.10 ip4:203.0.113.11 include:_spf.cloud-mail.example -all"
Read it left to right. v=spf1 declares the SPF version. ip4:203.0.113.10 and ip4:203.0.113.11 authorize Meridian's two on-prem mail servers. include:_spf.cloud-mail.example delegates to a cloud provider's own SPF record (so that mail Meridian sends through, say, a marketing platform also passes) — include is how you authorize a third party without listing their ever-changing IPs yourself. The final mechanism is the most important and the most often botched: -all means "everything not listed above should be treated as a hard fail — reject it." The alternatives are ~all (soft fail: mark as suspicious but accept) and the dangerous ?all (neutral: do nothing, which makes the record decorative). A receiver evaluating a message that claims to be from Meridian but arrives from some random server will see it match none of the authorized sources and hit -all: SPF fails.
SPF has two well-known limitations you must understand to deploy it correctly. First, it authenticates the envelope sender (the MAIL FROM address used during SMTP delivery, also called the Return-Path), not the From: header the user actually sees. An attacker can pass SPF for a domain they control while still showing a forged From: to the human — which is exactly why SPF alone does not stop spoofing and why DMARC (below) exists to tie authentication back to the visible From:. Second, SPF breaks when mail is forwarded: if a message is relayed through an intermediate server (a mailing list, an auto-forward), it now arrives from the forwarder's IP, which is not in the original domain's SPF record, so SPF fails for legitimate mail. DKIM survives forwarding; SPF does not. This is not a reason to skip SPF — it is a reason to deploy all three.
DKIM — was it tampered with, and does the domain vouch for it
DKIM (DomainKeys Identified Mail) is an email-authentication standard in which the sending server attaches a cryptographic signature to each message, computed over selected headers and the body using a private key; the receiver verifies the signature using a public key published in the sender's DNS. Where SPF checks where mail came from, DKIM checks that the message genuinely originated from the domain and was not altered in transit. The sending server adds a DKIM-Signature header; the public key lives in a TXT record at a selector subdomain so a domain can rotate keys and run several:
selector1._domainkey.meridianbank.example. IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNAD...EXAMPLE...AQAB"
The receiver reads the DKIM-Signature header on an incoming message, sees it references selector selector1 and domain meridianbank.example, fetches the public key from selector1._domainkey.meridianbank.example, and verifies the signature. If it validates, two things are proven: the message was signed by something holding Meridian's private key, and the signed portions (headers and body) were not modified after signing. Because the signature travels with the message, DKIM survives forwarding where SPF does not — a forwarded message keeps its valid signature. DKIM's limitation is the mirror of SPF's: on its own, a passing DKIM signature only proves some domain signed the message, not that the signing domain matches the From: the user sees. Again: DMARC is the piece that ties it together.
DMARC — the policy that makes the other two matter
This is the keystone. DMARC (Domain-based Message Authentication, Reporting, and Conformance) is an email-authentication policy and reporting standard that builds on SPF and DKIM: it tells receivers what to do with mail that fails authentication and whose authenticated identity does not align with the visible From: domain, and it asks receivers to send the domain owner reports about messages claiming to be from their domain. DMARC adds three things the other two lack: alignment, a policy, and reporting.
Alignment is the critical concept. DMARC passes only if SPF or DKIM passes and the domain it authenticated aligns with the domain in the From: header the user actually sees. This is what finally defeats the spoofing trick where an attacker passes SPF for attacker.example while displaying From: ceo@meridianbank.example. Under DMARC, that mismatch — authenticated domain ≠ visible From: domain — fails alignment, and the receiver applies Meridian's published policy. Here is Meridian's DMARC record, published at the special _dmarc subdomain:
_dmarc.meridianbank.example. IN TXT "v=DMARC1; p=reject; rua=mailto:dmarc-reports@meridianbank.example; pct=100; adkim=s; aspf=s"
Decode it. v=DMARC1 is the version. p=reject is the policy: messages that fail DMARC for meridianbank.example should be rejected outright. The three policy values form a deployment ladder: p=none (monitor only — take no action, just send me reports), p=quarantine (treat failing mail as suspicious — send to spam), and p=reject (refuse it). rua=mailto:... is where aggregate reports are sent — daily XML summaries from receivers worldwide of how much mail claimed to be from your domain and whether it passed. pct=100 applies the policy to 100% of failing mail (you can ramp up gradually). adkim=s and aspf=s require strict alignment (the domains must match exactly, not just share an organizational parent); r (relaxed) is the more forgiving default.
Deploy them in the right order
The order matters, and getting it wrong is how organizations break their own legitimate mail. The correct rollout:
STEP 1 Publish SPF (-all) and DKIM (sign all outbound).
▼ ensure your real mail streams pass both.
STEP 2 Publish DMARC at p=none with rua= reporting.
▼ collect aggregate reports for weeks. LISTEN, don't enforce.
STEP 3 Read the reports. Find every legitimate sender that fails
(forgotten marketing tools, the helpdesk app, a branch server).
▼ fix each one (add to SPF, enable DKIM for it).
STEP 4 Move to p=quarantine, pct ramping 25 -> 50 -> 100. Watch reports.
▼
STEP 5 Move to p=reject. Spoofing of your domain now bounces worldwide.
Figure 9.3 — The DMARC deployment ladder. The p=none monitoring phase is not optional throat-clearing — it is how you discover your own broken mail streams before enforcement starts rejecting them. Skipping straight to p=reject is the classic way to take down your own newsletters and helpdesk notifications.
⚠️ Common Pitfall: Publishing DMARC at
p=noneand declaring victory.p=nonedoes nothing to stop spoofing — it only collects reports. An attacker can still spoof your domain freely; you are merely watching them do it. A vast number of organizations sit permanently atp=none, mistaking monitoring for protection. Monitoring is step two of five. The control only takes effect atquarantineorreject. Conversely, the opposite mistake — jumping top=rejectwithout the listening phase — silently destroys legitimate mail you forgot you send. The discipline is: enforce, but only after you have listened long enough to know what enforcement will break.
Reading a DMARC aggregate report
The reports (rua) are where this stops being configuration and becomes detection. Receivers send daily XML; tooling renders it readably. A simplified, illustrative view of one day for Meridian:
DMARC aggregate report — meridianbank.example — 2024-05-14 — receiver: a large mailbox provider
source_ip count SPF DKIM DMARC disposition note
203.0.113.10 842 pass pass PASS delivered our primary mail server (good)
203.0.113.11 310 pass pass PASS delivered our secondary mail server (good)
198.51.100.50 127 pass pass PASS delivered cloud-mail.example (our marketing — good)
192.0.2.77 54 fail fail FAIL rejected UNKNOWN — spoofing attempt, correctly blocked
198.51.100.99 18 fail pass PASS delivered our helpdesk app — DKIM saves it; ADD TO SPF
Two findings leap off this page, and learning to see both is the skill. The row for 192.0.2.77 is an attacker: 54 messages claiming to be from Meridian, failing both SPF and DKIM, correctly rejected because Meridian is at p=reject. That is the control working — and the report proves it worked. But the row for 198.51.100.99 is a self-inflicted finding: Meridian's own helpdesk application sends mail that fails SPF (the app's IP was never added to the SPF record) and is saved only because DKIM happens to pass. That is a fragile, half-broken legitimate stream — exactly the kind of thing the p=none listening phase exists to surface. The defender's job reading this report is to chase the attacker and fix their own house. A DMARC report is simultaneously an intrusion-detection feed and a mail-hygiene audit.
Back to Meridian's near-miss: what SPF/DKIM/DMARC would have done
Now we can answer the question this whole section was built for. Recall the Chapter 1 phishing email: it impersonated a title company, and the link went to a look-alike portal. Where do SPF/DKIM/DMARC help, and where do they not?
The honest answer — and honesty is the point — is it depends on whose domain was being abused. If the attacker had spoofed From: someone@meridianbank.example (impersonating the bank to its own staff or customers), then Meridian's p=reject DMARC record would have caused receiving servers, including Meridian's own, to reject the spoofed message outright, and the loan officer would never have seen it. That is the clean win, and it is why every organization should publish DMARC at enforcement: it stops attackers from impersonating you. But the Chapter 1 attacker impersonated a third party (a title company) — and Meridian cannot publish DNS records for a domain it does not own. Here the defenses are different and complementary: Meridian's inbound DMARC verification would check whether the message actually aligned with the title company's real domain (if that company published DMARC, an exact-domain spoof would fail and be quarantined); the secure email gateway would weigh the freshly registered look-alike domain's poor reputation and rewrite the URL for click-time inspection; and the human report plus the phishing-resistant authentication (Chapter 16) catch what slips through. The composite lesson is the book's spine: SPF/DKIM/DMARC are a powerful, mandatory layer that eliminates a whole class of attack (spoofing your own domain) and raises the cost of others — but they are one layer in a defense in depth, not a silver bullet. Deploy them at enforcement, and deploy everything behind them too.
🔗 Connection: The reporting half of DMARC feeds directly into the security-awareness program of Chapter 30. The aggregate reports tell you which look-alike domains and lures are targeting your people, which sharpens the phishing-simulation and training program — and the human reporting culture from §9.3 closes the loop. Email authentication (machine) and human awareness (people) are two halves of one defense.
🔄 Check Your Understanding: 1. Explain DMARC alignment in one sentence, and use it to explain why SPF and DKIM alone — without DMARC — fail to stop an attacker who displays
From: ceo@meridianbank.example. 2. Why must you spend weeks atp=nonebefore moving top=reject? What specific failure does skipping that phase cause?
Answers
- Alignment requires that the domain authenticated by SPF or DKIM match the domain in the visible
From:header; without DMARC, an attacker can pass SPF/DKIM for a domain they control while still displayingFrom: ceo@meridianbank.example, because nothing forces the authenticated domain to match the one the user sees — DMARC's alignment check is what closes that gap. 2. Thep=nonephase collects aggregate reports that reveal every legitimate mail stream (marketing tools, helpdesk apps, branch servers) that currently fails authentication; skipping it and going straight top=rejectcauses receivers to reject that legitimate mail, taking down your own newsletters and notifications.
9.5 Web protocol hardening: headers, HSTS, and cookies
The third protocol the Meridian attacker abused was the web itself — they served a stolen login page over HTTPS to harvest credentials. We cannot stop an attacker from building a malicious site on infrastructure they control. What we can do is harden the delivery of our own web applications so that the browser becomes an ally in defense, refusing to do dangerous things even when an attacker tries to trick it. The instruments are HTTP security headers — directives a web server sends in its responses that instruct the browser to enable protective behaviors — and a small set of cookie attributes. They are nearly free to deploy and they shut down whole categories of attack.
🔗 Connection: This section hardens the transport and browser layer; the application attacks these headers defend against — cross-site scripting, clickjacking, injection — are the subject of Chapter 13 (web application security), where we go deep on Content-Security-Policy and the same-origin model. Here we establish the baseline a defender configures on every site; there we dissect the attacks in full.
HSTS — never downgrade to plaintext
We begin with the one this chapter owns and that Chapter 5 deferred to us. HSTS (HTTP Strict Transport Security) is a web security policy, delivered via the Strict-Transport-Security response header, that instructs a browser to interact with a site only over HTTPS for a specified duration and to refuse any attempt to connect over plain HTTP — closing the window in which an attacker could force or intercept an unencrypted connection. The problem it solves is the protocol downgrade. Even when your site supports HTTPS, a user who types meridianbank.example (without https://) makes a first request over plain HTTP, which an on-path attacker can intercept and either read or redirect — the "SSL stripping" attack, where the attacker keeps an HTTPS connection to the server but feeds the victim plain HTTP, silently removing the encryption. HSTS slams that window shut. Meridian's header:
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
max-age=63072000 (two years, in seconds) tells the browser to remember, for that long, that this site is HTTPS-only — so even if the user later types http://, the browser silently upgrades to HTTPS before sending anything. includeSubDomains extends the policy to every subdomain (so online.meridianbank.example is covered too). preload opts the domain into a list, baked into major browsers, of sites that are HTTPS-only from the very first visit — eliminating even the initial bootstrap window, at the cost that adding and removing from the preload list is slow and deliberate. HSTS builds directly on the TLS foundation from Chapter 5 (TLS is what provides the encryption; HSTS is the policy that says always use it).
The security-header baseline
HSTS is the headline, but a defender configures a small standard set on every application. Here is Meridian's baseline, with each header's job:
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Content-Security-Policy(CSP) is the most powerful and the most intricate: it tells the browser which sources of scripts, styles, images, and frames are permitted, so that even if an attacker injects a<script>tag (a cross-site scripting attack — Chapter 13), the browser refuses to execute code from an unapproved source.default-src 'self'means "by default, only load resources from this same origin";object-src 'none'blocks plugins;frame-ancestors 'none'forbids the page from being framed (an anti-clickjacking measure, overlapping withX-Frame-Options). CSP is the single highest-value header for a web application, and also the easiest to misconfigure into uselessness (a policy with'unsafe-inline'and a wildcard source defeats its own purpose).X-Content-Type-Options: nosniffstops the browser from "MIME-sniffing" a response into a different content type than declared — a trick attackers use to make the browser execute a file the server intended as harmless data.X-Frame-Options: DENYforbids other sites from embedding your page in a frame, preventing clickjacking (overlaying an invisible frame of your site over a decoy so the victim's clicks land on your app). It is the older companion to CSP'sframe-ancestors.Referrer-Policycontrols how much of the originating URL is sent when a user clicks away, preventing sensitive paths or tokens in URLs from leaking to third parties.
Secure cookies
Finally, the cookies that carry session identity — the thing an attacker most wants to steal, because a stolen session cookie is a logged-in session, no password required. A defender sets three attributes on every sensitive cookie:
Set-Cookie: session=<id>; Secure; HttpOnly; SameSite=Strict
Secure ensures the cookie is only ever transmitted over HTTPS, never plain HTTP (so it cannot be sniffed on a downgraded connection — note how this reinforces HSTS). HttpOnly makes the cookie inaccessible to JavaScript, so that a cross-site scripting flaw cannot read and steal the session token. SameSite=Strict (or Lax) prevents the browser from sending the cookie on cross-site requests, which blunts cross-site request forgery (CSRF) — an attack that tricks a logged-in user's browser into making an unwanted request (covered fully in Chapter 13). Three attributes, three different attacks defused.
🛡️ Defender's Lens: These headers and flags are not just preventive — their absence is detectable and their presence is auditable. A defender (or an attacker doing reconnaissance) can request any page and read its headers in seconds; security scanners flag missing HSTS, weak CSP, or cookies lacking
HttpOnlyas routine findings. When you harden Meridian's online-banking portal, set the baseline above, then verify it from the outside — the gap between "we configured it" and "it is actually being sent on every response, including error pages" is where real exposures hide.🔄 Check Your Understanding: 1. What specific attack does HSTS prevent, and why is the
preloaddirective needed to close a gap thatmax-agealone leaves open? 2. A session cookie is set withSecureandSameSite=Strictbut notHttpOnly. Which class of attack can still steal it, and which header from the baseline would have reduced the chance of that attack succeeding in the first place?
Answers
- HSTS prevents protocol-downgrade / SSL-stripping attacks, where an on-path attacker forces or intercepts an unencrypted HTTP connection before HTTPS is established;
max-ageonly takes effect after a browser's first successful HTTPS visit, leaving the very first request vulnerable, sopreloadbakes the HTTPS-only rule into the browser ahead of time, closing even that initial bootstrap window. 2. WithoutHttpOnly, a cross-site scripting (XSS) flaw can read the cookie from JavaScript and exfiltrate the session token; a properly configuredContent-Security-Policywould reduce the chance the injected script runs at all.
9.6 Catching DNS and email abuse in telemetry
We have hardened all three protocols. Now we put on the SOC analyst's hat, because prevention will fail — Theme 4 — and the consolation, and the opportunity, is that DNS and email are two of the richest detection sources a defender has. Nearly every intrusion touches them, and each abuse leaves a recognizable signature. This section is the bridge to the security-operations work of Part V (this telemetry feeds the SIEM of Chapter 21); here we name the signals and show what the detections look like.
DNS detections. From §9.1–9.2, the high-value DNS signals are:
- Tunneling / exfiltration: abnormally long subdomain labels and high character entropy (random-looking strings), plus a high volume of queries to a single parent domain. A normal lookup is
www.bank.example; a tunnel looks likef8a3k2j9.d7m4q1.exfil.example, repeated thousands of times. - DGA activity: a burst of
NXDOMAIN(non-existent domain) responses as malware cycles through unregistered candidate domains, combined with the random-looking names themselves. - Known-bad / sinkhole hits: any internal host querying a domain on your threat-intel blocklist — by definition, a likely infection.
- Newly registered or rare domains: first-time-seen domains, or domains registered in the last few days, are disproportionately malicious.
A SIEM query (here in a readable SQL-like pseudocode — the platform-specific SPL/KQL comes in Chapter 21) to surface possible tunneling:
-- Possible DNS tunneling/exfiltration: long, high-entropy subdomains,
-- many queries to one parent domain in a short window. Illustrative.
SELECT src_host, parent_domain,
COUNT(*) AS query_count,
AVG(label_len) AS avg_subdomain_len,
AVG(entropy) AS avg_entropy
FROM dns_query_logs
WHERE event_time > NOW() - INTERVAL '1' HOUR
GROUP BY src_host, parent_domain
HAVING COUNT(*) > 100 -- unusually chatty toward one domain
AND AVG(label_len) > 30 -- long labels (normal subdomains are short)
AND AVG(entropy) > 3.5 -- random-looking (high Shannon entropy)
ORDER BY query_count DESC;
Email detections. From §9.3–9.4, the high-value email signals are:
- Authentication failures with alignment mismatch: mail claiming to be from your domain that fails DMARC — read straight from the aggregate reports (the attacker row in §9.4) or from the SEG logs.
- Look-alike / cousin domains: sender domains that are a small edit-distance away from yours or a known partner's (
meridi1anbank.example), or newly registered domains in theFrom:. - BEC linguistic and behavioral markers: financial-urgency language ("wire," "urgent," "confidential," "gift cards," "change of bank details") combined with a first-time sender, a reply-to that differs from the from, or a display name that matches an executive while the address does not.
- Reported phishing clusters: when several users report the same lure, pivot on the URL and sender to find everyone who received it and pull it from inboxes.
🛡️ Defender's Lens: The most powerful email detection is correlation, not any single rule. A message in isolation may look fine; the same message, sent to forty employees, from a domain registered yesterday, with a display name impersonating the CFO and the word "urgent" in the subject, is a high-confidence BEC attempt. The SIEM's job (Chapter 21) is to stitch these weak signals into one strong alert. Your job here is to know which weak signals exist — that is what this section gives you.
🧩 Try It in the Lab: In your own authorized lab or your personal domain, request and read a real DMARC aggregate report (free tooling and services parse the XML for you). Identify your own legitimate senders and confirm they pass. Then, separately, inspect the response headers of a few websites you use with your browser's developer tools — note which set HSTS, which set a Content-Security-Policy, and which session cookies carry
HttpOnlyandSecure. You will quickly develop an eye for who has done their homework and who has not. Authorized systems only.🔄 Check Your Understanding: 1. Name the single most characteristic DNS log signature of (a) a domain generation algorithm and (b) DNS tunneling. Why are they different? 2. Why is correlation across multiple weak signals more effective for catching BEC than any one rule, given that BEC messages often contain no malware or links?
Answers
- (a) A DGA produces a burst of
NXDOMAINresponses, because the malware cycles through many unregistered candidate domains and most do not resolve; (b) DNS tunneling produces long, high-entropy subdomain labels and a high volume of queries to a single parent domain that does resolve (to the attacker's authoritative server). They differ because a DGA is searching for a live domain (mostly failed lookups) while a tunnel is using an established one (many successful, data-bearing lookups). 2. Because a BEC message has no malware or link to trigger a content rule, its maliciousness lives in the combination of weak signals — new sender domain, display-name impersonation, financial-urgency language, reply-to mismatch — none decisive alone but jointly high-confidence; correlation is what turns those weak signals into an actionable alert.
Project Checkpoint
This chapter adds Meridian's email and DNS controls to the security program and the dnsguard.py module to bluekit.
Program increment — email & DNS controls. Building on the network architecture and perimeter controls from Chapters 6 and 7, Sam Whitfield and the team produce Meridian's email-and-DNS hardening standard. It specifies: (1) publish SPF with -all, sign all outbound with DKIM, and roll DMARC up the ladder to p=reject over one quarter, following Figure 9.3 — with the p=none listening phase used to find and fix Meridian's broken legitimate streams (the helpdesk app from the §9.4 report is the first finding); (2) enable DNSSEC signing on Meridian's externally facing zones and turn on validation at the internal resolvers; (3) deploy a DNS sinkhole fed by threat intelligence, and enable resolver query logging to the SIEM; (4) set the HTTP security-header baseline (HSTS with preload, CSP, secure-cookie flags) on the online-banking portal and verify it externally; (5) wire a report-phish button to the SOC and stand up the email/DNS detections of §9.6. The artifact slots into the program's network-security section and directly feeds the awareness program (Chapter 30) and web-app controls (Chapter 13).
bluekit increment — dnsguard.py. Three functions: check_spf and check_dmarc grade a domain's published records against the deployment guidance above, and dga_score flags algorithmically generated domains by character entropy. As always, the code is illustrative and hand-traced — never executed during authoring.
# bluekit/dnsguard.py — Chapter 9 increment
"""Audit email-auth DNS records and score domains for DGA-like randomness."""
import math
from collections import Counter
def check_spf(record: str) -> str:
"""Grade an SPF TXT record. Returns a posture string."""
if not record.startswith("v=spf1"):
return "INVALID: not an SPF record"
if "-all" in record: return "STRONG: hard-fail (-all)"
if "~all" in record: return "WEAK: soft-fail (~all) — tighten to -all"
if "?all" in record or "+all" in record:
return "DANGER: neutral/pass-all — record is decorative"
return "INCOMPLETE: no 'all' mechanism — add -all"
def check_dmarc(record: str) -> str:
"""Grade a DMARC TXT record by its enforcement policy."""
if "v=DMARC1" not in record: return "INVALID: not a DMARC record"
if "p=reject" in record: return "STRONG: enforcing (reject)"
if "p=quarantine" in record: return "MODERATE: quarantine — ramp to reject"
if "p=none" in record: return "MONITOR-ONLY: no protection yet — advance the ladder"
return "INVALID: missing policy (p=)"
def dga_score(name: str) -> float:
"""Shannon entropy (bits/char) of the leftmost label; higher = more DGA-like."""
label = name.split(".")[0]
counts = Counter(label)
n = len(label)
return round(-sum((c/n) * math.log2(c/n) for c in counts.values()), 2) if n else 0.0
if __name__ == "__main__":
print(check_spf("v=spf1 ip4:203.0.113.10 -all"))
print(check_dmarc("v=DMARC1; p=none; rua=mailto:dmarc@meridianbank.example"))
print("loan ->", dga_score("loan.meridianbank.example")) # human-readable
print("dga ->", dga_score("kq3v9xzplmw.example")) # 11 distinct chars
# Expected output:
# STRONG: hard-fail (-all)
# MONITOR-ONLY: no protection yet — advance the ladder
# loan -> 2.0
# dga -> 3.46
Trace the last two by hand to trust the tool. For dga_score("loan.meridianbank.example"), the leftmost label is loan — four characters, all distinct, so each appears with probability $1/4$. Shannon entropy is $-\sum (1/4)\log_2(1/4) = \log_2 4 = 2.0$ bits per character. For kq3v9xzplmw, all eleven characters are distinct, each with probability $1/11$, so the entropy is $\log_2 11 \approx 3.46$. The gap between a human-readable label (around 2 bits/char) and a random-looking one (above 3 bits/char) is the signal; pick a real threshold from your own baseline — roughly 3.5 bits/char is a common starting line, matching the §9.6 query. The module already does real defensive work: in one call each it tells you whether a domain's SPF is enforcing, whether its DMARC actually protects or merely watches, and whether a name looks machine-generated — three of the most common questions a SOC analyst asks about a domain, answered from the records themselves.
Summary
This chapter hardened the three protocols every organization runs and few secure well.
- DNS translates names to addresses and underlies nearly every connection. Classic DNS is unauthenticated over UDP and caches answers, which enables DNS poisoning (forged cache entries), typosquatting (look-alike registered domains), DNS tunneling/exfiltration (data smuggled in subdomain labels through the universally permitted DNS channel), and DGAs (malware generating random C2 domains).
- DNSSEC adds cryptographic signatures (a chain of trust from the root via
DS/DNSKEY/RRSIG) to provide integrity and origin authentication — it stops poisoning but does not encrypt (use DoH/DoT for that) or stop typosquatting. A DNS sinkhole returns a controlled answer for known-bad domains, acting as both a preventive and a detective control. DNS monitoring is a low-cost, high-value telemetry source. - Email rests on SMTP, which never authenticates the sender — making spoofing trivial. The threat spectrum runs from high-volume phishing to targeted spear-phishing to business email compromise (BEC), which steals the most money while often carrying no malware at all. A secure email gateway filters mail; a report-phish button and trained humans catch the rest.
- SPF authorizes sending IPs (envelope sender; breaks on forwarding; use
-all). DKIM cryptographically signs messages (survives forwarding; per-selector keys). DMARC adds alignment (authenticated domain must match the visibleFrom:), a policy (none→quarantine→reject), and reporting. Deploy in order, listen atp=noneto fix your own broken streams, then enforce. A DMARC aggregate report is both an intrusion feed and a mail-hygiene audit. - Web hardening uses HTTP security headers: HSTS (
Strict-Transport-Security) forces HTTPS and stops downgrade/SSL-stripping (usepreloadto close the first-visit gap); CSP restricts resource sources to blunt XSS;X-Content-Type-Options,X-Frame-Options, andReferrer-Policyeach close a specific hole; and secure cookies (Secure,HttpOnly,SameSite) protect session tokens. - DNS and email are detection goldmines. DGAs show as
NXDOMAINbursts; tunneling as long, high-entropy, high-volume subdomain queries; BEC as a correlation of weak signals (new domain, display-name impersonation, financial urgency). Collect the logs, or you are blind.
Spaced Review
Retrieval practice over this chapter and earlier ones (the schedule revisits Chapters 7 and 2). Answer before checking.
- (This chapter) Put SPF, DKIM, and DMARC in order of deployment and state, in one phrase each, what each one authenticates or does.
- (Chapter 7) A DNS sinkhole blocks known-bad domains at the resolution layer. How is this the same idea as a firewall's default-deny posture from Chapter 7, and at what different point in a connection attempt does each act?
- (Chapter 2) BEC is a form of social engineering, the attack category from Chapter 2. Why do social-engineering attacks like BEC bypass technical controls such as antivirus and SPF, and what does that imply about where the defense must live?
- (This chapter) Why does DNSSEC not make your DNS queries private, and what would?
Answers
1. Order: SPF and DKIM first, then DMARC. SPF authenticates *which sending IPs are authorized* (envelope sender); DKIM *cryptographically signs the message* so tampering and origin can be verified (and survives forwarding); DMARC *ties authentication to the visible `From:` via alignment, sets an enforcement policy, and provides reporting*. 2. Both are "deny by default, allow only the known-good (or block the known-bad)" applied at a chokepoint; the firewall acts on packets at the network layer when a connection is attempted, while the sinkhole acts earlier — at the *name-resolution* step, before any packet is even sent to the malicious host. 3. Social engineering targets a human and a business process rather than a software flaw, so there is no payload for antivirus to detect and (in the compromised-mailbox case) authentication passes; the defense must therefore live in *people and process* — out-of-band verification of money/data changes and a reporting culture — not only in technology. 4. DNSSEC provides integrity and origin authentication (signatures proving an answer is genuine) but leaves the query and answer in cleartext; encrypting the channel with DNS over HTTPS (DoH) or DNS over TLS (DoT) is what provides query privacy.What's Next
You have hardened the protocols that carry attacks in; the next chapter teaches you to see the attacks that get through. Chapter 10 — Network Monitoring and Traffic Analysis — moves from the application protocols to the wire itself: capturing and reading packets with Wireshark, turning packets into searchable logs with Zeek, scaling to flow data with NetFlow, and detecting the beaconing, exfiltration, and lateral movement that the DNS and email signals in §9.6 only hint at. The DNS query logs you started collecting here become one input among many to the network-visibility layer that, in Part V, feeds the SIEM. Prevention narrows the attacker's options; visibility is how you catch the options that remain.