Learning Goals
3 minBy the end of this lesson you can:
- Name the seven OSI layers and what each does.
- Map a given attack or defence to the right layer.
- Relate OSI to the simpler TCP/IP model you already use.
- Identify which layer your Python network code operates at.
Warm-Up · Why Layers?
5 minWhen something breaks on a network, the first question is "at which layer?" A cut cable, a wrong IP, a closed port, and a bad TLS certificate are completely different problems — and the OSI model gives everyone the same vocabulary to pinpoint which.
The OSI model splits a network connection into seven layers, each building on the one below. Data is encapsulated going down (each layer wraps it in a header) and unwrapped going up. Security matters because attacks target specific layers — and so do defences. Knowing the layer tells you the tool: a firewall (L3/4), a WAF (L7), TLS (L4/presentation), a switch config (L2).
New Concept · The Seven Layers, Each With a Threat
14 minTop to bottom (a mnemonic: "All People Seem To Need Data Processing")
L7 Application what the user/app sees: HTTP, DNS, SMTP, your requests call attack: SQLi, XSS, malicious HTTP defence: WAF, input validation L6 Presentation encoding, encryption, compression: TLS, JSON, images attack: weak ciphers, downgrade defence: strong TLS config L5 Session conversations: setup/teardown, auth sessions attack: session hijacking defence: secure session tokens L4 Transport reliable delivery: TCP, UDP, ports attack: SYN flood, port scan defence: firewall, rate limit L3 Network routing across networks: IP, ICMP (ping) attack: IP spoofing, routing attacks defence: filtering, ingress checks L2 Data Link local network: MAC addresses, switches, ARP, wifi attack: ARP spoofing, MAC flooding defence: switch security, 802.1X L1 Physical cables, radio, electrical signals attack: cut cable, tapping, jamming defence: physical security
How data flows through the layers
Your code: requests.get("https://...") ← Layer 7
L7 adds HTTP headers
L6 TLS-encrypts the data
L4 wraps in a TCP segment (+ ports)
L3 wraps in an IP packet (+ addresses)
L2 wraps in a frame (+ MAC addresses)
L1 sends as bits on the wire ───────► ... server reverses the processEach layer adds its own header (encapsulation) and only talks to the same layer on the other side. Your requests call is pure Layer 7 — but it rides on all six below it, and a weakness anywhere can compromise it.
OSI vs. TCP/IP (the practical model)
OSI (7 layers, theory) TCP/IP (4 layers, real-world) L7 Application ┐ L6 Presentation │──────────► Application (HTTP, TLS, DNS) L5 Session ┘ L4 Transport ──────────► Transport (TCP, UDP) L3 Network ──────────► Internet (IP) L2 Data Link ┐ L1 Physical ┘──────────► Link (Ethernet, wifi)
TCP/IP is what the internet actually runs; OSI is the richer teaching/diagnostic model. Security folk use both — "a Layer 7 attack" and "an application-layer attack" mean the same thing.
Why this matters for defence
The layer tells you the right control. A firewall blocks by IP/port (L3/L4). A Web Application Firewall inspects HTTP (L7). TLS protects confidentiality/integrity (L6, riding on L4). You can't stop SQL injection with a network firewall — it's a Layer 7 problem needing a Layer 7 fix (parameterised queries). Match the defence to the layer.
Worked Example · Trace a Request & Classify Attacks by Layer
12 minFirst, a classifier that places common attacks at their OSI layer — drilling the "which layer?" reflex that makes you fast at diagnosis.
OSI_LAYER = { "SQL injection": (7, "Application", "input validation / params"), "Cross-site scripting":(7, "Application", "output encoding / CSP"), "Weak TLS cipher": (6, "Presentation", "strong TLS config"), "Session hijacking": (5, "Session", "secure, rotated session tokens"), "SYN flood (DoS)": (4, "Transport", "rate limiting / SYN cookies"), "Port scan": (4, "Transport", "firewall / IDS"), "IP spoofing": (3, "Network", "ingress filtering"), "ARP spoofing": (2, "Data Link", "dynamic ARP inspection"), "Cable tap": (1, "Physical", "physical access control"), } for attack, (num, name, defence) in sorted(OSI_LAYER.items(), key=lambda kv: -kv[1][0]): print(f"L{num} {name:13} {attack:22} → {defence}")
L7 Application SQL injection → input validation / params L7 Application Cross-site scripting → output encoding / CSP L6 Presentation Weak TLS cipher → strong TLS config L5 Session Session hijacking → secure, rotated session tokens L4 Transport SYN flood (DoS) → rate limiting / SYN cookies L4 Transport Port scan → firewall / IDS L3 Network IP spoofing → ingress filtering L2 Data Link ARP spoofing → dynamic ARP inspection L1 Physical Cable tap → physical access control
See your own code's layer
import socket # A raw socket connection exposes L4 (TCP) + L3 (IP) directly: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # SOCK_STREAM = TCP = L4 s.settimeout(1) s.connect(("127.0.0.1", 3000)) # L3 IP + L4 port peer = s.getpeername() # the (IP, port) we reached — L3/L4 local = s.getsockname() # our own (IP, port) print("L3/L4 connection:", local, "→", peer) # requests.get(...) would sit at L7, riding on this same TCP/IP plumbing.
Read the result
The classifier shows why "defence in depth" is layered: SQLi can't be fixed by a firewall and a port scan can't be fixed by input validation — each layer needs its own control. The socket example makes it concrete: SOCK_STREAM is you working directly at Layer 4 (TCP) over Layer 3 (IP), while a requests.get adds Layer 7 (HTTP) and Layer 6 (TLS) on top. When you debug or defend, naming the layer is half the solution.
Try It Yourself
13 minFor each, name the OSI layer: a DNS lookup, a TCP retransmission, an HTTPS certificate error, a ping (ICMP), a wifi password, a malicious JavaScript payload.
Check
DNS lookup → L7 (app); TCP retransmission → L4; cert error → L6 (presentation); ping/ICMP → L3 (network); wifi password → L2 (data link); malicious JS → L7.
Given the defences {firewall, WAF, TLS, physical locks, ARP inspection}, assign each to its primary OSI layer and explain in one line why it can't stop attacks at a different layer.
Write diagnose(symptom) that takes a plain-English network symptom and returns the likely layer and what to check. E.g. "page loads over http but not https" → L6 (TLS/cert); "can ping the server but the port refuses" → L4 (service down/firewalled).
Hint
RULES = { "no link light / dead cable": (1, "check the physical connection"), "can't reach other devices on LAN": (2, "ARP/switch/wifi issue"), "ping fails, wrong subnet": (3, "IP/routing config"), "ping works but port refuses": (4, "service down or firewalled"), "https fails, http works": (6, "TLS/certificate problem"), "page loads but shows an error from the app": (7, "application bug"), } def diagnose(symptom): layer, advice = RULES.get(symptom, (None, "narrow it down layer by layer")) print(f"likely L{layer}: {advice}" if layer else advice)
Mini-Challenge · The Defence-in-Depth Diagram
8 minPick a real system (a banking website, say) and build a "defence in depth" table: for each OSI layer, list one realistic attack and the control that defends that layer. The point: no single layer is enough — security is stacked. Output it as a tidy printed table.
Show a sample solution
DEPTH = [ (7, "App", "SQLi / XSS", "input validation, WAF, CSP"), (6, "Present.", "weak/old TLS", "TLS 1.3 only, strong ciphers"), (5, "Session", "session hijack", "HttpOnly+Secure cookies, rotation"), (4, "Transport","SYN flood, scan", "firewall, rate limit, SYN cookies"), (3, "Network", "IP spoof, DDoS", "ingress filtering, scrubbing"), (2, "Data Link","ARP spoof (LAN)", "dynamic ARP inspection, 802.1X"), (1, "Physical", "tap / theft", "locked racks, CCTV, access control"), ] print(f"{'L':2} {'layer':9} {'attack':18} defence") for n, layer, attack, defence in DEPTH: print(f"{n:<2} {layer:9} {attack:18} {defence}") print("\nNo single row is enough — that's why it's called depth.")
Non-negotiables: all seven layers, a realistic attack and matching control per layer, and the "no single layer suffices" point.
Recap
3 minThe OSI model has seven layers — Physical, Data Link, Network, Transport, Session, Presentation, Application — each building on the one below, with data encapsulated going down and unwrapped going up. Its security value is precision: attacks and defences live at specific layers, so naming the layer tells you the right control (firewall at L3/4, WAF/validation at L7, TLS at L6). The simpler TCP/IP four-layer model is what the internet runs; OSI is the diagnostic map. Your requests call is Layer 7 riding on everything beneath it — and defence in depth means securing every layer, not just one.
Vocabulary Card
- OSI model
- A seven-layer reference model for how network communication is structured.
- encapsulation
- Each layer wrapping data in its own header as it descends the stack.
- Layer 7 / Layer 4
- Application (HTTP) / Transport (TCP, ports) — common shorthand.
- defence in depth
- Layered controls so no single failure compromises the system.
Homework
4 minTrace one real interaction end to end — e.g. typing https://example.com and hitting Enter — and write what happens at each OSI layer, plus one thing that could go wrong (and its defence) at each. Then build your diagnose tool and test it on five symptoms.
Sample · loading https://example.com by layer
L7 App: browser builds an HTTP GET; (DNS resolves the name first).
risk: malicious/compromised site → defence: validation, CSP.
L6 Present: TLS handshake encrypts the session.
risk: weak cipher/expired cert → defence: TLS 1.3, valid cert.
L5 Session: keeps the TLS/HTTP conversation state.
risk: hijacked session → defence: secure tokens.
L4 Transport: TCP handshake to port 443.
risk: SYN flood → defence: rate limit / SYN cookies.
L3 Network: IP routes packets across the internet.
risk: spoofing/DDoS → defence: ingress filtering.
L2 Data Link: frames cross my wifi to the router.
risk: ARP spoof on the LAN → defence: ARP inspection.
L1 Physical: bits over wifi radio / fibre.
risk: tap/jam → defence: physical & RF security.Non-negotiables: all seven layers with a concrete event, risk, and defence each — and a working diagnose tool.