Cyber Security Basics 📂 Foundation · 9 of 15 41 min read

How Data Moves Through the Network Stack

A practical, layer-by-layer walkthrough of how a single web request travels from your browser to the physical wire and back — covering encapsulation, the application layer (HTTP/DNS/SSH), the network layer (IP/routing/ICMP/BGP), and the physical layer (copper/fiber/RF). Each section pairs the technical mechanics with the real-world attack techniques and defenses security professionals need to know, from DNS tunneling and BGP hijacking to cable tapping and TEMPEST.

Section 01

The Story That Explains the Entire Network Stack

Sending a Letter Across the World
Imagine you write a letter to a friend overseas. You don't just throw the paper out the window — you put it in an envelope with their name on it, that envelope goes into a mail sack addressed to a city, the sack rides on a truck, then a plane, then another truck, and finally a local postman delivers it. Nobody at the airport reads your letter — they only read the outer addressing. Your friend opens every layer in reverse until they get the raw letter.

That is exactly how a packet travels across the Internet. Your browser writes the "letter" (an HTTP request), and four more layers wrap it in envelopes — port numbers, IP addresses, MAC addresses — until it becomes pure voltage on a wire. This process is called encapsulation, and understanding it is the single most important skill for any cybersecurity professional, because every attack technique targets a specific layer of this journey.

As a Certified Ethical Hacker, I think about networking in exactly this layered way — not because it's academic trivia, but because every exploit, every defense, and every forensic investigation depends on knowing which layer you're operating at. This tutorial walks through the full journey of a single web request — from your browser to the literal copper or fiber that carries it — explaining what happens, why it matters, and how attackers and defenders fight at each stop.

🌲
The Core Insight

Networking is built in layers so that each one only has to solve one problem. The application layer worries about meaning (what does this data say?). The network layer worries about direction (where does it go?). The physical layer worries about energy (how does it actually move?). Once you can place any protocol, device, or attack into one of these layers, the entire field of networking and network security becomes far less mysterious.


Section 02

The OSI Model vs the TCP/IP Model

There are two mental maps used to describe networking: the academic 7-layer OSI model, and the practical 4-layer TCP/IP model that the real Internet actually runs on. You need both — OSI gives you precise vocabulary, TCP/IP tells you how it really works.

OSI LayerNameExample ProtocolsTCP/IP Equivalent
L7ApplicationHTTP, DNS, SMTP, SSHApplication
L6PresentationTLS, JPEG, MIME
L5SessionRPC, sockets, NetBIOS
L4TransportTCP, UDP, QUICTransport
L3NetworkIPv4, IPv6, ICMPInternet
L2Data LinkEthernet, Wi-Fi, ARPLink
L1PhysicalCopper, fiber, RF
💡
Why This Tutorial Skips L5–L6

In practice, the session and presentation layers (L5, L6) are usually folded into the application layer — TLS, for example, is technically L6 but is implemented and discussed as part of "the application stack." This tutorial focuses on the four layers that matter most for hands-on security work: Application, Transport (briefly), Network, and Physical.

Animated Diagram — Data Descending the Stack

⚡ Live Animation — One Request, Five Layers
L7 — Application: HTTP GET /index.html L4 — Transport: TCP segment, port 443 L3 — Network: IP packet, TTL 64 L2 — Data Link: Ethernet frame + MAC L1 — Physical: voltage / light / RF
Watch each layer light up in sequence as one request descends from application data to raw physical signal.

Section 03

Why Layering Matters — And Why Attackers Love It Too

Layering exists so complexity doesn't pile up in one place. But the same separation that makes networking manageable also gives attackers six distinct attack surfaces to choose from — one per layer.

📦
Abstraction
Higher layers don't need to know how packets are physically transmitted. Your browser has no idea if it's running over fiber or Wi-Fi.
🔗
Interoperability
Standardized interfaces let any vendor implement any single layer independently — a Cisco router talks to a Juniper one with no issue.
⚙️
Modularity
Layers can be swapped — the world upgraded from IPv4 to IPv6 without rewriting HTTP, DNS, or any application.
⚠️
Distinct Attack Surfaces
Each layer has its own threats — ARP spoofing at L2, BGP hijacking at L3, XSS at L7. A firewall that protects one layer is blind to the rest.
🛡️
Defense-in-Depth
Controls at one layer can compensate for weaknesses at another — TLS at L7 protects data even if L3 routing is compromised.
🔍
Easier Diagnosis
You can isolate exactly where a problem occurs: ping tests L3, traceroute tests L3 hop-by-hop, curl tests L7.

