35 min read

> "To understand how to hack something, you must first understand how it works. And nothing in cybersecurity works without the network."

Learning Objectives

  • Explain the OSI and TCP/IP models from an attacker's perspective, identifying attack surfaces at each layer
  • Perform IP addressing, subnetting, and routing analysis to map network topologies during reconnaissance
  • Analyze TCP three-way handshakes, UDP communications, and connection states to understand network behavior
  • Identify and exploit weaknesses in DNS, including cache poisoning, zone transfers, and tunneling
  • Dissect HTTP/HTTPS communications to understand web application attack surfaces
  • Use Wireshark to capture and analyze network traffic for evidence of attacks and vulnerabilities
  • Craft custom packets with Scapy for network reconnaissance and testing

Chapter 6: Networking Fundamentals for Hackers

"To understand how to hack something, you must first understand how it works. And nothing in cybersecurity works without the network." — Georgia Weidman, Penetration Testing: A Hands-On Introduction to Hacking

Chapter Overview

On February 24, 2008, Pakistan Telecom attempted to block YouTube within Pakistan by advertising a more specific BGP route for YouTube's IP address space. Due to a configuration error, this false route leaked beyond Pakistan's borders and propagated across the global internet. For approximately two hours, a significant portion of the world's YouTube traffic was routed to Pakistan Telecom—where it was dropped into a black hole. YouTube was effectively offline for millions of users worldwide.

The Pakistan/YouTube BGP hijack was not the work of a sophisticated attacker. It was a configuration mistake that exploited a fundamental design weakness in the Border Gateway Protocol, one of the internet's oldest and most critical routing protocols. BGP, designed in an era when the internet was a small, trusted network of academics and researchers, has no built-in authentication mechanism. Any network that participates in BGP can announce any route, and other networks will trust and propagate that announcement. This trust-based design, while efficient, makes BGP hijacking trivially easy.

This incident—which we will examine in detail in our first case study—illustrates a principle that is central to everything we will learn in this chapter: the protocols that power the internet were designed for functionality, not security. They were created by engineers who trusted each other, working in an environment where threats were few and the consequences of abuse were minimal. Today, these same protocols carry the world's most sensitive communications, financial transactions, and critical infrastructure operations, and the security weaknesses baked into their design are the foundation on which much of modern hacking rests.

In this chapter, we will systematically examine the networking stack from bottom to top, through the eyes of a hacker. We will not just learn how protocols work—you can get that from any networking textbook. We will learn how they fail, how they can be abused, and how defenders can protect against those abuses. By the end of this chapter, when you look at a network, you will see not just connections and data flows, but attack surfaces and opportunities.


6.1 The OSI and TCP/IP Models: An Attacker's Perspective

6.1.1 Why Models Matter to Hackers

Every aspiring network administrator learns the OSI (Open Systems Interconnection) model and the TCP/IP model. These models describe the layered architecture of network communications, from the physical electrical signals on a wire to the application-level protocols that users interact with. For network engineers, these models are organizational tools—ways of thinking about how different networking technologies relate to each other.

For hackers, these models are something more: they are attack maps. Each layer of the networking stack represents a distinct attack surface with unique vulnerabilities, tools, and techniques. Understanding which layer you are attacking—and which layers are above and below you—is essential for planning effective attacks and understanding their consequences.

6.1.2 The OSI Model Through an Attacker's Lens

The OSI model divides network communication into seven layers:

Layer 1 — Physical Layer

The Physical layer deals with the raw transmission of bits over a physical medium—electrical signals on copper, light pulses on fiber, or radio waves in wireless networks.

Attack surface: Physical attacks include tapping cables, installing hardware implants (such as keystroke loggers or network taps), jamming wireless signals, and exploiting electromagnetic emissions (TEMPEST attacks). Physical security is often the weakest link in an organization's security posture—a point we will explore extensively in later chapters on physical penetration testing.

Attacker techniques: Wiretapping, hardware implants, wireless jamming, evil twin access points, rogue network devices.

Defensive measures: Physical access controls, shielded cabling, wireless intrusion detection, hardware integrity monitoring.

Layer 2 — Data Link Layer

The Data Link layer handles communication between devices on the same local network segment. It uses MAC (Media Access Control) addresses to identify devices and includes protocols like Ethernet, Wi-Fi (802.11), ARP, and VLANs.

Attack surface: Layer 2 attacks are among the most powerful and underappreciated in the hacker's arsenal. Because most network security controls operate at Layer 3 and above, Layer 2 attacks can bypass firewalls, intrusion detection systems, and access control lists.

Attacker techniques: - ARP Spoofing/Poisoning: By sending forged ARP messages, an attacker can associate their MAC address with the IP address of another host (such as the default gateway), causing traffic intended for that host to be sent to the attacker instead. This enables man-in-the-middle attacks. - MAC Flooding: By flooding a switch with frames containing different source MAC addresses, an attacker can overflow the switch's MAC address table, causing it to revert to hub-like behavior and broadcast all traffic to all ports—enabling passive eavesdropping. - VLAN Hopping: By crafting frames with 802.1Q tags, an attacker can potentially access traffic on VLANs they are not authorized to be on. This typically exploits misconfigured trunk ports or the native VLAN. - STP Attacks: By injecting malicious Spanning Tree Protocol (STP) Bridge Protocol Data Units (BPDUs), an attacker can manipulate the network's spanning tree, potentially becoming the root bridge and controlling traffic flow.

Defensive measures: Port security, Dynamic ARP Inspection (DAI), DHCP snooping, BPDU Guard, private VLANs.

🔴 Red Team Perspective: Layer 2 attacks are devastatingly effective in internal penetration tests. Once you have a foothold on the local network (through a compromised host, a rogue device planted during physical testing, or a wireless attack), ARP spoofing alone can give you visibility into traffic that firewalls and IDS systems cannot see. Tools like Ettercap, Bettercap, and arpspoof make these attacks trivially easy to execute.

