41 min read

The breach that cost a different bank its weekend started with a single laptop in a branch office and a network that had no internal walls. An attacker phished one teller, ran a tool that impersonated the branch's gateway, and within forty minutes...

Prerequisites

  • 1
  • 3

Learning Objectives

  • Map the TCP/IP and OSI layers to the specific attack and defense opportunities that live at each one.
  • Read ports, sockets, and the TCP three-way handshake, and recognize them in logs and captures.
  • Explain network segmentation, VLANs, subnets, and DMZs, and why the flat-network perimeter is dead.
  • Identify spoofing, man-in-the-middle, and denial-of-service attacks and the controls that detect or prevent each.
  • Design a segmented network architecture for Meridian that isolates a cardholder zone from the rest of the bank.

Chapter 6: Network Security Fundamentals: TCP/IP, Ports, Protocols, and Where Attacks Live

"The network is the computer." — John Gage, Sun Microsystems

Overview

The breach that cost a different bank its weekend started with a single laptop in a branch office and a network that had no internal walls. An attacker phished one teller, ran a tool that impersonated the branch's gateway, and within forty minutes was reading traffic between the teller's workstation and the bank's core systems — because once you are on a flat network, every machine can talk to every other machine, and the network itself will helpfully tell a liar where to send the packets. The attacker never touched the perimeter firewall again after that first email. There was nothing left to touch. The inside of the bank was one undivided room, and the attacker was now standing in it.

That is the failure mode this chapter exists to prevent, and it is worth naming the uncomfortable thing it teaches: the firewall at the edge of your network — the control most people picture when they hear "network security" — did its job and was still almost irrelevant. The attacker came in through a person, not a port. Real network defense is not a single wall at the boundary. It is the shape of the whole interior: which machines can reach which other machines, what travels between them, and whether you can see any of it. A network that has been designed for security is one where compromising a teller's laptop lets the attacker reach a teller's laptop — and almost nothing else.

To build that, you have to understand how a network actually moves data, because every layer of that machinery is also an attack surface (Chapter 1) and a place to put a control (Chapter 3). We assume the perimeter has already failed — that is the only safe assumption — and we ask what holds anyway. By the end of this chapter you will read a packet the way Theo reads an alert, explain why a man-in-the-middle attack works and exactly which control stops it, and produce the first version of Meridian's segmented network architecture: a design where the cardholder data environment is a locked room inside a locked building, not a corner of an open floor.

In this chapter, you will learn to:

  • Trace data down the TCP/IP and OSI layers and name, at each layer, what an attacker can do and what a defender can do about it.
  • Read ports, sockets, and the TCP three-way handshake fluently enough to spot a scan, a flood, or a spoof in telemetry.
  • Explain segmentation, VLANs, subnets, and DMZs — and why "inside the firewall" is no longer a safe place to be.
  • Recognize ARP spoofing, man-in-the-middle, and denial-of-service attacks and pair each, immediately, with the control that detects or prevents it.
  • Design Meridian's network zones so that a foothold in one zone is contained there, and start the netfilter.py tool that parses firewall logs.

Learning Paths

This is a foundational Part II chapter that every later network and operations chapter builds on. Weight it by your goal:

🛡️ SOC Analyst: This is one of your core chapters. Live in §6.2 (you will read ports and handshakes in every investigation) and §6.5 (spoofing/MITM/DoS are alerts you will triage). The netfilter.py checkpoint is the start of reading firewall logs at scale. 🏗️ Security Engineer: §6.4 (segmentation) and §6.6 (designing Meridian's zones) are your design playbook; this is where the architecture you harden in Chapters 7 and 11 begins. 📋 GRC: Focus on §6.4 — segmentation is a PCI-DSS requirement, and you must be able to describe the cardholder data environment and its isolation to an auditor. 📜 Certification Prep: The OSI model, ports/protocols, the TCP handshake, and the attack taxonomy in §§6.1–6.5 are dense exam territory for Security+ and CISSP. key-takeaways.md maps them to exam domains.


6.1 The stack, layer by layer — the attacker's and defender's view

Theo's third week at Meridian, Marcus handed him a packet capture and said, "Tell me what's wrong with this." Theo could see the bytes. He could not yet see the story. The difference between those two — between staring at data and reading an attack — is a mental model of how networks work, and that model is the OSI model: a seven-layer conceptual framework that describes how data moves from an application on one computer, down through the machinery of the network, across the wire, and back up to an application on another computer. Each layer has one job and talks only to the layers directly above and below it. You will hear "Layer 3" and "Layer 7" in every network conversation for the rest of your career; here is what those numbers mean.

The seven layers, top to bottom, are Application (7), Presentation (6), Session (5), Transport (4), Network (3), Data Link (2), and Physical (1). A common mnemonic is "All People Seem To Need Data Processing." In practice the security world mostly cares about a handful of them, so let us be honest about which matter and ground every one in an attack and a defense.

In the real world, the OSI model's seven layers are implemented by the four-layer TCP/IP model — the actual protocol suite that runs the internet, named for its two foundational protocols, the Transmission Control Protocol (TCP) and the Internet Protocol (IP). TCP/IP collapses OSI's top three layers into one "Application" layer and its bottom two into one "Link" layer, leaving four: Application, Transport, Internet (OSI's Network layer), and Link. When someone says "Layer 3" they mean IP; "Layer 4" means TCP or UDP; "Layer 7" means the application protocol like HTTP or DNS. You need both models: OSI to name precisely where something happens, TCP/IP because it is what actually runs.

Here is the journey of one piece of data — Theo logging into Meridian's intranet — down the stack and back up, with the attack surface at each stop:

   THEO'S LAPTOP                                    INTRANET SERVER
   ────────────                                     ───────────────
 7 Application   HTTP request "GET /timesheet"  →  7 Application
                   ▲ attack: app-layer (Ch.13), phishing payloads
 6 Presentation  encrypt (TLS), encode             6 Presentation
                   ▲ attack: weak TLS, downgrade (Ch.5)
 5 Session       session established                5 Session
                   ▲ attack: session hijack/fixation (Ch.13)
 4 Transport     TCP segment, port 443          →  4 Transport
                   ▲ attack: SYN flood, port scan, spoofed ports
 3 Network       IP packet, src/dst IP address  →  3 Network
                   ▲ attack: IP spoofing, routing attacks, DDoS
 2 Data Link     Ethernet frame, MAC address     2 Data Link
                   ▲ attack: ARP spoofing, MAC flooding, VLAN hop
 1 Physical      bits on copper/fiber/radio       1 Physical
                   ▲ attack: tap the cable, rogue device, jamming
   ────────────                                     ───────────────
        └──────────► over the network wire ◄──────────┘

Figure 6.1 — The OSI stack as a defender reads it. Data is wrapped (encapsulated) in a new header at each layer going down — a packet inside a frame inside bits — and unwrapped going up. Every layer is a distinct attack surface and a distinct place to put a control.

The crucial idea here is encapsulation: as your data goes down the stack, each layer wraps it in its own header, like nesting envelopes. Your HTTP request becomes the payload of a TCP segment; the TCP segment becomes the payload of an IP packet — the fundamental unit of data the network layer routes, consisting of a header (source and destination IP addresses, among other fields) and the data it carries; the IP packet becomes the payload of an Ethernet frame with hardware (MAC) addresses; the frame becomes bits on the wire. The receiving machine unwraps each envelope in turn. This matters for defense because different controls operate at different layers, and each can only see what reaches it. A network firewall reading Layer 3 and 4 sees IP addresses and ports but not the contents of an encrypted Layer 7 request. A web application firewall (Chapter 13) reads Layer 7 but trusts that the packet got there. No single control sees everything — which is the whole reason for defense in depth (Chapter 3).

🚪 Threshold Concept: Every defensive control lives at a specific layer and is blind to the layers it does not inspect. An attacker's job is to find a layer you are not watching; a defender's job is to ensure that an attack visible at some layer is caught by a control that reads that layer. When you evaluate any network defense, the first question is always: "What layer does this operate at, and therefore what can it not see?" This reframes "we have a firewall" into the far more useful "we inspect Layers 3 and 4 at the perimeter, Layer 7 at the application, and Layer 2 nowhere — so Layer 2 attacks are invisible to us."

From the defender's seat, the layers map cleanly to the controls you will meet in this book. The Physical layer (1) is access control and tamper-evidence — a network jack in an unlocked lobby is a Layer 1 vulnerability. The Data Link layer (2) is switch security, port security, and the ARP and VLAN attacks we dissect in §6.5. The Network layer (3) is IP filtering, routing security, and the firewalls and segmentation that are this chapter's heart. The Transport layer (4) is port filtering and the stateful firewall (Chapter 7). The Session through Application layers (5–7) are TLS (Chapter 5), authentication (Chapter 16), and application security (Chapters 12–13). You do not defend "the network." You defend each layer with controls that can actually see it.

⚠️ Common Pitfall: Assuming encryption at Layer 6 protects you at Layers 2 and 3. TLS keeps an attacker from reading the contents of your intranet login, but it does nothing to stop an attacker at Layer 2 from redirecting the traffic to themselves, or at Layer 3 from flooding the server off the internet. "It's encrypted" answers a confidentiality question and leaves availability and lower-layer integrity wide open. Always ask which leg of the CIA triad (Chapter 1) and which OSI layer a control actually covers.

🔄 Check Your Understanding: 1. A control inspects source and destination IP addresses and TCP port numbers but cannot read the encrypted contents of a request. Which OSI layers does it operate at, and which does it not see? 2. Why does encapsulation mean that no single network control can defend against every attack?

Answers

  1. It operates at Layer 3 (IP addresses) and Layer 4 (TCP ports) — a classic stateful firewall — and cannot see Layers 5–7 (the encrypted session and application content). 2. Because each layer wraps the one above it in a new header, a control that reads one layer's header is blind to the deeper payload; defending every attack requires controls at multiple layers, i.e., defense in depth.

6.2 Ports, sockets, and the three-way handshake

If IP addresses get a packet to the right machine, ports get it to the right program on that machine. A port is a 16-bit number (0–65535) that identifies a specific network service or connection endpoint, so that one server can run a web service, an email service, and a database simultaneously without their traffic colliding. By long-standing convention, common services listen on well-known ports (0–1023): HTTP on 80, HTTPS on 443, SSH on 22, DNS on 53, SMTP on 25, RDP on 3389. A socket is the combination of an IP address and a port — for example 192.0.2.10:443 — and it is the precise endpoint of a network connection. A full connection is defined by four values together (the "4-tuple"): source IP, source port, destination IP, destination port. That 4-tuple is how a server keeps a thousand simultaneous connections straight, and — for you — how you tell one conversation from another in a log.

This is not trivia. Ports are the vocabulary of network defense. A firewall rule is, at bottom, a statement about ports and addresses: "allow the internet to reach 203.0.113.10 on port 443, and nothing else." A port scan — an attacker's reconnaissance — is a sweep across ports asking "what's listening here?" An unexpected listening port on a server ("why is this database answering on the public internet?") is often the first sign of a misconfiguration or a compromise. When Theo investigates an alert, one of his first moves is to ask which ports were involved, because the port frequently names the service and therefore the attacker's intent.

Most of this traffic rides on TCP, which is a connection-oriented protocol: before any data flows, the two machines perform the three-way handshake — a three-message exchange that establishes a reliable, ordered connection and synchronizes sequence numbers. It is the single most important sequence to recognize in network security, because attacks against it are common and look distinctive in logs. The three steps:

   CLIENT (Theo's laptop)                     SERVER (intranet, port 443)
   ──────────────────────                     ───────────────────────────
        │   ──── SYN (seq=x) ────────────────────►   │   "I want to connect"
        │                                            │
        │   ◄──── SYN-ACK (seq=y, ack=x+1) ──────    │   "OK, and I want to too"
        │                                            │
        │   ──── ACK (ack=y+1) ──────────────────►   │   "Acknowledged — connected"
        │                                            │
        │   ═══════ connection ESTABLISHED ═══════   │   (data now flows)

Figure 6.2 — The TCP three-way handshake: SYN, SYN-ACK, ACK. Each side proposes an initial sequence number and acknowledges the other's, so both ends agree on where the conversation begins and can detect lost or reordered data.

Read it as a conversation. The client sends SYN (synchronize): "I'd like to connect; my sequence number starts at x." The server replies SYN-ACK: "Acknowledged (here's x+1), and I'd like to connect too; my sequence starts at y." The client sends ACK: "Acknowledged (y+1) — we're connected." Only now does data flow. UDP, the other major transport protocol, skips all of this: it is connectionless, fire-and-forget, used for DNS, voice, and video where speed beats reliability. UDP's lack of a handshake makes it easy to spoof (there is no return acknowledgment to forge) and is why so many amplification floods (§6.5) use UDP services.

🛡️ Defender's Lens: The handshake is a detection goldmine. A normal connection shows SYN → SYN-ACK → ACK and then data. A port scan often shows a flood of SYNs to many different ports with no completed handshakes — the scanner sends SYN, learns whether it gets SYN-ACK (port open) or RST (port closed), and never finishes. A SYN flood (a denial-of-service technique, §6.5) shows thousands of SYNs with no final ACK, deliberately leaving half-open connections to exhaust the server. When you learn to see the shape of the handshake in flow data, scans and floods stop being abstract and become patterns you recognize at a glance. This is the foundation of the traffic analysis you will do at scale in Chapter 10.

Here is a tiny, illustrative slice of a connection log of the kind you will read constantly — TCP state transitions for one server, source addresses in the documentation range:

time      src_ip          src_port  dst_ip        dst_port  flags     state
10:14:02  198.51.100.7    51234     192.0.2.10    443       SYN       NEW
10:14:02  192.0.2.10      443       198.51.100.7  51234     SYN,ACK   NEW
10:14:02  198.51.100.7    51234     192.0.2.10    443       ACK       ESTABLISHED
10:14:31  203.0.113.66    40001     192.0.2.10    22        SYN       NEW
10:14:31  203.0.113.66    40002     192.0.2.10    23        SYN       NEW
10:14:31  203.0.113.66    40003     192.0.2.10    25        SYN       NEW
10:14:31  203.0.113.66    40004     192.0.2.10    3389      SYN       NEW

The first three lines are a healthy handshake: a client at 198.51.100.7 completes a connection to the web service on 443. The last four are a different animal: a single source at 203.0.113.66 sending lone SYNs to ports 22, 23, 25, and 3389 in the same second, none of them ever reaching ESTABLISHED. That is the signature of a port scan — one host knocking on many doors to learn which are open. Neither pattern is, by itself, proof of an attack (scanning is constant background noise, as Chapter 1 noted), but the shape tells you instantly which conversation is normal and which deserves a second look.

🧩 Try It in the Lab: In your own VM or home lab — never on a network you do not own or are not authorized to test — install Wireshark and capture traffic while you load a single web page. Find the three-way handshake: the SYN, the SYN-ACK, the ACK. Note the source and destination ports. Then look at how many separate connections (4-tuples) one page actually opens. Seeing the handshake with your own eyes makes §6.2 permanent. We go deep on Wireshark in Chapter 10.

🔄 Check Your Understanding: 1. A log shows hundreds of SYN packets from one source to one server, almost none followed by an ACK. Name two different things this could be and the field that distinguishes them. 2. What is a socket, and why does it take a 4-tuple (not just a destination port) to uniquely identify a connection?

Answers

  1. It could be a SYN flood (a DoS attack — many SYNs to one port, intending to exhaust the server) or a port scan (SYNs to many different ports, intending to enumerate open services). The destination-port field distinguishes them: one port versus many. 2. A socket is an IP address plus a port (an endpoint). A connection needs source IP, source port, destination IP, and destination port together, because many clients may connect to the same destination socket simultaneously and the source side disambiguates them.

6.3 Where attacks live at each layer

Now we can answer Marcus's question — "what's wrong with this packet?" — systematically, by walking the stack and asking, at each layer, what can go wrong here, and how would I see it? This is how experienced defenders think: not "is this bad?" but "if this were bad, which layer would the badness live at, and is something watching that layer?" Let us tour the layers that matter most, threat then defense, which is the rhythm of this entire book.

Layer 2 (Data Link) — the trusted neighborhood. Within a single local network segment, machines find each other using MAC addresses and the Address Resolution Protocol (ARP), and here is the structural weakness: ARP has no authentication. A machine that claims "I am the gateway" is believed. This is the basis of ARP spoofing (§6.5) and of MAC flooding, where an attacker overwhelms a switch's address table to make it broadcast all traffic. Layer 2 attacks are invisible to a Layer 3 firewall because they never leave the local segment — the packets never get to the firewall. Defense: switch port security (limit MAC addresses per port), dynamic ARP inspection, and — the structural answer — segmentation, so that a Layer 2 attack is confined to one small segment instead of the whole bank.

Layer 3 (Network) — the address you can lie about. IP packets carry a source address, and nothing inherently verifies it. An attacker can forge — spoof — the source IP, claiming to be someone they are not. Spoofing enables reflection/amplification DDoS (§6.5) and lets attackers evade naive IP-based access rules. Routing protocols can also be poisoned to reroute traffic. Defense: ingress/egress filtering (drop packets whose source address could not legitimately have come from where they arrived — known as BCP 38), anti-spoofing rules at the perimeter, and not trusting IP addresses as identity.

Layer 4 (Transport) — the doors and the floods. This is where ports live, and therefore where scanning, SYN floods, and connection-exhaustion attacks operate. A denial-of-service attack often lives here. Defense: the stateful firewall (Chapter 7), which tracks the state of each connection and can drop packets that do not belong to a legitimate, established conversation; SYN cookies to survive SYN floods; rate limiting.

Layers 5–7 (Session, Presentation, Application) — where the meaning is. The actual content — the HTTP request, the SQL query, the login — lives here, and so do the richest attacks: SQL injection, cross-site scripting, session hijacking, credential phishing (Chapters 12–13, 16). Critically, if the traffic is encrypted with TLS (Chapter 5), a network device cannot read Layer 7 without terminating or inspecting the encryption. Defense: application security, web application firewalls, authentication, and TLS inspection where policy and privacy allow.

🔗 Connection: Notice how the layer model organizes the entire book. Layers 1–4 are this part (Network Security, Chapters 6–10). Layers 5–7 are Part III (System and Application Security, Chapters 11–15) and Part IV (Identity, Chapters 16–20). The OSI model is not just a networking concept — it is a map of where each of your defenses lives and which attacks each one can and cannot see.

There is a deeper lesson in this tour, and it is the second of our recurring themes made concrete: attackers will always probe the layer you are not watching. A team that pours its budget into a sophisticated Layer 7 web application firewall and never enables Layer 2 port security has built a bank vault with a screen door at the back. The attacker does not attack your strength; they find your blind layer. This is why defense in depth (Chapter 3) is not optional decoration — it is the only response to an adversary who gets to choose where they strike.

📟 War Story: A constructed but representative example. A retailer invested heavily in next-generation perimeter firewalls and a web application firewall, and passed every external penetration test for years. Then an attacker who got a single foothold via a phished employee found that the internal network was completely flat and unmonitored — no segmentation, no Layer 2 protections, no internal traffic inspection. From that one laptop, using ordinary ARP spoofing and lateral movement at Layers 2 and 3, the attacker reached the point-of-sale systems in weeks. Every dollar had gone to the perimeter (the layers the pen-testers attacked) and none to the interior (the layers a real intruder uses once inside). The perimeter was a fortress wall around an open field.

🔄 Check Your Understanding: 1. Why can a Layer 3 perimeter firewall not detect an ARP spoofing attack happening between two workstations in a branch? 2. An attacker forges the source IP address of their packets. Which layer is this, what is it called, and name one defense.

Answers

  1. ARP operates at Layer 2 and is confined to the local network segment; the spoofed ARP traffic never traverses the Layer 3 firewall, so the firewall never sees it. Defense must live on the local segment (port security, dynamic ARP inspection) or through segmentation. 2. It is at Layer 3 (Network); it is IP spoofing; defenses include ingress/egress (anti-spoofing) filtering per BCP 38 and not trusting source IP as identity.

6.4 Segmentation, VLANs, subnets, and DMZs

We now arrive at the single most important defensive idea in this chapter, the one that would have saved the bank in this chapter's opening: network segmentation — dividing a network into separate zones with controlled, monitored, default-denied communication between them, so that compromising one zone does not grant access to the others. A flat network — one undivided space where every device can reach every other — means that one foothold equals total reach. A segmented network means a foothold reaches only its own zone, and crossing into another zone requires passing a control that can deny and log the attempt. Segmentation is how you make "assume breach" (Chapter 3) survivable: you assume the attacker gets in, and you ensure that getting in somewhere is not getting in everywhere.

Three related mechanisms build segmentation, and beginners often blur them, so let us be precise.

A subnet (subnetwork) is a logically subdivided range of IP addresses — a Layer 3 boundary. Splitting 10.0.0.0/16 into 10.0.1.0/24, 10.0.2.0/24, and so on creates separate IP neighborhoods, and a router (or firewall) sits between them, giving you a natural place to enforce rules about which subnet may talk to which. Subnetting is the addressing foundation of segmentation.

A VLAN (virtual local area network) is a Layer 2 mechanism that lets one physical switch behave as several logically separate switches, isolating groups of ports into independent broadcast domains even though they share hardware. VLAN 10 (tellers) and VLAN 20 (guests) on the same switch cannot see each other's Layer 2 traffic; to communicate at all, their traffic must go up to a Layer 3 device that can filter it. VLANs let you segment without running separate cables for every zone — but they are only as strong as their configuration (misconfigured VLANs can sometimes be "hopped," which is why a VLAN is a boundary, not a vault).

A DMZ (demilitarized zone) is a special segment that sits between the untrusted internet and the trusted internal network, hosting the systems that must be reachable from outside — a public web server, a mail gateway — so that those exposed systems are isolated from the internal network. The logic is unforgiving: anything reachable from the internet will eventually be probed and may be compromised (Chapter 1), so you place it where its compromise is contained. If Meridian's public web server lives in a DMZ and is breached, the attacker is in the DMZ — not in the core banking network — because a second firewall stands between the DMZ and the interior, denying by default.

Closely tied to the DMZ is NAT (network address translation), the technique by which a router rewrites the IP addresses in packets as they cross it — typically mapping many private internal addresses (the RFC 1918 ranges like 10.0.0.0/8) to one public address. NAT exists primarily to conserve scarce public IPv4 addresses, but it has a security side effect worth understanding precisely: because internal hosts have no publicly routable address, they are not directly reachable from the internet. This is a useful obstacle — but it is not a security control, and treating it as one is a classic mistake. NAT hides addresses; it does not authenticate, filter content, or stop an attacker who arrives through an allowed connection (like a phished user's browser reaching out). NAT is a side effect you benefit from, not a wall you rely on.

Here is the vocabulary that ties the interior together. Traffic that crosses the boundary between your network and the outside world — a customer's browser reaching the online-banking server, the server reaching the internet — is north-south traffic. Traffic that moves laterally between systems inside your network — one server talking to another, a workstation reaching a file share — is east-west traffic. The names come from the way network diagrams are drawn, with the internet at the top (north) and internal systems spread across the middle (east-west). This distinction is the heart of modern network defense:

🚪 Threshold Concept: For two decades, network security meant guarding north-south traffic — building a strong perimeter between inside and outside. But almost every serious breach involves east-west movement: the attacker gets one foothold (north-south, through a person or an exposed service) and then moves sideways (east-west) toward the valuable systems. A perimeter firewall sees none of this east-west traffic, because it never crosses the perimeter. The realization that the inside of your network is where attackers actually operate is what killed the perimeter as a sufficient defense and gave rise to segmentation, microsegmentation (Chapter 7), and ultimately zero trust (Chapter 32). Internalize this: the attacker's goal is east-west movement, and an undivided interior is a superhighway for it.

How does an attacker abuse a flat (unsegmented) network? Exactly as the chapter's opening described: once on any machine, they enumerate the network, use Layer 2 and 3 techniques to move laterally, and reach systems that should never have been reachable from a teller's laptop. There is no control between zones because there are no zones. How you detect and prevent it: segment the network into zones by trust and function (cardholder data, core banking, corporate, branch, guest, management); place firewalls or access-control lists between zones with a default-deny posture (Chapter 7) so that east-west traffic must be explicitly permitted; monitor inter-zone traffic so that an attempt to cross a boundary generates an alert. The single most cost-effective network security investment most organizations can make is not a better perimeter firewall — it is internal segmentation that turns one breach into a contained incident.

⚠️ Common Pitfall: "We have VLANs, so we're segmented." VLANs separate traffic at Layer 2, but if the Layer 3 device that routes between them permits any-to-any traffic, you have logical separation with no security benefit — the zones can still reach each other freely. Segmentation is not the VLAN; it is the enforced, default-deny policy between zones. A VLAN with a permissive inter-VLAN routing rule is a labeled open door. Always verify what the firewall between the segments actually allows.

🔄 Check Your Understanding: 1. Distinguish north-south from east-west traffic, and explain why a traditional perimeter firewall provides little defense against lateral movement. 2. Why is NAT not a security control, even though internal hosts behind it are not directly reachable from the internet?

Answers

  1. North-south crosses the network boundary (in/out to the internet); east-west moves laterally between internal systems. A perimeter firewall only inspects traffic crossing the boundary (north-south), so east-west lateral movement inside the network never passes it and is not filtered. 2. NAT only rewrites/hides addresses to conserve IPs; it does not authenticate, inspect content, or block connections that are allowed (e.g., an internal user's outbound browser session that an attacker rides). It is an obstacle, not an enforced policy, and provides no protection once a connection is established through it.

6.5 Spoofing, MITM, and DoS/DDoS — and defenses

We have named these attacks in passing; now we treat the three families that define network-layer threats, each in the book's rhythm: how it works, how an attacker abuses it, and — always — how you detect and prevent it. None of what follows is a recipe; it is the defender's understanding of an adversary's move, which is the only way to counter it.

Spoofing and ARP spoofing

Spoofing, broadly, is forging an identifier to impersonate another system — a source IP address, a MAC address, an email sender, a DNS response. The network-layer cases matter here. IP spoofing (Layer 3) forges the source address of packets; because IP has no built-in authentication of the source, the receiver may believe a lie. How it's abused: to launch amplified DDoS (forging the victim's address so replies flood the victim), to bypass naive IP-allowlist controls, and to obscure the attacker's origin. Detection and prevention: ingress/egress filtering (BCP 38) at network edges drops packets whose claimed source could not have legitimately arrived from that direction; do not use source IP as an authentication factor; cryptographic authentication (Chapters 4–5, 16) defeats spoofing by binding identity to something unforgeable.

The most important Layer 2 case is ARP spoofing (also called ARP poisoning): an attacker on the local network sends forged ARP messages associating their own MAC address with the IP address of another host — usually the default gateway — so that traffic meant for the gateway is sent to the attacker instead. Because ARP is unauthenticated (§6.3), the switch and the victims simply believe the forged mapping. This is the engine of most local man-in-the-middle attacks, and it was the technique in the chapter's opening breach.

   NORMAL                                    UNDER ARP SPOOFING
   ──────                                    ──────────────────
   Teller PC ──► Gateway ──► Core            Teller PC ──► [Attacker] ──► Gateway ──► Core
   (10.0.10.5)   (10.0.10.1)                 (10.0.10.5)   (forged as       (10.0.10.1)
                                                            10.0.10.1)
   ARP table:                                Poisoned ARP table on Teller PC:
   10.0.10.1 -> aa:bb:cc:11:22:33 (gateway)  10.0.10.1 -> de:ad:be:ef:00:01 (ATTACKER!)

Figure 6.3 — ARP spoofing inserts the attacker between the victim and the gateway. The teller's PC now sends "gateway" traffic to the attacker's MAC address; the attacker forwards it on (so nothing appears broken) while reading and potentially altering it — a man-in-the-middle.

Man-in-the-middle (MITM)

A man-in-the-middle attack is one in which the attacker secretly positions themselves between two communicating parties, relaying and possibly altering the traffic, while each party believes it is talking directly to the other. ARP spoofing is the most common way to achieve a MITM on a local network, but a MITM can also be set up via a rogue wireless access point (Chapter 8), a malicious DNS response (Chapter 9), or a compromised router. Once in the middle, the attacker can read unencrypted traffic, harvest credentials, and inject content. How it's abused: exactly the chapter's opening — read the teller's session, capture credentials, reach the core. Detection and prevention: this is where lower-layer and upper-layer defenses combine, and it is a clean illustration of defense in depth. At Layer 2, dynamic ARP inspection and port security on managed switches detect and block ARP spoofing; static ARP entries for critical gateways help; and segmentation shrinks the population of machines an attacker can reach to MITM in the first place. At Layers 5–7, encryption is the decisive control: if the teller's traffic is protected by properly validated TLS (Chapter 5), the man in the middle can relay the bytes but cannot read or alter them without breaking the cryptography or presenting an invalid certificate that the client should reject. A MITM defeats confidentiality and integrity only when the traffic is unencrypted or the encryption is improperly validated. Watch for the telltale signs in telemetry: a host suddenly answering for many IP addresses (ARP anomalies), unexpected certificate warnings, or duplicate MAC/IP bindings in switch logs.

🛡️ Defender's Lens: The reason banks obsess over TLS everywhere — even on internal traffic — is precisely the MITM. A defender who assumes the internal network is trustworthy is one ARP spoof away from an attacker reading internal traffic. "Assume breach" applied to the network means: encrypt internal traffic too, because you must assume someone is already in the middle. This is also the seed of zero trust (Chapter 32), which discards the idea of a trusted internal network entirely.

Denial of service (DoS) and distributed denial of service (DDoS)

A denial-of-service attack aims not to steal or alter data but to make a system or network unavailable to its legitimate users — an attack on the availability leg of the CIA triad (Chapter 1). A distributed denial-of-service attack does the same from many sources at once, typically a botnet of thousands of compromised machines, making it far harder to block by source. DoS/DDoS comes in flavors: volumetric (flood the target's bandwidth — often via reflection/amplification, where the attacker spoofs the victim's IP and triggers large responses from third-party servers like open DNS or NTP, multiplying their firepower); protocol (exhaust connection state — the SYN flood of §6.2, which sends a torrent of SYNs and never completes the handshakes, filling the server's table of half-open connections); and application-layer (Layer 7 — slow, low-volume requests that exhaust application resources while looking almost legitimate). How it's abused: extortion ("pay or we keep your site down"), distraction (a DDoS as cover for a quieter intrusion elsewhere), and pure disruption. Detection and prevention: traffic baselining and anomaly detection (a sudden 50× spike in inbound traffic is visible if you are watching — Chapter 10); upstream DDoS-mitigation and scrubbing services that absorb volumetric floods before they reach you; SYN cookies and connection rate-limiting for protocol attacks; rate-limiting and application-aware filtering (and the WAF of Chapter 13) for Layer 7; and over-provisioning and anycast for resilience. Critically, defending a large DDoS requires capacity upstream of you — you cannot absorb a 100-Gbps flood on a 1-Gbps link, which is why this is one defense organizations almost always buy as a service.

Here is a compact illustrative comparison of normal traffic versus a SYN flood as you would see it in flow telemetry:

   NORMAL handshake completion rate           SYN FLOOD (protocol DoS)
   ────────────────────────────────           ────────────────────────
   SYN sent:        1,000 / min               SYN sent:      900,000 / min
   SYN-ACK:         1,000 / min               SYN-ACK:       900,000 / min
   ACK (completed): 985 / min  (~98%)         ACK (completed): 1,200 / min (~0.1%)
   half-open conns: ~15 (transient)           half-open conns: ~600,000 (table FULL)
                                              src IPs: spoofed, thousands, random

The diagnostic is the completion ratio: in normal traffic, almost every SYN becomes a completed connection; in a SYN flood, a torrent of SYNs arrives and almost none complete, deliberately filling the server's half-open connection table so it can accept no legitimate connections. The spoofed, random source addresses are why you cannot simply block the attacker by IP — and why anti-spoofing filtering and SYN cookies, not an IP blocklist, are the right defenses.

⚠️ Common Pitfall: Trying to stop a volumetric DDoS with your own firewall. By the time the flood reaches your firewall, it has already saturated the link in front of it — the firewall can drop the packets, but the bandwidth is already consumed and legitimate traffic is already starved. Volumetric DDoS must be absorbed upstream, at your ISP or a scrubbing provider with far more capacity than you have. Knowing where a defense must sit (upstream, not at your edge) is as important as knowing what it is.

🔄 Check Your Understanding: 1. A MITM attacker successfully sits between a teller and the gateway, but all the teller's traffic is protected by properly validated TLS. What can and cannot the attacker do, and why? 2. Why does a volumetric DDoS using spoofed source IPs need to be mitigated upstream rather than at your own firewall, and why can't you just block the attacking IPs?

Answers

  1. The attacker can relay the encrypted bytes and see metadata (that a connection exists, to where, how much data) but cannot read or alter the contents, because validated TLS provides confidentiality and integrity bound to the server's authenticated certificate; tampering or substituting a certificate would trigger a warning the client should reject. 2. The flood saturates the network link upstream of the firewall, so by the time packets reach your edge the bandwidth is already consumed; you need a provider with more capacity to absorb it first. You can't block by IP because the sources are spoofed and numerous (a botnet), so an IP blocklist is futile and may even block legitimate users.

6.6 Designing Meridian's network zones

It is time to turn principle into architecture. Sam Whitfield, Meridian's security engineer, has been asked to do what the bank in this chapter's opening never did: divide the network so that a foothold in one place is contained. He starts not from products but from a question this chapter has built toward — which systems must talk to which, and what is the blast radius if any one zone is compromised? The answer is a set of trust zones, each a separate segment with default-deny between them.

Meridian's environment (frozen in the bible) gives Sam his zones. The internet is untrusted, full stop. A DMZ holds the systems that must be internet-reachable: the public website, the online-banking front-end, and the email gateway. The core zone holds the crown jewels — the legacy core-banking system and the systems of record — and is reachable only from narrowly defined places, never from the internet and never directly from a branch teller. The cardholder data environment (CDE) is segmented even from the rest of the core, because PCI-DSS demands it and because card data is a magnet for fraud: it is a locked room inside the locked core. The branch zone holds teller workstations and branch infrastructure across 120 locations; tellers need to reach specific banking applications and nothing else. A corporate zone holds general staff and email. A separate management zone holds the administrative interfaces of the network gear itself, reachable only from privileged workstations. And a guest WiFi zone (Chapter 8) is isolated entirely, with a path to the internet and to nothing internal.

Here is Sam's first architecture — the diagram he will present at the checkpoint, and the artifact this chapter contributes to Meridian's program:

                         ┌─────────────────────┐
                         │      INTERNET        │   (untrusted)
                         └──────────┬───────────┘
                                    │  north-south only
                         ┌──────────┴───────────┐
                         │   PERIMETER FIREWALL  │   default-deny inbound
                         └──────────┬───────────┘
                                    │
              ┌─────────────────────┴─────────────────────┐
              │                  DMZ                        │  public web,
              │   [web]   [online-banking front-end]  [mail │  banking front-end,
              │                                       gw]   │  mail gateway
              └─────────────────────┬─────────────────────┘
                                    │
                         ┌──────────┴───────────┐
                         │   INTERNAL FIREWALL   │   default-deny between zones
                         └──────────┬───────────┘
            ┌───────────────┬───────┴───────┬───────────────┐
            │               │               │               │
     ┌──────┴─────┐  ┌──────┴─────┐  ┌──────┴──────┐ ┌──────┴──────┐
     │ CORPORATE  │  │  BRANCH    │  │    CORE      │ │ MANAGEMENT  │
     │ staff, M365│  │ 120 sites, │  │ core-banking,│ │ device admin│
     │            │  │ tellers    │  │ systems of   │ │ (priv. only)│
     │            │  │            │  │ record       │ │             │
     └────────────┘  └────────────┘  └──────┬───────┘ └─────────────┘
                                            │  tightly controlled
                                     ┌──────┴───────┐
                                     │     CDE       │  cardholder data env.
                                     │ (PCI-DSS):    │  locked room inside
                                     │ card systems  │  the core; least access
                                     └──────────────┘

     [ GUEST WiFi ] ──► internet only, isolated from everything internal

Figure 6.4 — Meridian's network zones, version 1. Two firewall tiers (perimeter and internal) and a default-deny posture between zones turn the bank from one open room into a building of locked rooms. The CDE is segmented even from the core, satisfying PCI-DSS and shrinking the blast radius of any single compromise.

Walk the design as a defender. The perimeter firewall handles north-south traffic and denies inbound by default — only the DMZ services are reachable from the internet, each on exactly one port. The DMZ is deliberately exposed and deliberately isolated: if the public web server is breached, the attacker is in the DMZ and faces a second firewall before reaching anything internal. The internal firewall enforces default-deny between every internal zone, so that east-west traffic — the lateral movement attackers depend on (§6.4) — must be explicitly permitted and is logged when it is. A teller's workstation in the branch zone can reach the specific banking application it needs and is denied everything else; a breach of that teller's laptop reaches the teller's zone and stops. The CDE is the strictest zone of all, segmented from the core and accessible only from a handful of authorized systems, because the worst case — card data theft — must require crossing the most boundaries.

This is segmentation as the answer to a concrete fear, not a compliance checkbox. Compare it to the chapter's opening: there, one phished teller equaled total reach because the inside was flat. Here, one phished teller equals one compromised workstation in one zone, an east-west movement attempt that hits a default-deny rule and generates an alert in Marcus's SOC. The architecture does not prevent the phish (people will click — Chapter 1's theme 3) and does not pretend to. It ensures the phish is survivable. That is the whole point of designing for "assume breach."

⚖️ Authorization & Ethics: A note as you start designing and testing networks. Mapping, scanning, and capturing traffic on a network are powerful and, on a network you do not own or are not explicitly authorized to assess, potentially illegal under laws like the U.S. Computer Fraud and Abuse Act. Every technique in this chapter — reading packets, scanning ports, analyzing ARP — is for systems you own or have written authorization to defend or test. When you validate Meridian's segmentation, you do it in a lab or with a signed scope, never against a production network you have not been cleared to touch. We return to the legal landscape in Chapter 39.

🔄 Check Your Understanding: 1. Why is Meridian's online-banking front-end placed in the DMZ rather than in the core zone with the systems of record? 2. In this design, what happens — step by step — when an attacker phishes a branch teller and lands on their workstation? Contrast that with the flat-network outcome in the chapter's opening.

Answers

  1. The front-end must be reachable from the internet, and anything internet-reachable will be probed and may be compromised; placing it in the DMZ isolates it behind a second firewall so that its compromise does not directly expose the systems of record in the core. 2. The attacker controls one workstation in the branch zone; any attempt to move east-west toward the core, CDE, or other zones hits the internal firewall's default-deny policy, is denied, and is logged as an alert — so the breach is contained to one zone. On the flat network, the same foothold could reach every system directly, turning one click into total compromise.

Project Checkpoint

Meridian's program now gains its network architecture (version 1), and bluekit gains its first network module.

Program increment — network architecture diagram v1. This chapter's deliverable is exactly Figure 6.4 plus a one-page description of each zone, its trust level, what it contains, and the default-deny posture between zones — the network section of the security program Dana will present to the board. Crucially, it documents the cardholder data environment as a segmented zone, which is the foundation of Meridian's PCI-DSS scope (Chapter 28): by isolating the CDE, Meridian shrinks the systems "in scope" for the most demanding standard it faces, which is both a security win and an audit win. The diagram becomes the canvas Chapter 7 fills in with concrete firewall rules and IDS/IPS placement, and that later chapters extend with monitoring (Chapter 10) and zero-trust microsegmentation (Chapter 32). The running artifact lives in the capstone folder; templates are in Appendix I.

bluekit increment — netfilter.py with parse_fw_log(line). A defender lives in firewall logs, and the first skill is turning a raw log line into a structured record you can filter, count, and alert on. This module parses one common firewall log format into a dictionary; Chapter 7 extends it with rule_matches(pkt, rule) and default_deny(rules) so the toolkit can reason about rulesets. As always, the code is illustrative and never executed during authoring — the expected output is hand-traced in a comment.

# bluekit/netfilter.py  — Chapter 6 increment
"""Parse firewall logs into structured records — the first network tool.

A firewall log line is the ground truth of what crossed (or was denied at) a
zone boundary. We turn the raw text into a dict a SOC can filter and count.
Extended in Chapter 7 with rule_matches() and default_deny().
"""

def parse_fw_log(line: str) -> dict:
    """Parse one space-delimited 'key=value' firewall log line into a dict.

    Expected fields include action, src, dst, dport, proto. Unknown keys are
    kept; a line with no recognizable pairs raises ValueError (an integrity
    check on your own input).
    """
    fields = {}
    for token in line.split():
        if "=" in token:
            key, _, value = token.partition("=")
            fields[key] = value
    if not fields:
        raise ValueError(f"no key=value pairs found in: {line!r}")
    fields["denied"] = fields.get("action", "").upper() in ("DENY", "DROP", "BLOCK")
    return fields


if __name__ == "__main__":
    log = [
        "action=ALLOW src=198.51.100.7 dst=192.0.2.10 dport=443 proto=tcp",
        "action=DENY  src=203.0.113.66 dst=192.0.2.10 dport=22  proto=tcp",
    ]
    for line in log:
        r = parse_fw_log(line)
        flag = "DENIED " if r["denied"] else "allowed"
        print(f"{flag} {r['src']:>15} -> {r['dst']}:{r['dport']}/{r['proto']}")

# Expected output:
# allowed    198.51.100.7 -> 192.0.2.10:443/tcp
# DENIED    203.0.113.66 -> 192.0.2.10:22/tcp

Read what this twenty-line module gives a defender. It refuses an unparseable line (a small integrity control on your own tooling, exactly as riskcalc.py refused bad input in Chapter 1), it normalizes the many ways a firewall might say "blocked" into one denied flag, and it produces a record you can now filter ("show me every DENY to port 22") or feed into the rule-matching logic Chapter 7 adds. The denied connection in the sample — a lone attempt to reach SSH on port 22, blocked by default-deny — is precisely the kind of event that, repeated across many ports, reveals the port scan from §6.2. You have written the first line of Meridian's network monitoring.

Summary

This chapter built the network model that the rest of Part II — and much of the book — depends on.

  • The OSI model (7 layers) and TCP/IP model (4 layers) describe how data moves; via encapsulation, each layer wraps the one above it. Every control lives at a specific layer and is blind to the layers it does not inspect — the structural reason for defense in depth on the network.
  • A packet is the Layer 3 unit (with source/destination IP); a port (0–65535) identifies a service; a socket is an IP + port; a connection is a 4-tuple (src IP/port, dst IP/port).
  • The TCP three-way handshake (SYN → SYN-ACK → ACK) establishes a connection; its shape in telemetry distinguishes normal traffic, port scans (SYNs to many ports, no completion), and SYN floods (SYNs to one port, no completion).
  • Attacks map to layers: ARP spoofing and MAC flooding at L2; IP spoofing, routing attacks, and DDoS at L3; scans and floods at L4; injection, XSS, and session attacks at L5–7. Attackers probe the layer you are not watching.
  • Segmentation (default-denied zones) makes "assume breach" survivable. Subnets are the L3 boundary, VLANs the L2 mechanism, DMZs the isolated zone for internet-facing systems; NAT hides addresses but is not a security control.
  • North-south traffic crosses the perimeter; east-west traffic moves laterally inside — and east-west lateral movement, invisible to a perimeter firewall, is how real breaches spread. This killed the sufficient perimeter.
  • Spoofing forges an identifier (defense: anti-spoofing/BCP 38 filtering, cryptographic identity); MITM sits between two parties (defense: L2 ARP inspection/port security and validated TLS encryption — defense in depth); DoS/DDoS attacks availability (defense: upstream scrubbing for volumetric, SYN cookies for protocol, rate-limiting/WAF for L7 — mitigate volumetric upstream, not at your own edge).
  • Meridian's network architecture v1 divides the bank into default-denied zones (internet / DMZ / core / CDE / branch / corporate / management / guest), isolating the cardholder data environment and turning one foothold into a contained incident. bluekit gains netfilter.pyparse_fw_log(line).

Spaced Review

Retrieve, without scrolling up. These revisit Chapter 3 (principles) and Chapter 1 (foundations) alongside this chapter, so the ideas resurface at expanding intervals.

  1. (Ch.3) Classify network segmentation by control function and nature: is a default-deny firewall between zones preventive or detective, and technical, administrative, or physical? How does it embody least privilege and defense in depth?
  2. (Ch.1) A SYN flood makes Meridian's online-banking portal unreachable but steals and alters nothing. Which leg of the CIA triad does it attack, and why do new defenders sometimes underrate this kind of harm?
  3. (Ch.3) "Assume breach" is a Chapter 3 idea. Explain how network segmentation is the network-layer implementation of assume-breach.
  4. (Ch.1) Using risk = likelihood × impact, why might "no internal segmentation" score as a higher-priority finding than a single missing patch on an isolated server?
Answers 1. It is primarily **preventive** (it blocks unauthorized traffic) and also **detective** (it logs denied attempts); its nature is **technical**. It embodies least privilege by granting each zone only the connectivity it needs, and defense in depth by adding an internal layer that holds even after the perimeter is breached. 2. It attacks **availability**; new defenders underrate it because no data is disclosed or changed, but for a bank that cannot process transactions, an outage can be the most damaging breach of all (Chapter 1's point that availability *is* security). 3. Assume-breach designs each layer as if the prior one failed; segmentation assumes the attacker gets a foothold *somewhere* and ensures that getting in to one zone is not getting in to all of them — the foothold is contained and its lateral movement is denied and logged. 4. Because likelihood and impact are both high: a flat internal network is reachable by any foothold (high likelihood of being abused for lateral movement) and the impact is total reach to crown jewels, whereas an isolated unpatched server has low likelihood (unreachable) and low impact (no path to value) — exactly the printer-vs-portal contrast from Chapter 1.

What's Next

You now have the map: how networks move data, where attacks live at each layer, and how segmentation turns a flat bank into a building of locked rooms. But a zone boundary is only as good as the control that enforces it, and so far we have drawn firewalls as boxes without saying what rules they hold. Chapter 7 makes those boxes real: how firewalls evolved from simple packet filters to stateful and next-generation devices, how to write rules with default-deny and least privilege on the wire, how intrusion detection and prevention systems (IDS/IPS) watch for attacks the firewall lets pass, and how network access control and microsegmentation shrink the trusted zone further still — continuing to fill in the architecture you just designed, and extending netfilter.py to reason about whole rulesets.