Section 04

Encapsulation — How Data Gets Wrapped

Encapsulation is the process where each network layer wraps the data unit it receives from the layer above with its own header (and sometimes a trailer) before handing it down. Each layer's wrapped unit has its own name — its Protocol Data Unit (PDU).

LayerPDU Name
Application (L7–L5)Data / Message
Transport (L4)Segment (TCP) / Datagram (UDP)
Network (L3)Packet
Data Link (L2)Frame
Physical (L1)Bits / Symbols
📦 Watch the Data Unit Grow as It Descends
L7-L5
[ payload ] — just the raw HTML, JSON, or text
L4
[ TCP | payload ] — adds source/destination port, sequence, ack
L3
[ IP | TCP | payload ] — adds source/destination IP and TTL
L2
[ ETH | IP | TCP | payload ] — adds source/destination MAC + trailer/CRC
L1
[ 0101...1010 ] — the frame becomes raw electrical, optical, or radio signal

By the time your data reaches L1, what started as 100 bytes of HTTP payload can be 154 bytes on the wire. Every byte of overhead is metadata that routers, switches, firewalls, and attackers all read.

Practical Example — Loading example.com

🎯 Step-by-Step: One HTTP GET Request
1 · L7
Browser builds an HTTP request: GET /index.html HTTP/1.1, Host: example.com
2 · L4
TCP wraps it as a segment: source port 51437, destination port 443, sequence, ack, flags
3 · L3
IP wraps the segment as a packet: source IP 192.168.1.10, destination IP 93.184.216.34, TTL 64
4 · L2
Ethernet wraps it as a frame: source MAC aa:bb:cc:11:22:33, destination MAC (the gateway), type 0x0800
5 · L1
The NIC converts the frame into voltage transitions on twisted-pair copper

Decapsulation — The Reverse Journey at the Receiver

When the packet arrives at its destination, the process runs in reverse — bottom to top. Each layer reads its own header, validates it, strips it off, and hands the rest upward.

⬆️ Unwrapping at the Receiving Server
L1
NIC recovers the frame from electrical/optical/radio signals
L2
Validate CRC checksum, check destination MAC matches, strip the Ethernet header
L3
Check destination IP matches, decrement TTL, strip the IP header
L4
Match the TCP port, reassemble out-of-order segments, strip the TCP header
L7-L5
Hand the raw payload off to the application (the web server)
⚠️
Security Implication — Headers Are Metadata, Not Secrets

Even with TLS encrypting your payload end-to-end, the IP and TCP headers remain plaintext — source/destination IPs, ports, and timing all leak. This is why traffic analysis (without decrypting anything) can still reveal who you're talking to and roughly what you're doing. Attackers also abuse encapsulation itself: tunneling means hiding command-and-control traffic inside DNS queries, HTTPS sessions, or ICMP echo payloads — smuggling malicious data inside what looks like legitimate protocol traffic.

Animated Diagram — Encapsulation in Motion

📦 Live Animation — Headers Wrapping the Payload
ETHERNET HEADER (L2 — MAC src/dst) IP HEADER (L3 — src/dst IP, TTL) TCP HEADER (L4 — src/dst port) HTTP PAYLOAD
Each ring appears outward-in, mirroring how TCP, IP, and Ethernet headers wrap the original payload before it hits the wire.

Section 05

The Application Layer — Where Humans Meet the Network

The application layer is the top of the stack and the one users actually interact with. It defines how programs format messages, request services, authenticate, and transfer payloads — everything from your browser to your email client to your SSH terminal lives here.

🌐
Web
HTTP, HTTPS, WebSocket, QUIC
🔍
Name Lookup
DNS, mDNS, LLMNR
📧
Mail
SMTP, IMAP, POP3
💻
Remote Shell
SSH, Telnet, RDP

Pocket Reference — Protocols, Ports, and Threats

ProtocolPortPurposeSecure VariantCommon Threats
HTTP80Web trafficHTTPS (443)XSS, SQLi, request smuggling
DNS53Name resolutionDoT (853) / DoH (443)Spoofing, tunneling, DDoS
SMTP25/587Email deliverySMTPS / STARTTLSSpoofing, relaying, phishing
IMAP143Email retrievalIMAPS (993)Credential theft, MITM
FTP21File transferSFTP (22) / FTPSCleartext creds, bounce attack
SSH22Remote shellAlways encryptedBrute force, weak keys, MITM
Telnet23Remote shell (legacy)None — DO NOT USECleartext credentials
SNMP161Network managementSNMPv3Default community strings
LDAP389Directory servicesLDAPS (636)Injection, enumeration
RDP3389Remote desktopTLS-wrappedBlueKeep, credential spray