Layer 3 — Network Layer

The Network layer handles routing packets between different networks. Its primary protocol is IP (Internet Protocol), and it includes routing protocols like BGP, OSPF, and EIGRP, as well as ICMP.

Attack surface: The Network layer is where IP addressing, routing, and fragmentation occur—all of which present attack opportunities.

Attacker techniques: - IP Spoofing: Forging the source IP address of packets to impersonate another host or to hide the attacker's identity. - Route Hijacking (BGP Hijacking): Announcing false routes via BGP to redirect traffic through the attacker's network. - ICMP Attacks: Using ICMP for reconnaissance (ping sweeps, traceroute mapping), denial of service (ping floods, smurf attacks), or covert channels (ICMP tunneling). - IP Fragmentation Attacks: Crafting overlapping or malformed IP fragments to evade IDS/IPS detection or crash vulnerable network stacks.

Defensive measures: Ingress/egress filtering (BCP38), RPKI (Resource Public Key Infrastructure) for BGP, rate limiting ICMP, fragment reassembly enforcement.

Layer 4 — Transport Layer

The Transport layer provides end-to-end communication between applications. Its primary protocols are TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).

Attack surface: The Transport layer's connection management, flow control, and port-based multiplexing create numerous attack opportunities.

Attacker techniques: - Port Scanning: Probing target systems to identify open ports and the services running on them. This is the most fundamental reconnaissance technique in network hacking. - SYN Flooding: Exploiting the TCP three-way handshake by sending a flood of SYN packets without completing the handshake, exhausting the target's connection table. - TCP Session Hijacking: Predicting or observing TCP sequence numbers to inject data into an existing connection. - UDP Amplification: Exploiting UDP-based services (DNS, NTP, memcached) that respond with much larger packets than the request, amplifying denial-of-service attacks.

Defensive measures: SYN cookies, stateful firewalls, rate limiting, TCP sequence number randomization.

Layer 5 — Session Layer

The Session layer manages sessions between applications. In practice, this layer is often merged with the Transport or Application layers in modern implementations.

Attack surface: Session management vulnerabilities, including session fixation, session hijacking, and session replay attacks.

Layer 6 — Presentation Layer

The Presentation layer handles data formatting, encryption, and compression. TLS/SSL encryption operates primarily at this layer.

Attack surface: Cryptographic attacks, including protocol downgrade attacks (forcing the use of weaker encryption), SSL stripping, and exploitation of vulnerabilities in specific TLS implementations (such as Heartbleed, POODLE, and BEAST).

Layer 7 — Application Layer

The Application layer is where users interact with network services. Protocols include HTTP, HTTPS, DNS, SMTP, FTP, SSH, and many others.

Attack surface: Application-layer attacks are the most diverse and numerous category. Web application attacks (SQL injection, cross-site scripting, command injection), email attacks (phishing, header manipulation), DNS attacks (cache poisoning, zone transfers), and many others all operate at this layer.

6.1.3 The TCP/IP Model: A Practical Simplification

While the OSI model provides a useful conceptual framework, the TCP/IP model more accurately reflects the architecture of the internet. The TCP/IP model has four layers:

TCP/IP Layer OSI Equivalent Key Protocols
Network Access Physical + Data Link Ethernet, Wi-Fi, ARP
Internet Network IP, ICMP, BGP, OSPF
Transport Transport TCP, UDP
Application Session + Presentation + Application HTTP, DNS, SMTP, SSH, TLS

For practical purposes, most penetration testers think in terms of the TCP/IP model, occasionally referencing the OSI model for precision when discussing specific attack techniques.

💡 Intuition: Think of the networking stack as a building. Each layer depends on the layers below it. If you can compromise a lower layer (say, Layer 2 with ARP spoofing), you can potentially observe or manipulate everything above it (including Layer 7 application data). This is why Layer 2 attacks are so powerful—they undermine the foundation that all higher-layer security controls rest upon.


6.2 IP Addressing, Subnetting, and Routing

6.2.1 IPv4 Addressing

Every device on a TCP/IP network is identified by an IP address. IPv4 addresses are 32-bit numbers, typically written in dotted-decimal notation (e.g., 192.168.1.100). Understanding IP addressing is essential for network reconnaissance, scope definition, and target identification.

Address Classes (Historical):

The original IPv4 addressing scheme divided addresses into classes:

Class First Octet Range Default Mask Networks Hosts/Network
A 1-126 255.0.0.0 (/8) 126 ~16.7 million
B 128-191 255.255.0.0 (/16) 16,384 ~65,534
C 192-223 255.255.255.0 (/24) ~2.1 million 254

While classful addressing has been superseded by CIDR (Classless Inter-Domain Routing), understanding the old classes helps you quickly identify network sizes and ranges during reconnaissance.

Private (RFC 1918) Address Ranges:

Three address ranges are reserved for private networks and are not routable on the public internet:

  • 10.0.0.0/8 (10.0.0.0 - 10.255.255.255): Class A private range
  • 172.16.0.0/12 (172.16.0.0 - 172.31.255.255): Class B private range
  • 192.168.0.0/16 (192.168.0.0 - 192.168.255.255): Class C private range

For penetration testers, recognizing private addresses is crucial. If you encounter a private address during external testing, it indicates a network misconfiguration that is leaking internal addressing information—a finding worth reporting.

Special Addresses:

  • 127.0.0.0/8: Loopback addresses. 127.0.0.1 (localhost) is the most commonly used.
  • 169.254.0.0/16: Link-local addresses (APIPA). If a host cannot obtain an address via DHCP, it will auto-assign an address in this range. Finding these addresses during a scan indicates DHCP issues.
  • 0.0.0.0: Used as a source address during DHCP bootstrapping or to indicate "any address" in some contexts.
  • 255.255.255.255: Limited broadcast address.

6.2.2 Subnetting for Hackers

Subnetting—dividing a network into smaller segments—is a skill that penetration testers use constantly. You need to understand subnetting to:

  1. Define engagement scope: Your scope document will typically specify IP ranges in CIDR notation. You must be able to determine exactly which addresses are included.
  2. Identify network segments: During reconnaissance, subnetting helps you understand the target's network architecture—where different departments, servers, and security zones are located.
  3. Calculate broadcast addresses: Broadcast addresses are useful for discovery techniques.
  4. Identify potential pivot points: Understanding how subnets are connected helps you plan lateral movement during an engagement.

CIDR Notation: Modern networks use CIDR notation to specify network sizes. The number after the slash indicates the number of bits in the network mask:

CIDR Subnet Mask Hosts Common Use
/32 255.255.255.255 1 Single host
/30 255.255.255.252 2 Point-to-point link
/28 255.255.255.240 14 Small segment
/24 255.255.255.0 254 Typical LAN
/16 255.255.0.0 65,534 Large organization
/8 255.0.0.0 ~16.7M ISP/major enterprise

Subnetting Example: Suppose your scope document specifies 10.50.25.0/27. What addresses are included?

  • A /27 mask means 27 bits for the network, 5 bits for hosts.
  • 2^5 = 32 total addresses, minus 2 (network and broadcast) = 30 usable hosts.
  • Network address: 10.50.25.0
  • First usable: 10.50.25.1
  • Last usable: 10.50.25.30
  • Broadcast: 10.50.25.31

🧪 Try It in Your Lab: In your Student Home Lab from Chapter 3, practice subnetting your virtual network. If your lab network is 192.168.56.0/24, try subdividing it into /28 subnets to separate your attacker machine, your target machines, and your monitoring systems. This replicates the segmented network architecture you will encounter in real engagements.

6.2.3 IPv6 Addressing

IPv6, the successor to IPv4, uses 128-bit addresses written in hexadecimal notation (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334). While IPv4 remains dominant, IPv6 adoption is growing steadily and presents unique security considerations:

Security implications of IPv6:

  • Dual-stack configurations: Many networks run both IPv4 and IPv6 simultaneously. Security controls that only monitor IPv4 traffic can be bypassed by using IPv6. This is a common oversight in corporate networks.
  • Auto-configuration (SLAAC): IPv6 hosts can auto-configure their addresses using Stateless Address Auto-Configuration, which can expose the host's MAC address (and therefore the hardware manufacturer) in the address itself.
  • Larger address space: IPv6's vast address space makes traditional network scanning more difficult (scanning an entire /64 subnet would take millions of years), but also makes certain types of host tracking easier.
  • Extension headers: IPv6 extension headers can be used to evade IDS/IPS systems that do not properly parse the IPv6 header chain.
  • Transition mechanisms: Technologies like 6to4, Teredo, and ISATAP that bridge IPv4 and IPv6 can create unexpected tunnels through security controls.

🔴 Red Team Perspective: IPv6 is frequently a blind spot in security monitoring. During internal penetration tests, try communicating over IPv6 even if the target organization does not think it uses IPv6. Many modern operating systems enable IPv6 by default, and if the security team is only monitoring IPv4, your IPv6 traffic will fly under the radar.

6.2.4 Routing Fundamentals

Routing is the process by which packets find their way from source to destination across interconnected networks. Understanding routing helps penetration testers map network topologies, identify choke points, and plan attack paths.

Key routing concepts:

  • Default Gateway: The router that a host sends packets to when the destination is not on the local network. Compromising or spoofing the default gateway gives an attacker control over the host's outbound traffic.
  • Routing Tables: Each router maintains a table that maps network destinations to next-hop routers or interfaces. Examining a compromised router's routing table reveals the network topology.
  • Static vs. Dynamic Routing: Static routes are manually configured; dynamic routes are learned through routing protocols (OSPF, EIGRP, BGP). Dynamic routing protocols can be attacked to inject false routes.
  • NAT (Network Address Translation): NAT allows multiple hosts on a private network to share a single public IP address. Understanding NAT is important for penetration testers because NAT can complicate certain attack techniques (particularly those that require direct connectivity to internal hosts from outside the network).

6.3 TCP, UDP, and the Three-Way Handshake

6.3.1 TCP: The Reliable Protocol

TCP (Transmission Control Protocol) provides reliable, ordered, and error-checked delivery of data between applications. It is the protocol underlying HTTP, HTTPS, SSH, FTP, SMTP, and many other application-layer protocols.

The Three-Way Handshake:

TCP connections are established through a three-way handshake:

  1. SYN: The client sends a TCP segment with the SYN (Synchronize) flag set, along with an initial sequence number (ISN).
  2. SYN-ACK: The server responds with a segment that has both the SYN and ACK (Acknowledge) flags set, along with its own ISN and an acknowledgment of the client's ISN.
  3. ACK: The client sends a segment with the ACK flag set, acknowledging the server's ISN. The connection is now established.
Client                    Server
  |                         |
  |--- SYN (seq=100) ----->|
  |                         |
  |<-- SYN-ACK (seq=300, --|
  |    ack=101) ------------|
  |                         |
  |--- ACK (seq=101, ----->|
  |    ack=301) ------------|
  |                         |
  |   Connection Established|

Why the Three-Way Handshake Matters to Hackers:

The three-way handshake is the foundation of several critical hacking techniques:

Port Scanning (SYN Scan): The most common port scanning technique, Nmap's SYN scan (-sS), exploits the three-way handshake. The scanner sends a SYN packet to each target port. If the port is open, the target responds with SYN-ACK. The scanner immediately sends a RST (Reset) to tear down the connection without completing the handshake. This is called a "half-open" scan because the connection is never fully established, making it faster and somewhat stealthier than a full connect scan.

Open port:     SYN → SYN-ACK ← RST →
Closed port:   SYN → RST-ACK ←
Filtered port: SYN → (no response)