Anatomy of a Real HTTP Request

This is what actually crosses the wire when your browser asks for a page:

GET /search?q=hello HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 ...
Accept: text/html
Accept-Encoding: gzip
Cookie: session=abc123...
Connection: keep-alive
(empty line - end of headers)
🧠 Reading the Request
Request line
Method + path + version — defines exactly what is being asked for
Host header
Mandatory in HTTP/1.1 — enables virtual hosting (many sites, one IP)
User-Agent
Browser fingerprint — useful for analytics, but also a privacy leak
Cookie
Session/auth state — a high-value target for session hijacking

DNS — The Hidden Workhorse Behind Every Web Visit

01
Browser asks the OS resolver
The browser doesn't know how to find example.com — it asks the operating system to resolve the name.
02
OS resolver checks its cache
If the answer is cached locally, it's returned instantly. Otherwise the query is forwarded to a recursive DNS server.
03
Recursive DNS walks the hierarchy
It queries the root servers, then the TLD servers (.com), then the authoritative name server for example.com.
04
Authoritative server answers
It returns the A record: 93.184.216.34.
05
Browser caches the result and connects
The IP is cached locally, and the browser opens a TCP connection directly to that address.
🎯
DNS Hijacking
A compromised resolver redirects users to attacker-controlled IPs instead of the legitimate site.
🔒
DNS Tunneling
Attackers exfiltrate data by hiding it inside subdomain queries — a covert command-and-control channel.
DNSSEC + DoH/DoT
Signing and encrypting DNS traffic defends both the integrity and the privacy of every lookup.
🌐 Live Animation — DNS Resolution Path
YOU RESOLVER ROOT TLD AUTH example.com → 93.184.216.34
The yellow packet walks the resolution chain — resolver, root, TLD, and finally the authoritative server that holds the answer.

Application Layer Security Toolkit

🔐
Transport Encryption
TLS 1.3 for HTTP, IMAP, and SMTP encrypts the payload right at the L7 boundary.
🔐
Authentication
OAuth 2.0, OIDC, SAML, and mTLS verify identity at the application layer, not below it.
Input Validation
Allow-lists, schema validation, and parameterized queries are the SQL injection and XSS killers.
🛡️
Web Application Firewall
L7-aware filtering inspects HTTP headers, parameters, and body content for known attack patterns.
👁
Application Logging
Structured logs of every request feed your SIEM and power anomaly detection.
⏱️
Rate Limiting
Throttling at the API gateway stops brute force, scraping, and credential stuffing before they scale.

Section 06

The Network Layer — How Packets Find Their Way

The network layer (Internet Protocol) has exactly one job: get a packet from any source IP to any destination IP on Earth. It does this through logical addressing, hop-by-hop routing, and fragmentation — handling the messy reality of underlying networks with different maximum packet sizes.

Logical Addressing
IPv4 / IPv6
Hierarchical IP addresses identify hosts globally and enable routing without knowing the physical topology.
Routing
Next-Hop Selection
Each router picks the best next hop toward the destination based on its local routing table.
Fragmentation
Split to Fit MTU
Packets are split into smaller pieces to fit the maximum transmission unit of the underlying link.
Reliability
Not L3's Job
IP is connectionless and best-effort — no delivery guarantee. TCP at L4 handles retransmission.

The IPv4 Header — Every Field Explained

Every router on Earth reads at least 20 bytes of this header on every single packet that crosses it. A few fields matter enormously for security:

FieldWhat It DoesSecurity Relevance
TTLHop count — decremented at every routerSets max hops; exploited by traceroute to map paths
ProtocolIdentifies the next header (6=TCP, 17=UDP, 1=ICMP, 50=ESP)Used by firewalls to filter by transport protocol
Source IPIdentifies the senderOften spoofed in DDoS attacks; needs BCP38 ingress filtering
Fragment fieldsIdentification, flags, fragment offsetAbused in tiny-fragment and overlapping-fragment evasion attacks

Practical Example — How a Packet Hops Across the Internet

A packet typically crosses 10–20 routers between your laptop and a remote server. Each router looks up the destination IP, picks the best next hop, decrements the TTL by one, and forwards the packet — repeating until it's delivered or the TTL hits zero.

HopDeviceTTL
1Your Laptop (192.168.1.10)64
2Home Router (default gateway)63
3ISP Router (AS 7018)62
4Tier-1 Backbone (AS 1299)61
5Server (93.184.216.34)60
💡
Routing Decisions Are Always Local

No router has a "map of the Internet." Each router only knows its directly connected neighbors and the rules it has learned via routing protocols like BGP or OSPF. The Internet works the way it does because thousands of independent, local decisions compose into a global delivery system — there is no central traffic controller.

🔗 Live Animation — Packet Hopping Hop-by-Hop
LAPTOP HOME RTR ISP RTR BACKBONE SERVER TTL=64 TTL=63 TTL=62 TTL=61 TTL=60
TTL decrements by one at every router. If it ever hits zero, the packet is dropped and an ICMP Time Exceeded message is sent back — the exact mechanism traceroute relies on.

ICMP — The Network's Diagnostic Sidekick

ICMP (Internet Control Message Protocol) sits at L3 alongside IP and carries error and informational messages — it's the protocol behind the tools you probably use every day.

TypeNameUsed By
0Echo Replyping response
3Destination UnreachableNetwork/host/port unreachable errors
8Echo Requestping query
11Time ExceededTTL expired — the mechanism traceroute exploits
# Diagnose connectivity with the tools ICMP powers
ping example.com               # is the host alive?
traceroute example.com          # map the path, hop by hop
mtr example.com                 # continuous ping + traceroute with stats
⚠️
ICMP Abuse — Know These Attacks

A Smurf attack spoofs a victim's IP and broadcasts ICMP echo requests, causing every host on the network to flood the victim with replies — a classic amplification DDoS. A Ping of Death sends an oversized ICMP packet to crash legacy network stacks. ICMP tunneling hides command-and-control data inside echo payloads, slipping past firewalls that allow ping traffic by default.

Routing Protocols — How Routers Learn the Map

🔄
RIP
Distance-Vector
Hop-count metric, max 15 hops, runs over UDP port 520. Suitable only for small networks. Easy to spoof — exploited since the 1990s.
🧠
OSPF
Link-State
Builds a full topology map using areas and LSAs, used inside enterprise networks. Supports MD5/SHA-256 authentication — turn it on or it's spoofable.
🌐
BGP
Path-Vector
Glues the entire Internet together between Autonomous Systems via policy-driven routing. BGP hijacking is a global problem — RPKI cryptographically signs route origin announcements as the fix.

Network Layer Threats and Defenses

⚠️ Threats
IP SpoofingForging source IP to impersonate or amplify DDoS
BGP HijackingFalse route announcements redirect global traffic
ICMP TunnelingCovert channels hidden in echo payloads
Fragmentation AttacksTiny/overlapping fragments evade IDS, crash stacks
Routing LoopsMisconfigurations cause black-holes or oscillation
✅ Defenses
Ingress Filtering (BCP38)Block spoofed source IPs at the network edge
RPKI ValidationCryptographically sign route origin announcements
IPsecL3 encryption + integrity (AH, ESP) — the VPN foundation
Stateful L3 FirewallsTrack session state, enforce src/dst/port rules
Reverse Path ForwardingDrop packets arriving on unexpected interfaces

Section 07

The Physical Layer — Bits Become Energy

Everything above this point has been logical — headers, addresses, abstractions. The physical layer is where it all becomes real: voltage changes on copper, light pulses on fiber, or electromagnetic waves through the air. L1 transforms the logical frame built at L2 into physical signals, and defines connectors, pinouts, and timing.

Electrical (Copper)
Twisted pair (Cat 5/6/7) and coaxial cable carry bits as voltage changes. Uses RJ-45/8P8C connectors.
💡
Optical (Fiber)
Single-mode and multi-mode glass carry bits as pulses of light. Uses LC, SC, and ST connectors.
📶
Wireless (Radio)
RF waves through air carry bits for Wi-Fi, cellular, Bluetooth, and satellite — at 2.4/5/6 GHz and mmWave.

Comparing Physical Media