SYN Flood Attack: A denial-of-service attack that exploits the three-way handshake by sending a flood of SYN packets without completing the handshake. The target allocates resources for each half-open connection and eventually runs out of memory or connection table entries, preventing legitimate connections.

TCP Sequence Prediction: If an attacker can predict the initial sequence number (ISN) that a server will use, the attacker can inject packets into a TCP connection or hijack an existing session. Modern operating systems use randomized ISNs to prevent this attack, but older systems and embedded devices may still be vulnerable.

6.3.2 TCP Flags and States

TCP uses several control flags that are important for penetration testers to understand:

Flag Name Purpose
SYN Synchronize Initiates a connection
ACK Acknowledge Acknowledges received data
FIN Finish Requests connection termination
RST Reset Abruptly terminates a connection
PSH Push Requests immediate delivery of data
URG Urgent Marks data as urgent

Unusual Flag Combinations in Scanning:

Nmap and other scanning tools use non-standard flag combinations to fingerprint operating systems and evade firewalls:

  • NULL scan (-sN): No flags set. Open and filtered ports typically do not respond; closed ports respond with RST.
  • FIN scan (-sF): Only FIN flag set. Similar response pattern to NULL scan.
  • Xmas scan (-sX): FIN, PSH, and URG flags set (the packet is "lit up like a Christmas tree"). Similar response pattern.

These scans work because the TCP specification (RFC 793) states that closed ports should respond to unexpected packets with RST, while open ports should silently drop them. However, not all implementations follow the RFC precisely, so results vary across operating systems.

🔵 Blue Team Perspective: Monitoring for unusual TCP flag combinations is a reliable indicator of scanning activity. Your IDS should be configured to alert on NULL, FIN, and Xmas scans, as well as other anomalous flag combinations. Additionally, an unusual volume of SYN packets to many different ports on a single host is a strong indicator of a port scan.

6.3.3 TCP Connection Termination

TCP connections are terminated through a four-step process (sometimes called the four-way handshake):

  1. The initiating party sends a FIN segment.
  2. The receiving party acknowledges with ACK.
  3. The receiving party sends its own FIN segment.
  4. The initiating party acknowledges with ACK.

Alternatively, either party can send a RST to abruptly terminate the connection. RST is used when something goes wrong—an unexpected packet, an application crash, or (in the case of a SYN scan) a deliberate desire to terminate without completing normal connection procedures.

6.3.4 UDP: The Fast but Unreliable Protocol

UDP (User Datagram Protocol) provides connectionless, unreliable communication. It does not establish connections, does not guarantee delivery, and does not maintain sequence order. Its simplicity makes it faster than TCP, and it is used for applications where speed matters more than reliability: DNS queries, streaming media, VoIP, online gaming, and SNMP.

Why UDP Matters to Hackers:

  • UDP Scanning is Slow and Unreliable: Because UDP does not use a handshake, there is no definitive way to determine whether a UDP port is open. Nmap's UDP scan (-sU) sends a UDP packet to each port; if the port is closed, the target responds with an ICMP Port Unreachable message. If the port is open or filtered, there may be no response at all. This makes UDP scanning much slower and less reliable than TCP scanning.

  • UDP Amplification Attacks: Many UDP-based services respond with much larger packets than the request. An attacker can spoof the source IP address of a UDP request (because there is no handshake to verify the source) and direct the amplified response at a victim. Common amplification vectors include DNS (up to 54x amplification), NTP (up to 556x), memcached (up to 51,000x), and SSDP (up to 30x).

  • UDP-Based Services are Often Overlooked: Because UDP scanning is slow and unreliable, penetration testers sometimes skip it or scan only a limited number of ports. This means that vulnerable UDP services (SNMP, TFTP, NFS) may go undetected.

⚠️ Common Pitfall: Do not skip UDP scanning during penetration tests. While it is slower and noisier than TCP scanning, UDP services often have weaker security controls and can provide easy wins. SNMP with default community strings, open TFTP servers, and vulnerable NTP implementations are common findings on internal networks. At a minimum, scan the top 100 UDP ports.


6.4 DNS and Its Weaknesses

6.4.1 How DNS Works

The Domain Name System (DNS) is one of the internet's most critical protocols. It translates human-readable domain names (like www.shopstack.com) into IP addresses (like 93.184.216.34) that computers use to route traffic. DNS is also used for email routing (MX records), service discovery (SRV records), and text-based information (TXT records, used for SPF, DKIM, and other purposes).

DNS Resolution Process:

When a user types www.shopstack.com into their browser:

  1. The browser checks its local DNS cache.
  2. If not cached, the operating system's resolver checks the system DNS cache.
  3. If not cached, the resolver sends a query to the configured DNS server (typically the ISP's recursive resolver or a public resolver like 8.8.8.8).
  4. The recursive resolver checks its cache. If not cached, it queries the root DNS servers.
  5. The root servers respond with a referral to the .com TLD (Top-Level Domain) servers.
  6. The .com TLD servers respond with a referral to the authoritative DNS servers for shopstack.com.
  7. The authoritative servers respond with the IP address for www.shopstack.com.
  8. The recursive resolver caches the response and returns it to the client.

DNS Record Types Important for Penetration Testing:

Record Type Purpose Security Relevance
A Maps hostname to IPv4 address Target identification
AAAA Maps hostname to IPv6 address IPv6 target discovery
CNAME Alias to another hostname Subdomain takeover potential
MX Mail server for the domain Email attack surface
NS Authoritative name server DNS infrastructure mapping
TXT Arbitrary text data SPF/DKIM/DMARC analysis
SOA Start of Authority Zone information, serial numbers
PTR Reverse DNS (IP to hostname) Infrastructure mapping
SRV Service location Service discovery

6.4.2 DNS Reconnaissance Techniques

DNS is a goldmine for reconnaissance because it provides structural information about a target's infrastructure without requiring any direct interaction with the target's servers:

Zone Transfers (AXFR): A DNS zone transfer is a mechanism for replicating DNS data across authoritative servers. If a DNS server is misconfigured to allow zone transfers to any requester (rather than just authorized secondary servers), an attacker can obtain the complete DNS zone file, revealing every hostname, IP address, and record in the domain.

# Attempting a zone transfer
dig axfr shopstack.com @ns1.shopstack.com

# Using host command
host -t axfr shopstack.com ns1.shopstack.com

Zone transfer misconfigurations are less common than they once were, but they still occur, particularly in internal DNS infrastructures.

DNS Enumeration: Tools like dnsrecon, dnsenum, and fierce can enumerate DNS records, brute-force subdomains, and discover hidden infrastructure:

# Subdomain brute-forcing
dnsrecon -d shopstack.com -t brt -D /usr/share/wordlists/subdomains.txt

# Enumerate all record types
dnsrecon -d shopstack.com -t std

# Fierce for zone transfer and brute-force
fierce --domain shopstack.com

Reverse DNS Lookups: Given an IP address range, reverse DNS lookups can reveal hostnames that may not be documented elsewhere:

# Reverse lookup on a range
dnsrecon -r 10.50.25.0/24

Passive DNS: Services like SecurityTrails, VirusTotal, and PassiveDNS databases collect historical DNS data, allowing you to discover subdomains, IP address changes, and infrastructure relationships without making any queries to the target's DNS servers.

6.4.3 DNS Cache Poisoning

DNS cache poisoning is an attack in which an attacker injects false DNS records into a resolver's cache, causing the resolver to return incorrect IP addresses for legitimate domain names. This can redirect users to malicious servers for phishing, malware distribution, or man-in-the-middle attacks.

The classic DNS cache poisoning attack exploits the fact that DNS queries are sent over UDP (which is connectionless and easily spoofed) and that the only protection against forged responses is a 16-bit transaction ID (which provides only 65,536 possible values—easily brute-forced).

Dan Kaminsky's 2008 discovery, which we will examine in Case Study 2, showed that cache poisoning was far easier than previously believed. Kaminsky demonstrated that by flooding a recursive resolver with queries for random non-existent subdomains of a target domain, an attacker could generate many opportunities to inject forged responses, dramatically increasing the attack's success rate.

DNSSEC (DNS Security Extensions) was designed to prevent cache poisoning by adding cryptographic signatures to DNS records. However, DNSSEC adoption remains incomplete, with only a fraction of domains properly signing their zones and many resolvers not validating signatures.

6.4.4 DNS Tunneling

DNS tunneling is a technique that encodes data within DNS queries and responses to create a covert communication channel. Because DNS traffic is typically allowed through firewalls and is rarely inspected by security tools, DNS tunneling can be used to:

  • Exfiltrate data from a compromised network
  • Establish command-and-control (C2) channels for malware
  • Bypass captive portals in hotels, airports, and other networks that block direct internet access but allow DNS

DNS tunneling tools like iodine, dns2tcp, and dnscat2 can achieve data transfer rates of up to 500 Kbps through DNS alone—not fast enough for streaming video, but more than adequate for command-and-control communications and data exfiltration.

📊 Real-World Application: During a penetration test of MedSecure Health Systems, you discover that the network's firewall blocks all outbound traffic except DNS. This is a common configuration in healthcare environments where strict egress filtering is required by compliance frameworks. DNS tunneling could allow you to demonstrate that an attacker who gains initial access to the internal network could exfiltrate sensitive patient data through the DNS channel—a finding that would be critical for MedSecure's compliance posture.


6.5 HTTP/HTTPS and the Web Stack

6.5.1 HTTP: The Protocol of the Web

HTTP (Hypertext Transfer Protocol) is the protocol that powers the World Wide Web. Understanding HTTP at a deep level is essential for web application penetration testing, which is one of the most common and in-demand areas of security testing.

HTTP Request Structure:

An HTTP request consists of:

GET /api/users/123 HTTP/1.1
Host: www.shopstack.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: application/json
Cookie: session=abc123def456
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
  • Method: GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, etc.
  • URI: The resource being requested
  • Headers: Metadata about the request
  • Body: (For POST/PUT) The data being sent

HTTP Response Structure:

HTTP/1.1 200 OK
Content-Type: application/json
Set-Cookie: session=xyz789; HttpOnly; Secure
X-Frame-Options: DENY
Content-Security-Policy: default-src 'self'

{"id": 123, "name": "John Doe", "email": "john@example.com"}
  • Status Code: 200 (OK), 301 (Redirect), 403 (Forbidden), 404 (Not Found), 500 (Server Error), etc.
  • Headers: Metadata about the response, including security headers
  • Body: The response data

6.5.2 HTTP Methods and Their Attack Surfaces

Each HTTP method presents different security considerations:

GET: Should be used only for retrieval. If a GET request causes state changes (such as deleting a record), this creates CSRF (Cross-Site Request Forgery) vulnerabilities.

POST: Used for submitting data. POST requests are the primary target for injection attacks (SQL injection, command injection, XSS).

PUT/PATCH: Used for updating resources. If improperly authorized, these methods can allow unauthorized data modification.

DELETE: Used for deleting resources. If improperly authorized, this can lead to data destruction.

OPTIONS: Returns the methods supported by a resource. Can reveal information about the server's configuration and capabilities.

TRACE: Echoes the request back to the client. Can be exploited for Cross-Site Tracing (XST) attacks.

HEAD: Returns headers only (no body). Useful for reconnaissance because it reveals server information without downloading full responses.

6.5.3 Security Headers

HTTP response headers play a critical role in web application security. During penetration testing, analyzing security headers is one of the first steps in web application assessment:

Header Purpose Misconfiguration Risk
Content-Security-Policy Controls which resources can be loaded XSS if too permissive
X-Frame-Options Prevents clickjacking Clickjacking if missing
Strict-Transport-Security Enforces HTTPS MITM if missing
X-Content-Type-Options Prevents MIME type sniffing MIME confusion attacks
X-XSS-Protection Browser XSS filter XSS if disabled
Referrer-Policy Controls referrer information Information leakage
Permissions-Policy Controls browser features Feature abuse

6.5.4 HTTPS and TLS

HTTPS is HTTP over TLS (Transport Layer Security). TLS provides encryption, integrity, and authentication for HTTP communications. Understanding TLS is essential for penetration testers because:

TLS Versions and Cipher Suites: Not all TLS configurations are equally secure. SSLv2, SSLv3, TLS 1.0, and TLS 1.1 are all deprecated and have known vulnerabilities. TLS 1.2 is secure when configured with strong cipher suites, and TLS 1.3 is the current standard. Testing a server's TLS configuration is a standard part of web application penetration testing.

# Testing TLS configuration with testssl.sh
testssl.sh https://www.shopstack.com

# Nmap NSE script for SSL enumeration
nmap --script ssl-enum-ciphers -p 443 www.shopstack.com

Certificate Validation: TLS certificates authenticate the server's identity. Misconfigured certificates—expired certificates, self-signed certificates, certificates with incorrect hostnames, or certificates signed by untrusted CAs—can indicate security weaknesses.

TLS Attacks: - SSL Stripping: Intercepting an HTTP-to-HTTPS redirect and keeping the connection on HTTP, enabling eavesdropping. HSTS (HTTP Strict Transport Security) mitigates this. - Heartbleed (CVE-2014-0160): A buffer over-read vulnerability in OpenSSL that allowed attackers to read up to 64KB of the server's memory per request, potentially exposing private keys, session tokens, and other sensitive data. We will examine Heartbleed in detail in Case Study 2. - POODLE, BEAST, CRIME, BREACH: Various attacks on older TLS versions and compression features.

🔴 Red Team Perspective: During internal penetration tests, SSL stripping combined with ARP spoofing is a powerful technique. Use tools like Bettercap to ARP-spoof the target's gateway, intercept HTTP-to-HTTPS redirects, and serve the site over plain HTTP. Users who do not notice the missing padlock icon will submit credentials in cleartext. This technique demonstrates the importance of HSTS preloading and user security awareness.


6.6 Common Protocols and Their Attack Surfaces

6.6.1 ARP (Address Resolution Protocol)

ARP maps IP addresses to MAC addresses on local networks. It operates at Layer 2 and has no authentication mechanism—any device on the network can respond to ARP requests or send unsolicited ARP replies.

ARP Spoofing/Poisoning: By sending forged ARP replies, an attacker can associate their MAC address with the IP address of another device (such as the default gateway), causing traffic intended for that device to be sent to the attacker. This enables man-in-the-middle attacks on the local network.

Normal: Host A → (ARP: Who has 10.0.0.1?) → Gateway responds with its MAC
Attack: Attacker → (ARP: 10.0.0.1 is at [attacker's MAC]) → Host A now sends
        traffic to attacker instead of gateway

Tools: arpspoof, Ettercap, Bettercap, Cain & Abel

Defenses: Dynamic ARP Inspection (DAI), static ARP entries, 802.1X port-based authentication

6.6.2 DHCP (Dynamic Host Configuration Protocol)

DHCP automatically assigns IP addresses and network configuration to devices. It operates over UDP (ports 67 and 68) and has minimal authentication.

DHCP Attacks: - Rogue DHCP Server: An attacker sets up a fake DHCP server that provides clients with a malicious DNS server or default gateway, enabling man-in-the-middle attacks. - DHCP Starvation: An attacker exhausts the DHCP server's address pool by requesting all available addresses, causing a denial of service for legitimate clients.

Defenses: DHCP snooping, port security, 802.1X

6.6.3 SMTP (Simple Mail Transfer Protocol)

SMTP is the protocol for sending email. It operates on port 25 (unencrypted) or port 587 (submission with TLS). SMTP's trust-based design makes it vulnerable to:

  • Email Spoofing: SMTP does not inherently verify the sender's identity. Without SPF, DKIM, and DMARC, anyone can send email that appears to come from any address. This is the foundation of phishing attacks.
  • Open Relays: SMTP servers that relay email for any sender (not just authenticated users) can be used for spam and phishing.
  • Credential Harvesting: SMTP authentication credentials can be captured if the connection is not encrypted.

6.6.4 SMB (Server Message Block)

SMB is the protocol used for file sharing in Windows environments. It operates on ports 445 (direct) and 139 (over NetBIOS).

SMB Attack Surface: - EternalBlue (CVE-2017-0144): The vulnerability exploited by WannaCry and NotPetya. This SMBv1 vulnerability allowed remote code execution and was one of the most devastating exploits in history. - SMB Relay Attacks: An attacker intercepts SMB authentication traffic and relays it to another server to gain unauthorized access. - Null Sessions: Anonymous connections to SMB shares that may expose user lists, share names, and other sensitive information. - Share Enumeration: Discovering accessible SMB shares on the network, which may contain sensitive data.

6.6.5 SSH (Secure Shell)

SSH provides encrypted remote access and is considered one of the more secure protocols in common use. However, it is not immune to attack:

  • Brute Force: Weak passwords on SSH services can be cracked with tools like Hydra and Medusa.
  • Key Management: Poorly managed SSH keys (keys without passphrases, keys that are not rotated, keys shared across multiple systems) create security risks.
  • Version Vulnerabilities: Older versions of SSH implementations may have known vulnerabilities.

6.6.6 SNMP (Simple Network Management Protocol)

SNMP is used for monitoring and managing network devices. SNMPv1 and SNMPv2c use community strings (essentially passwords) transmitted in cleartext. Many devices ship with default community strings ("public" for read-only, "private" for read-write) that administrators fail to change.

SNMP Attacks: - Community String Guessing: Testing for default or weak community strings. - Information Disclosure: SNMP can expose system information, network configuration, and even credentials. - Configuration Modification: With read-write access (the "private" community string), an attacker can modify device configurations.

📊 Real-World Application: During an internal penetration test of ShopStack's office network, you discover multiple network printers and switches responding to SNMP queries with the default "public" community string. SNMP enumeration reveals detailed network topology information, including IP addresses, routing tables, and connected device information. This finding, while seemingly minor, provides a comprehensive map of ShopStack's internal network—invaluable for planning further attacks.


6.7 Wireshark: Packet Analysis in Practice

6.7.1 Introduction to Wireshark

Wireshark is the world's most widely used network protocol analyzer. It captures packets from network interfaces and provides a rich graphical interface for analyzing them. For penetration testers, Wireshark is an indispensable tool for:

  • Analyzing captured traffic during man-in-the-middle attacks
  • Understanding protocol behavior during exploitation
  • Troubleshooting network issues during testing
  • Extracting credentials from unencrypted protocols
  • Validating findings and documenting evidence

6.7.2 Capture Filters vs. Display Filters

Wireshark uses two types of filters:

Capture Filters (Berkeley Packet Filter syntax) determine which packets are captured:

# Capture only traffic to/from a specific host
host 192.168.1.100

# Capture only TCP traffic on port 80
tcp port 80

# Capture traffic on a specific subnet
net 10.0.0.0/24

# Capture only DNS traffic
port 53

Display Filters (Wireshark's own syntax) determine which captured packets are shown:

# Show only HTTP traffic
http

# Show packets to/from a specific IP
ip.addr == 192.168.1.100

# Show only TCP SYN packets (port scan detection)
tcp.flags.syn == 1 && tcp.flags.ack == 0

# Show DNS queries
dns.flags.response == 0

# Show HTTP POST requests
http.request.method == "POST"

# Show packets containing a specific string
frame contains "password"

# Show failed TCP connections (RST)
tcp.flags.reset == 1

# Show TLS handshake packets
tls.handshake.type == 1

6.7.3 Analyzing Common Attack Patterns

Wireshark can reveal attack patterns in captured traffic:

Detecting Port Scans: - Look for a single source IP sending SYN packets to many different ports on a single destination. - Filter: tcp.flags.syn == 1 && tcp.flags.ack == 0 - A rapid succession of SYN packets to sequential or random ports is a clear indicator of scanning.

Detecting ARP Spoofing: - Look for ARP replies that were not preceded by ARP requests (gratuitous ARP). - Look for multiple IP addresses being mapped to the same MAC address. - Filter: arp.opcode == 2 (ARP replies)

Extracting Credentials: - HTTP Basic Authentication transmits credentials in Base64 encoding (easily decoded). - Filter: http.authorization - FTP credentials are transmitted in plaintext. - Filter: ftp.request.command == "USER" || ftp.request.command == "PASS"

Following TCP Streams: - Right-click on any packet in a TCP connection and select "Follow > TCP Stream" to see the complete conversation, reconstructed from individual packets. This is invaluable for understanding HTTP transactions, reading email conversations, or extracting files transferred over unencrypted protocols.

6.7.4 tshark: Command-Line Packet Analysis

tshark is Wireshark's command-line companion, useful for scripting and automated analysis:

# Capture 100 packets on interface eth0
tshark -i eth0 -c 100

# Capture to a file
tshark -i eth0 -w capture.pcap

# Read a capture file and display HTTP requests
tshark -r capture.pcap -Y "http.request" -T fields -e http.host -e http.request.uri

# Extract credentials from HTTP POST requests
tshark -r capture.pcap -Y "http.request.method == POST" -T fields -e http.file_data

🧪 Try It in Your Lab: Set up your Student Home Lab with a Kali Linux machine and a target web server (DVWA or WebGoat from Chapter 3). Open Wireshark on the Kali machine and capture traffic while you browse the web application, log in, and submit forms. Practice using display filters to isolate specific types of traffic. Try to extract the login credentials from the captured traffic. This exercise builds practical packet analysis skills that you will use throughout your career.


6.8 Scapy: Crafting Packets from Scratch

6.8.1 What Is Scapy?

Scapy is a powerful Python-based packet manipulation library and tool. Unlike Wireshark, which is primarily a passive analysis tool, Scapy allows you to create, send, receive, and analyze network packets with complete control over every field at every layer.

For penetration testers, Scapy is valuable for:

  • Custom scanning: Creating scanning techniques that go beyond what Nmap offers
  • Protocol fuzzing: Generating malformed packets to test how systems respond
  • Attack simulation: Crafting ARP spoofing, DNS poisoning, and other attack packets
  • Tool development: Building custom network tools for specific testing scenarios

6.8.2 Basic Scapy Usage

from scapy.all import *

# Create an IP packet
ip = IP(dst="192.168.1.1")

# Create a TCP SYN packet
tcp = TCP(dport=80, flags="S")

# Combine layers
packet = ip/tcp

# Send and receive
response = sr1(packet, timeout=2)

# Examine the response
if response:
    response.show()

6.8.3 Common Scapy Operations for Penetration Testing

SYN Scan:

from scapy.all import *

target = "192.168.1.100"
ports = [21, 22, 23, 25, 53, 80, 443, 445, 3389, 8080]

for port in ports:
    response = sr1(IP(dst=target)/TCP(dport=port, flags="S"),
                   timeout=1, verbose=0)
    if response and response.haslayer(TCP):
        if response[TCP].flags == "SA":  # SYN-ACK = open
            print(f"Port {port}: OPEN")
            # Send RST to close
            sr1(IP(dst=target)/TCP(dport=port, flags="R"),
                timeout=1, verbose=0)

ARP Discovery:

from scapy.all import *

# Discover hosts on the local network
ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168.1.0/24"),
                 timeout=2, verbose=0)

for sent, received in ans:
    print(f"{received.psrc} is at {received.hwsrc}")

DNS Query:

from scapy.all import *

# Send a DNS query
dns_query = IP(dst="8.8.8.8")/UDP(dport=53)/DNS(
    rd=1, qd=DNSQR(qname="shopstack.com"))

response = sr1(dns_query, timeout=2, verbose=0)

if response and response.haslayer(DNS):
    for i in range(response[DNS].ancount):
        print(f"Answer: {response[DNS].an[i].rdata}")

⚖️ Legal Note: Scapy gives you the ability to craft arbitrary packets and send them to any network destination. This power comes with significant legal responsibility. Never use Scapy (or any packet crafting tool) against systems you are not authorized to test. Even in your home lab, be careful with broadcast and multicast packets that could affect your home network. Always use Scapy within the scope of your authorized testing activities.

6.8.4 Scapy for Protocol Analysis

Beyond crafting packets, Scapy is excellent for analyzing captured traffic:

from scapy.all import *

# Read a pcap file
packets = rdpcap("capture.pcap")

# Analyze packet statistics
print(f"Total packets: {len(packets)}")

# Filter for specific traffic
http_packets = [p for p in packets if p.haslayer(TCP) and
                (p[TCP].dport == 80 or p[TCP].sport == 80)]
print(f"HTTP packets: {len(http_packets)}")

# Extract unique source IPs
src_ips = set(p[IP].src for p in packets if p.haslayer(IP))
print(f"Unique source IPs: {src_ips}")

6.9 Putting It All Together: Network Reconnaissance Workflow

To conclude this chapter, let us walk through a network reconnaissance workflow that integrates the concepts and tools we have discussed. This workflow applies to the initial reconnaissance phase of a penetration test, where you are mapping the target's network infrastructure.

6.9.1 Phase 1: Passive DNS Reconnaissance

Before sending a single packet to the target, gather as much information as possible from public sources:

  1. DNS record enumeration: Query all DNS record types for the target domain.
  2. Subdomain discovery: Use passive DNS databases, certificate transparency logs, and search engines to discover subdomains.
  3. Reverse DNS lookups: Identify hostnames associated with the target's IP address ranges.
  4. Historical DNS data: Use SecurityTrails or similar services to identify previous IP addresses and hosting changes.

6.9.2 Phase 2: Active Network Scanning

With authorization, begin active scanning to map the target's network:

  1. Host discovery: Use ARP scanning (on local networks) or ICMP/TCP scanning (on remote networks) to identify live hosts.
  2. Port scanning: Conduct SYN scans of TCP ports and UDP scans of common UDP ports.
  3. Service identification: Use Nmap's version detection (-sV) to identify the software running on open ports.
  4. OS fingerprinting: Use Nmap's OS detection (-O) to identify operating systems.

6.9.3 Phase 3: Protocol Analysis

For each discovered service, analyze the protocol in detail:

  1. TLS configuration: Test HTTPS services for weak cipher suites, expired certificates, and TLS vulnerabilities.
  2. HTTP header analysis: Check for missing or misconfigured security headers.
  3. SNMP testing: Test for default community strings and information disclosure.
  4. SMB enumeration: Test for null sessions, open shares, and vulnerable SMB versions.
  5. DNS zone transfers: Attempt zone transfers on discovered DNS servers.

6.9.4 Phase 4: Traffic Analysis

If you have access to the local network (during an internal test or after gaining a foothold):

  1. Passive capture: Run Wireshark or tcpdump to capture traffic and identify unencrypted protocols.
  2. ARP analysis: Monitor ARP traffic for existing poisoning or anomalies.
  3. DHCP analysis: Observe DHCP traffic to understand network configuration.
  4. Broadcast traffic: Analyze broadcast and multicast traffic for service discovery.

🔗 Connection: This reconnaissance workflow is the technical implementation of the reconnaissance phase we described in Chapter 2's penetration testing lifecycle. In subsequent chapters, we will build on these networking fundamentals to explore specific attack techniques: web application attacks (using our understanding of HTTP), network attacks (using our understanding of TCP/IP and ARP), and wireless attacks (using our understanding of 802.11 and the Physical/Data Link layers).


Chapter Summary

In this chapter, we have built the networking foundation that underpins everything in ethical hacking:

  1. The OSI and TCP/IP models provide a framework for understanding network communication and identifying attack surfaces at each layer. Lower-layer attacks (Layer 2 ARP spoofing) can undermine all security above them.

  2. IP addressing and subnetting are essential skills for scope definition, network mapping, and target identification. IPv6 introduces new attack surfaces and defensive blind spots.

  3. TCP and UDP are the transport protocols that carry all network applications. The TCP three-way handshake is the foundation for port scanning and SYN flood attacks. UDP's connectionless nature enables amplification attacks and makes scanning more difficult.

  4. DNS is both an invaluable reconnaissance tool and a target-rich attack surface. Zone transfers, cache poisoning, and DNS tunneling are fundamental techniques in the ethical hacker's arsenal.

  5. HTTP/HTTPS form the foundation of web application security. Understanding HTTP methods, headers, status codes, and TLS is essential for web application penetration testing.

  6. Common protocols like ARP, DHCP, SMTP, SMB, SSH, and SNMP each have unique attack surfaces that must be understood and tested.

  7. Wireshark and Scapy are essential tools for packet analysis and packet crafting, enabling both passive observation and active testing of network protocols.

The key insight of this chapter is that network protocols are the language of hacking. Every exploit, every attack, every reconnaissance technique is ultimately a conversation between computers, conducted in the language of network protocols. The better you understand these protocols—not just how they work, but how they fail—the more effective you will be as an ethical hacker.


What's Next

With networking fundamentals firmly in hand, we move in Chapter 7 to the first major offensive discipline: reconnaissance and information gathering. We will take the DNS, HTTP, and network scanning techniques introduced in this chapter and combine them with OSINT (Open Source Intelligence) methodologies to build comprehensive profiles of target organizations. You will learn to think like an adversary conducting initial reconnaissance—mapping the target's digital footprint before a single exploit is fired.