MediumTypical SpeedMax DistanceEMI / Tapping Risk
Cat 5e UTP1 Gbps100 mSusceptible / easy to tap
Cat 6 / 6a10 Gbps55–100 mBetter shielding
Coaxial1 Gbps+500 m+Hard to tap unnoticed
Multimode fiber10–100 Gbps300–550 mImmune to EMI; can leak via bend
Single-mode fiber100 Gbps – 1 Tbps40+ kmImmune to EMI
Wi-Fi 6 / 6Eup to 9.6 Gbps30–50 mBroadcast — eavesdroppable
Submarine fiber100+ Tbps1000s kmPhysical attack vector (cable cut)

Signal Encoding — Turning Bits into Waves

How a bit pattern of 1011 actually looks on the medium:

NRZ
Non-Return-to-Zero
0 = low voltage, 1 = high voltage. Simple, but no clock recovery from the data itself.
🔄
Manchester
Used in 10BASE-T
Every bit period has a transition, embedding clock and data in one signal.
🔗
4B/5B
Used in 100BASE-TX
Maps 4 data bits to 5 line bits to guarantee enough signal transitions.
📊
PAM-4
Used in 200/400G Ethernet
Each symbol carries 2 bits via 4 distinct voltage levels — more data per clock cycle.

Physical Layer Devices

🔌
Network Interface Card
Converts frames to and from signals. Has a MAC address (L2) but speaks pure signal (L1) to the wire.
🔄
Repeater
Regenerates a weakening signal to extend distance. Pure L1 — it never reads or modifies the frame.
⚠️
Hub
A multi-port repeater that broadcasts to every port — obsolete today due to security and collision issues.

Physical Layer Security — When Attackers Get Close

⚠️ Physical Threats
Cable TappingVampire taps on copper; bend-coupling on fiber
ImplantsHardware keyloggers or rogue USB devices dropped into ports
TEMPESTRecovering screen/keyboard data from radio emanations
RF JammingWi-Fi deauth attacks, GPS spoofing, IMSI catchers
Cable CutsSubmarine cable severing; backhoe-driven outages
✅ Defenses
Locked Closets & CagesPhysical access control to wiring closets and racks
Fiber Tamper DetectionOptical Time-Domain Reflectometers (OTDR) detect taps
Faraday ShieldingTEMPEST-rated equipment for classified environments
Port Security / 802.1XAuthenticate devices at the switch port before they connect
CCTV & SensorsDoor sensors and tamper-evident seals on critical hardware
🔒
The First Rule of Physical Security

L1 attacks bypass every higher layer entirely. If an attacker has physical access to your switch, your fiber run, or your server room, your firewall rules, your TLS certificates, and your WAF mean nothing. Physical access is total access. This is why physical security is always rule number one, not an afterthought.


Section 08

Inspecting at the Right Layer — A Defense-in-Depth Practice

A common mistake security teams make is deploying a single control and assuming it covers the whole stack. It doesn't. An L3 firewall cannot read HTTP headers. An L7 WAF cannot see raw TCP flags. Real defense requires multiple inspection points working together.

🛡️ Where Each Defense Lives
1
L7 — Web Application Firewall (WAF). Inspects HTTP method, headers, query parameters, and body for known attack signatures like SQL injection and XSS.
2
L4 — Intrusion Detection System (IDS). Watches TCP flags, port scans, and connection patterns to catch reconnaissance and abnormal session behavior.
3
L3 — Stateful Firewall. Enforces source/destination IP and port rules, and tracks the state of every active connection.
4
L1 — Physical Access Control. Locked racks, badge readers, and cameras protect the layer that, if breached, makes every other control irrelevant.

Section 09

Golden Rules

🎯 How Data Moves — Non-Negotiable Takeaways
1
Data moves by wrapping. Each layer adds a header on the way down (encapsulation) and strips its own header on the way up (decapsulation). Both sides must agree on every header format for communication to work at all.
2
The application layer carries meaning. HTTP, DNS, and SMTP are where humans, programs, and protocols turn raw bytes into intent — and where the richest attack surface lives.
3
The network layer provides direction. IP gets a packet from any host to any other host, hop by hop, on a best-effort basis — with no delivery guarantee.
4
The physical layer is pure energy. Copper voltage, fiber light, and RF waves are what bits ultimately ride on — and physical access there is total access.
5
Every layer is an attack surface. XSS at L7, BGP hijacking at L3, cable tapping at L1 — your defense strategy must span all of them, not just one.
6
Defense in depth actually works. A WAF, a firewall, IPsec, and a locked server room are independent layers whose protections compound — together they are far stronger than any single control alone.