These are the notes for Cybersecurity Fundamentals (defensive), episode 24. Last time, every defence was a filter. Today we invent, one problem at a time, the most famous filter of all and the way to split a network into rooms: the firewall, its rules and access control lists (ACLs), first match, denylists vs allowlists and default deny, the packet filter, stateful inspection and the connection table, the next-generation firewall (NGFW), the host-based firewall, ingress and egress filtering, zones, the DMZ, VLANs, network segmentation and microsegmentation, the bastion host and the jump box, and the firewall rule review that finds any-any rules, expired rules and shadowed rules. Every term is explained the first time it appears, and the Glossary at the end defines them all again.
Ravi's shops, every host, address and rule are made up. Addresses are private (RFC 1918, like 10.0.0.5) or documentation-only (RFC 5737, like 192.0.2.10, 198.51.100.66, 203.0.113.66), and names like updates.example use a reserved example domain. All filters are toy simulations in plain Python: no packets are sent and no real network is touched. Every code sample runs with Python 3.13 using only the standard library; outputs are real, copied from actual runs.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| One hacked laptop reaches everything | Flat network, blast radius, firewall, rule, ACL |
| Blocking "known bad" isn't enough | Denylist vs allowlist, default deny, first match |
| Letting replies back in | Stateless packet filter, source port, stateful inspection, connection table, NGFW, host-based firewall |
| Malware phones home | Egress filtering, ingress filtering, command and control, anti-spoofing (BCP 38) |
| Walls between zones | Zone, DMZ, VLAN, network segmentation, microsegmentation |
| Admins need a way in, and rules rot | Bastion host, jump box, firewall rule review, any-any rule, shadowed rule, hit count |
Problem 1: one flat network
Ravi runs a chain of shops. He hires a refrigeration contractor who watches the shop fridges' temperatures over the network, through an HVAC panel (HVAC = heating, ventilation and air conditioning: the box that controls the building's climate and fridges). To do that, the contractor gets a login to Ravi's network.
Then the contractor's laptop is hacked, and its login (its credentials: username and password) is stolen. Vendors are part of your attack surface: anyone you give access to is a way in for whoever hacks them.
This really happened. Computerworld (6 Feb 2014) reported that in the 2013 Target breach, attackers first got into Target's network on 15 Nov 2013 with credentials stolen from Fazio Mechanical Services, an HVAC contractor. Malware on the point-of-sale (POS) systems (the tills where cards are swiped) then took data on about 40 million cards between 27 Nov and 15 Dec 2013. The analysis: Target should have segmented its network so vendors could not reach payment systems.
So, from the contractor's hacked laptop, what can an attacker reach on Ravi's network?
Demo 1: the flat network
A flat network means every machine can talk to every other machine, on any port (a numbered door on a machine, one per service: 443 for HTTPS websites, 22 for SSH remote login, 445 for SMB file sharing, 5432 here for the database; episode 19). The switch SEGMENTED = False models that. We try four targets from the laptop: the HVAC panel, the web server, a shop till (pos-terminal) and the customer database.
SEGMENTED = False # <- one flat network, or zones with rules
ZONE = {"vendor-laptop": "vendors", "hvac-panel": "facilities", "web-server": "dmz",
"pos-terminal": "payments", "customer-db": "payments"}
POLICY = {("vendors", "facilities"): {443}, # contractors may reach only the HVAC panel
("internet", "dmz"): {443}, # customers reach only the web server
("dmz", "payments"): {5432}, # the web server may query the database
("payments", "payments"): {5432}} # tills talk to the database
def allowed(src, dst, port):
if not SEGMENTED: return True # flat: everything reaches everything
return port in POLICY.get((ZONE[src], ZONE[dst]), set()) # default deny between zones
print("The contractor's laptop is hacked. What can it reach?")
for dst, port in [("hvac-panel", 443), ("web-server", 22), ("pos-terminal", 445), ("customer-db", 5432)]:
print(f" {dst:13} port {port:<5} {'REACHABLE' if allowed('vendor-laptop', dst, port) else 'blocked'}")
Output:
The contractor's laptop is hacked. What can it reach?
hvac-panel port 443 REACHABLE
web-server port 22 REACHABLE
pos-terminal port 445 REACHABLE
customer-db port 5432 REACHABLE
Reachable, reachable, reachable, reachable. The contractor needed one panel and got the whole company, including the tills and the card database.
Why? Nothing stood between the machines. The blast radius (everything an attacker can reach from one foothold, the first machine they control) was the entire company. A flat network means a huge blast radius.
(The POLICY table and allowed() function are already written but switched off; we turn them on in Problem 5.)
The fix: a gate with a list
Think of a housing society. Visitors can't walk to any flat they like:
| Housing society | Network | What it means |
|---|---|---|
| A guard at the gate; every visitor passes the gate | Firewall | A device or program that sits between networks (or between a network and one machine) and decides which traffic may cross |
| The guard's list: who may enter, to which flat, read top to bottom | Rules / ACL | Each rule says: from this source, to this destination, on this port (and protocol, e.g. TCP or UDP), allow or deny. An ordered list of rules is an access control list (ACL) |
| Not on the list? Not entering | Default deny | Anything no rule allows is blocked |
A firewall is just a gate plus a rule list. The rest of this episode is about writing that list well and putting gates in the right places.
Problem 2: allowlist vs denylist
There are two ways to write the guard's list:
- A denylist (also called a blocklist): block the things you know are bad, allow everything else. A guard told "keep out these three troublemakers; everyone else may go anywhere".
- An allowlist: allow only the things you know are needed, deny everything else. A guard told "these guests, to these flats; nobody else".
Firewalls check rules top to bottom, and the first rule that matches decides (first match wins). Nothing below it is even looked at.
Demo 2: a denylist and an allowlist, four visitors
The denylist blocks two "known bad" ports, Telnet (port 23, an old remote-login protocol that sends everything, even passwords, as plain text) and SMB (port 445, Windows file sharing), and allows the rest. The allowlist allows the shop website (443) and the mail server (25, the port for sending email), then denies everything. The four visitors: a customer, a Telnet probe, an attacker going for the database on 5432, and an attacker going for remote desktop (port 3389, controlling a Windows PC's screen over the network).
# A packet filter: rules checked top to bottom, the FIRST match decides
DENYLIST = [("deny", "any", 23), ("deny", "any", 445), # block "known bad" ports: Telnet, SMB
("allow", "any", "any")] # ...and allow everything else
ALLOWLIST = [("allow", "web-server", 443), # only what the business needs
("allow", "mail-server", 25),
("deny", "any", "any")] # default deny: everything else
def check(rules, dst, port):
for action, r_dst, r_port in rules:
if r_dst in ("any", dst) and r_port in ("any", port):
return action
attempts = [("web-server", 443, "customer -> shop"), ("db-server", 23, "telnet probe"),
("db-server", 5432, "attacker -> database"), ("hr-pc", 3389, "attacker -> remote desktop")]
print(f"{'':28}{'denylist':10}allowlist")
for dst, port, who in attempts:
print(f"{who:28}{check(DENYLIST, dst, port):10}{check(ALLOWLIST, dst, port)}")
Output:
denylist allowlist
customer -> shop allow allow
telnet probe deny deny
attacker -> database allow deny
attacker -> remote desktop allow deny
- Customer → shop: allowed by both lists. Good.
- Telnet probe: denied by both. Good.
- Attacker → database (5432) and attacker → remote desktop (3389): the denylist allowed both. Nobody thought to list them. The allowlist denied both, because they hit the final
("deny", "any", "any").
Why? A denylist has to predict every bad thing in advance, and the attacker only needs the one you forgot. An allowlist only has to know what's good, which you do know: it's what your business runs. Everything else falls to the last rule. List the good, deny the rest.
(A detail of the code: check() returns None if no rule matches at all. Both lists end with a catch-all "any", "any" rule, so that never happens here. Real firewalls also have a built-in last action for traffic no rule matched, and it should be deny.)
How firewall rules work
source -> destination -> port + protocol -> ACTION (allow / deny)
who to whom which service
- First match wins: order matters. A broad allow placed too early silently overrides everything below it (you'll see this go badly wrong in Problem 6).
- Denylist: block known bad, allow the rest. Fails open: anything you forgot is allowed.
- Allowlist: allow known good, deny the rest. Fails closed: anything you forgot is blocked, and someone complains, so you notice.
- NIST (the US National Institute of Standards and Technology), in SP 800-41 Rev. 1, "Guidelines on Firewalls and Firewall Policy" (September 2009): "firewalls should block all inbound and outbound traffic that has not been expressly permitted by the firewall policy". That is default deny, in both directions. Always.
Problem 3: stateful firewalls and NGFWs
Default deny inbound has a catch. An office PC, 10.0.0.5, opens a website: it goes out to the site's port 443. Fine. But the web page has to come back in.
The simplest firewall, a packet filter, looks at each packet (one small chunk of data with an address label on it) alone, with no memory of earlier packets. That's called stateless. It cannot tell "a reply to something we asked for" from "a stranger knocking". So admins write the obvious rule: allow anything coming from port 443.
Every packet carries a source port (the sender's door number) and a destination port (the receiver's door number). When the PC calls a website, the website's side is port 443 and the PC's side is a random high number like 51000. So the reply comes from 443 to 51000. The catch: a source port is just a number the sender chooses. An attacker can simply set theirs to 443.
Demo 3: stateless vs stateful
The stateless filter allows any packet whose source port is 443. The stateful filter keeps a connection table (also called a state table): a list of the conversations that inside machines started, and allows only packets that belong to one of them. Two packets arrive: the website's real reply, and an attacker's forged packet with source port 443, aimed at the PC's remote desktop port 3389.
# Inside: the office PC 10.0.0.5. It browses websites (port 443) and must get the replies back.
def stateless(pkt): # a packet filter only sees one packet at a time, so to let replies in...
return pkt["src_port"] == 443 # "...allow anything coming FROM port 443"
conns = set() # a stateful firewall remembers the connections inside machines started
def stateful(pkt):
return (pkt["src"], pkt["src_port"], pkt["dst"], pkt["dst_port"]) in conns
conns.add(("192.0.2.10", 443, "10.0.0.5", 51000)) # the PC opened 10.0.0.5:51000 -> site:443
reply = {"src": "192.0.2.10", "src_port": 443, "dst": "10.0.0.5", "dst_port": 51000}
attack = {"src": "198.51.100.66", "src_port": 443, "dst": "10.0.0.5", "dst_port": 3389} # forged
for name, pkt in [("real reply", reply), ("attacker, source port 443", attack)]:
verdicts = ["ALLOW" if f(pkt) else "drop" for f in (stateless, stateful)]
print(f"{name:26} stateless: {verdicts[0]:6} stateful: {verdicts[1]}")
Output:
real reply stateless: ALLOW stateful: ALLOW
attacker, source port 443 stateless: ALLOW stateful: drop
- The real reply: allowed by both. It matches the connection the PC opened.
- The forged packet: allowed by the stateless filter (source port 443, so it looks fine), dropped by the stateful one, because no inside machine ever started a conversation with
198.51.100.66.
That is stateful inspection. In NIST's words (SP 800-41 Rev. 1): "Stateful inspection improves on the functions of packet filters by tracking the state of connections". Remember the TCP states from episode 19 (SYN, SYN-ACK, ESTABLISHED, FIN)? A stateful firewall follows them for every connection, adding an entry when the inside machine opens a conversation and removing it when the conversation ends or goes quiet. Real-life picture: a building guard who writes down "flat 12 ordered food from the pizza shop at 8 pm" and lets that one delivery rider in, but not a stranger who just says he's from a pizza shop.
Kinds of firewalls
| Kind | What it looks at | Real-life picture |
|---|---|---|
| Packet filter (stateless) | Each packet alone: addresses, ports, protocol | A guard who checks each visitor's badge colour, with no memory |
| Stateful firewall | The above + a connection table | A guard with a logbook of who invited whom |
| Next-generation firewall (NGFW) | The above + which application, which user, usually an IPS and threat feeds, and optionally TLS inspection | A guard who also checks ID, knows each resident, and has the police's wanted list |
| Host-based firewall | Runs on each machine itself | A lock on every flat's own door |
- Packet filters and stateful firewalls both decide by port number. Anything that runs over port 443 looks the same to them: a website, a file-sharing app, or malware all look like "HTTPS".
- A next-generation firewall (NGFW) also identifies the application ("this is a file-sharing app, not a website") and the user behind the traffic. Most include an intrusion prevention system (IPS): a component that recognises the patterns of known attacks in the traffic and blocks them. Threat feeds are regularly updated lists of known-bad addresses and domains. TLS inspection means the firewall decrypts encrypted HTTPS traffic, looks inside, and re-encrypts it; this is only done on company-managed devices that are set up to trust it.
- A host-based firewall runs on each machine: Windows Defender Firewall on Windows, nftables or ufw on Linux. It guards that one machine, even from its neighbours on the same network, where a network firewall never sees the traffic.
Network firewall guards the zone; host firewall guards the machine. You want both: a gate for the zone, and a lock on every door.
Problem 4: egress filtering
Firewalls usually face inward. But suppose an attacker has already got malware onto Ravi's web server. Malware usually needs to call home to its command and control server (C2: the attacker's machine that sends it orders), and to upload stolen data (taking data out is called exfiltration). With no outbound rules, does any of that get out?
Demo 4: no outbound rules
EGRESS_FILTER = False # <- outbound rules on, or "anything may go out"
ALLOWED_OUT = {("updates.example", 443), ("dns-resolver", 53)} # what this server really needs
def leaves(dst, port):
return not EGRESS_FILTER or (dst, port) in ALLOWED_OUT
# The web server is hacked. The malware tries to phone home and to ship the database out.
for dst, port, why in [("updates.example", 443, "normal patching"),
("203.0.113.66", 4444, "malware calls its controller"),
("203.0.113.66", 443, "uploads customers.csv"),
("dns-resolver", 53, "name lookups")]:
print(f"{why:30} -> {dst + ':' + str(port):22} {'LEAVES' if leaves(dst, port) else 'BLOCKED, alert raised'}")
Output:
normal patching -> updates.example:443 LEAVES
malware calls its controller -> 203.0.113.66:4444 LEAVES
uploads customers.csv -> 203.0.113.66:443 LEAVES
name lookups -> dns-resolver:53 LEAVES
Everything leaves: the call to the controller on port 4444 and the upload of customers.csv, right alongside normal patching. "Anything may go out" is a denylist with nothing on it.
Demo 5: turn on egress filtering
This server only ever needs two things outside: its update server (443) and DNS (port 53, name lookups; episode 20). One switch: EGRESS_FILTER = True.
EGRESS_FILTER = True # <- outbound rules on, or "anything may go out"
ALLOWED_OUT = {("updates.example", 443), ("dns-resolver", 53)} # what this server really needs
def leaves(dst, port):
return not EGRESS_FILTER or (dst, port) in ALLOWED_OUT
# The web server is hacked. The malware tries to phone home and to ship the database out.
for dst, port, why in [("updates.example", 443, "normal patching"),
("203.0.113.66", 4444, "malware calls its controller"),
("203.0.113.66", 443, "uploads customers.csv"),
("dns-resolver", 53, "name lookups")]:
print(f"{why:30} -> {dst + ':' + str(port):22} {'LEAVES' if leaves(dst, port) else 'BLOCKED, alert raised'}")
Output:
normal patching -> updates.example:443 LEAVES
malware calls its controller -> 203.0.113.66:4444 BLOCKED, alert raised
uploads customers.csv -> 203.0.113.66:443 BLOCKED, alert raised
name lookups -> dns-resolver:53 LEAVES
Patching and name lookups still work. The controller call and the upload are blocked, and an alert is raised, which tells the defenders exactly which server is infected. Note that the upload went to port 443: port alone isn't enough, so the rule names the destination too. A server that suddenly talks to a new place is one of the strongest warning signs there is. Real-life picture: a bank's staff exit where every bag is checked; a stolen file is far harder to carry out.
Ingress and egress filtering
| Direction | Name | Rule of thumb |
|---|---|---|
| Traffic coming in | Ingress filtering | Default deny inbound; allow only the services you publish (the website on 443) |
| Traffic going out | Egress filtering | Each server talks out only to what it needs |
Egress has a second meaning too. NIST SP 800-41 Rev. 1: "Outbound traffic with invalid source addresses should be blocked (this is often called egress filtering)". A packet leaving Ravi's network that claims a source address that isn't Ravi's is forged (spoofed). That is the same anti-spoofing idea as RFC 2827 / BCP 38 (May 2000) from last episode: forward a customer's traffic only if its source address is in the customer's prefix (their block of addresses). BCP 38 does it from the internet provider's side; egress filtering does it from your own network's side (Practice 4). Filter both directions.
Problem 5: DMZ, VLANs and segmentation
One firewall at the edge isn't enough: once the contractor's laptop is inside, Demo 1 showed it reaches everything. We need walls inside too.
A bank branch isn't one big room:
| Bank branch | Network | What lives there |
|---|---|---|
| The public lobby: anyone may enter, nothing valuable | DMZ (demilitarised zone) | Servers the internet must reach, like the web server. If one is hacked, it's still outside the inner walls |
| Staff offices: badge needed | Internal zones | Staff laptops, HR, finance, each its own network |
| The vault: only two people, through one door | Restricted zone | Payment systems, card data |
| Locked doors between rooms, with a list at each door | Segmentation | Firewall rules controlling every crossing between zones |
A zone is a group of machines with the same job and the same trust level. Network segmentation means splitting a network into zones, with firewall rules controlling every crossing. Zones are often built as VLANs (virtual LANs, episode 23): separate networks that share the same physical switches, each kept apart by a label on its traffic.
Demo 6: the same program, segmented
The same program as Demo 1. Each machine sits in a zone: vendors, facilities, dmz, payments. The POLICY lists the few allowed crossings and their ports; everything else between zones is denied by default (POLICY.get(..., set()) gives an empty set, so no port is allowed). One switch: SEGMENTED = True. Same hacked laptop.
SEGMENTED = True # <- one flat network, or zones with rules
ZONE = {"vendor-laptop": "vendors", "hvac-panel": "facilities", "web-server": "dmz",
"pos-terminal": "payments", "customer-db": "payments"}
POLICY = {("vendors", "facilities"): {443}, # contractors may reach only the HVAC panel
("internet", "dmz"): {443}, # customers reach only the web server
("dmz", "payments"): {5432}, # the web server may query the database
("payments", "payments"): {5432}} # tills talk to the database
def allowed(src, dst, port):
if not SEGMENTED: return True # flat: everything reaches everything
return port in POLICY.get((ZONE[src], ZONE[dst]), set()) # default deny between zones
print("The contractor's laptop is hacked. What can it reach?")
for dst, port in [("hvac-panel", 443), ("web-server", 22), ("pos-terminal", 445), ("customer-db", 5432)]:
print(f" {dst:13} port {port:<5} {'REACHABLE' if allowed('vendor-laptop', dst, port) else 'blocked'}")
Output:
The contractor's laptop is hacked. What can it reach?
hvac-panel port 443 REACHABLE
web-server port 22 blocked
pos-terminal port 445 blocked
customer-db port 5432 blocked
- The HVAC panel: still reachable, because that is the contractor's real job.
- The web server, the tills and the card database: blocked.
The blast radius shrank from the whole company to one fridge panel. This is exactly the segmentation the Target analysis said was missing: vendors reach only their own system.
Segmentation, then microsegmentation
internet -> DMZ (web) -> internal (app) -> restricted (DB)
443 only needed ports 5432
- Each arrow is a firewall rule allowing only the ports needed: the web server may query the database, the internet may not.
- A VLAN alone is not a wall. VLANs separate networks on shared switches, but traffic between VLANs passes through a router (the device that forwards traffic between networks). If that router allows everything, it's still a flat network with extra steps. Put firewall rules on the crossing.
- Microsegmentation goes further: rules for each workload (each server, virtual machine or container, a small packaged app with its own little environment), even inside one zone. Two web servers in the DMZ don't need to talk to each other, so they can't; if one is hacked, it can't jump to its twin. It's common in cloud networks, and a building block of zero trust (the idea that being "inside the network" earns no trust by itself: every connection must be allowed explicitly). Real-life picture: not just locked doors between floors of an office, but a lock on every cabinet.
Goal: the smallest possible blast radius.
Problem 6: bastion hosts, jump boxes, rule reviews
Now the servers are walled off. But admins still need to log in and fix them. If SSH (22) and remote desktop (3389) are open from everywhere, the walls have a hole in every room.
A building has one service entrance with a guard for the maintenance crew:
| Building | Network | What it means |
|---|---|---|
| One service entrance, with a guard: the only way in for the crew | Bastion host | One specially hardened machine that is deliberately reachable, and the only way in. "Hardened" = everything unneeded removed, patched, closely watched |
| Sign in, show ID, get escorted; everything recorded | Jump box | The inside version: admins first log in to it with MFA (multi-factor authentication: a password plus something else, like a code on a phone), every session recorded, and only from there reach the servers |
| The guard's list is checked monthly; old contractors removed | Firewall rule review | Regularly checking every rule: who owns it, why it exists, whether it expired, whether it's ever used |
Admin ports like SSH and remote desktop are then open only from the jump box, never from the internet or ordinary laptops. One door, watched. (Some teams use "bastion host" and "jump box" for the same machine; the idea is the same: one controlled path in.)
Rules rot
Over the years, firewall rule lists grow: a "temporary" rule for debugging, a contractor who left, a server that was switched off. Nobody removes anything, because nobody remembers why it was added. A firewall rule review finds:
- Any-any rules: "allow from any source, to any destination, on any port". A hole the size of the wall.
- Rules with no owner: nobody can say why they exist.
- Expired rules: access that was meant to end.
- Shadowed rules: rules that can never match, because an earlier rule already catches everything they would (first match wins).
Demo 7: an automated rule review
Five rules, each with an owner and an expiry date. covers(a, b) asks: does rule a match everything rule b matches (every field of a is "any" or equal)? If any earlier rule covers this one, it's shadowed.
from datetime import date
RULES = [ # (id, src, dst, port, action, owner, expires)
(1, "any", "web-server", 443, "allow", "web team", None),
(2, "any", "any", "any", "allow", "unknown", None), # "temporary" debugging
(3, "vendors", "hvac-panel", 443, "allow", "facilities", date(2026, 3, 31)),
(4, "any", "db-server", 5432, "deny", "dba team", None),
(5, "any", "any", "any", "deny", "policy", None)]
TODAY = date(2026, 11, 2)
covers = lambda a, b: all(x == "any" or x == y for x, y in zip(a, b)) # does rule a match all that b does?
for i, (rid, src, dst, port, action, owner, expires) in enumerate(RULES):
problems = []
if action == "allow" and (src, dst, port) == ("any", "any", "any"): problems.append("ANY-ANY ALLOW")
if owner == "unknown": problems.append("no owner")
if expires and expires < TODAY: problems.append(f"expired {expires}")
if any(covers(r[1:4], (src, dst, port)) for r in RULES[:i]): problems.append(f"shadowed: never reached")
print(f"rule {rid}: {action:5} {src:8} -> {dst:10} {str(port):5} | {', '.join(problems) or 'ok'}")
Output:
rule 1: allow any -> web-server 443 | ok
rule 2: allow any -> any any | ANY-ANY ALLOW, no owner
rule 3: allow vendors -> hvac-panel 443 | expired 2026-03-31, shadowed: never reached
rule 4: deny any -> db-server 5432 | shadowed: never reached
rule 5: deny any -> any any | shadowed: never reached
- Rule 2: allow anything, anywhere, owner unknown: added "temporarily" for debugging and never removed.
- Because it's second, rules 3, 4 and 5 are shadowed. The database deny and the final default deny can never fire. One forgotten rule switched off the whole policy: this firewall is now effectively a flat network.
- Rule 3 also expired in March: the contractor's access that nobody cleaned up.
Real reviews add one more check: hit counts, how many times each rule actually matched traffic. A rule with zero hits for a year is probably safe to remove (Practice 2). Every rule: owner, reason, expiry.
The next problem
Ravi's network now has walls. But his staff work from home and from cafés, outside every wall. And his office Wi-Fi leaks into the car park, where anyone can try to join. Secure tunnels and secure wireless: VPNs, remote access and Wi-Fi security, next episode.
The whole chain
- Flat network, one laptop reaches everything → firewall, rules, ACL
- A denylist misses 5432 → allowlist, default deny, first match
- "Allow from port 443" lets forgeries in → stateful inspection
- Ports aren't apps → NGFW; machines need their own locks → host-based firewall
- Malware phones home → egress (and ingress) filtering
- One breach reaches all → DMZ, VLANs, segmentation, microsegmentation
- Admins need a way in → bastion host, jump box
- Rules rot → firewall rule review: owner, expiry, shadowing, hit counts
...and you just invented network segmentation.
Common mistakes (and what they print)
| Mistake | What you get | Why | Fix |
|---|---|---|---|
| Denylist: block 23 and 445, allow the rest | attacker -> database allow |
You can't list every bad port | Allowlist + default deny |
| "Allow anything from source port 443" | attacker, source port 443 stateless: ALLOW |
The sender picks the source port | Stateful rules for replies |
| A "temporary" any-any rule | rule 2: allow any -> any any \| ANY-ANY ALLOW, no owner |
It shadows every rule below it | Owner + expiry on every rule; regular reviews |
| Contractor access never removed | expired 2026-03-31 |
Nobody owns the clean-up | Expiry dates, checked automatically |
| No outbound rules | malware calls its controller -> 203.0.113.66:4444 LEAVES |
"Anything may go out" | Egress filtering per server, with alerts |
| One flat network | customer-db port 5432 REACHABLE from a vendor laptop |
Nothing between zones | Segmentation; vendors reach only their system |
| VLANs joined by an allow-all router | A flat network with extra steps | No rules on the crossing | A firewall between VLANs |
| Only a network firewall | Neighbours in the same zone reach each other freely | The gate never sees traffic inside the zone | Host-based firewalls, microsegmentation |
Mini project: Ravi's zone-policy checker
Before changing any wall, draw the map. This tool prints a reachability matrix: for every pair of zones, which ports may cross. Then it flags two kinds of risky crossings: a zone outside the vault's short list reaching the restricted payments zone, and an admin port (SSH or remote desktop) open from anywhere other than the admin zone where the jump box lives. Two "helpful" rules hide in the policy.
# Ravi's zone-policy checker: who may reach whom, and which crossings look risky
ZONES = ["internet", "vendors", "staff", "dmz", "facilities", "payments", "admin"]
POLICY = {("internet", "dmz"): {443},
("vendors", "facilities"): {443},
("staff", "dmz"): {443},
("staff", "payments"): {5432}, # someone asked for "reports access"
("dmz", "payments"): {5432},
("payments", "payments"): {5432},
("admin", "dmz"): {22},
("admin", "payments"): {22},
("internet", "admin"): {22}} # "so admins can work from home"
RESTRICTED = {"payments"} # the vault
MAY_ENTER_VAULT = {"dmz", "payments", "admin"} # the only zones allowed in
ADMIN_PORTS = {22, 3389} # SSH, remote desktop
print(f"{'from / to':11}" + "".join(f"{z:11}" for z in ZONES))
for src in ZONES:
cells = [",".join(map(str, sorted(POLICY.get((src, dst), set())))) or "-" for dst in ZONES]
print(f"{src:11}" + "".join(f"{c:11}" for c in cells))
print("\nFindings:")
for (src, dst), ports in POLICY.items():
if dst in RESTRICTED and src not in MAY_ENTER_VAULT:
print(f" {src} -> {dst} {sorted(ports)}: a zone outside the vault's list reaches the vault")
if ports & ADMIN_PORTS and src != "admin":
print(f" {src} -> {dst} {sorted(ports & ADMIN_PORTS)}: admin port open from outside the jump box zone")
Output:
from / to internet vendors staff dmz facilities payments admin
internet - - - 443 - - 22
vendors - - - - 443 - -
staff - - - 443 - 5432 -
dmz - - - - - 5432 -
facilities - - - - - - -
payments - - - - - 5432 -
admin - - - 22 - 22 -
Findings:
staff -> payments [5432]: a zone outside the vault's list reaches the vault
internet -> admin [22]: admin port open from outside the jump box zone
Read a row as "from this zone, to each column": staff can reach the DMZ on 443 and payments on 5432. The two findings are the two "helpful" rules: staff reaching the card database for "reports" (give them a report from the DMZ app instead), and SSH open from the internet straight into the admin zone (admins should come in through a VPN, next episode, then the jump box, with MFA). An empty facilities row is good news: the HVAC panel can't start conversations anywhere. Ideas to extend it: flag any "any" port, and add a column counting how many zones can reach each zone (its exposure).
Practice
1. Homework: add a staff zone to the zones demo. Staff may use the shop website, nothing else. Test from a hacked staff PC.
Solution
SEGMENTED = True
ZONE = {"vendor-laptop": "vendors", "hvac-panel": "facilities", "web-server": "dmz",
"pos-terminal": "payments", "customer-db": "payments",
"staff-pc": "staff"} # new: the office staff zone
POLICY = {("vendors", "facilities"): {443},
("internet", "dmz"): {443},
("dmz", "payments"): {5432},
("payments", "payments"): {5432},
("staff", "dmz"): {443}} # staff may use the shop website, nothing else
def allowed(src, dst, port):
if not SEGMENTED: return True
return port in POLICY.get((ZONE[src], ZONE[dst]), set())
print("A staff PC is hacked. What can it reach?")
for dst, port in [("web-server", 443), ("web-server", 22), ("pos-terminal", 445),
("customer-db", 5432), ("hvac-panel", 443)]:
print(f" {dst:13} port {port:<5} {'REACHABLE' if allowed('staff-pc', dst, port) else 'blocked'}")
Output:
A staff PC is hacked. What can it reach?
web-server port 443 REACHABLE
web-server port 22 blocked
pos-terminal port 445 blocked
customer-db port 5432 blocked
hvac-panel port 443 blocked
One new zone entry and one new policy line. Everything not listed, including the tills, the database and the HVAC panel, is blocked by default deny: you didn't have to write a single deny rule.
2. Homework: add hit counts to the rule review. Replay a made-up firewall log through the rules and count which rule matched each line.
Solution
from collections import Counter
RULES = [ # (id, src, dst, port, action)
(1, "any", "web-server", 443, "allow"),
(2, "vendors", "hvac-panel", 443, "allow"),
(3, "staff", "file-server", 445, "allow"),
(4, "any", "db-server", 5432, "deny"),
(5, "any", "any", "any", "deny")]
# made-up firewall log: source zone, destination, port
LOG = """internet web-server 443
internet web-server 443
staff web-server 443
vendors hvac-panel 443
internet db-server 5432
internet hr-pc 3389
internet web-server 443
vendors pos-terminal 445"""
hits = Counter()
def first_match(src, dst, port):
for rid, r_src, r_dst, r_port, action in RULES:
if r_src in ("any", src) and r_dst in ("any", dst) and r_port in ("any", port):
hits[rid] += 1
return action
for line in LOG.splitlines():
src, dst, port = line.split()
first_match(src, dst, int(port))
for rid, src, dst, port, action in RULES:
note = " <- zero hits: still needed?" if hits[rid] == 0 else ""
print(f"rule {rid}: {action:5} {src:7} -> {dst:11} {str(port):5} hits: {hits[rid]}{note}")
Output:
rule 1: allow any -> web-server 443 hits: 4
rule 2: allow vendors -> hvac-panel 443 hits: 1
rule 3: allow staff -> file-server 445 hits: 0 <- zero hits: still needed?
rule 4: deny any -> db-server 5432 hits: 1
rule 5: deny any -> any any hits: 2
Only the first matching rule gets the hit, just like a real firewall. Rule 3 never matched in this log: ask its owner whether the file server still exists before deleting it. Rule 5 (default deny) caught the remote desktop attempt and the vendor reaching for a till: those are worth an alert. Real reviews look at hit counts over months, not eight lines.
3. Homework: make the stateful table forget old connections.
Solution
TIMEOUT = 60 # seconds a quiet connection is remembered
conns = {} # connection -> last time we saw it
def remember(conn, now):
conns[conn] = now
def stateful(pkt, now):
key = (pkt["src"], pkt["src_port"], pkt["dst"], pkt["dst_port"])
for conn, seen in list(conns.items()): # forget connections that went quiet
if now - seen > TIMEOUT:
del conns[conn]
if key in conns:
conns[key] = now # still active: refresh the timer
return "ALLOW"
return "drop"
reply = {"src": "192.0.2.10", "src_port": 443, "dst": "10.0.0.5", "dst_port": 51000}
remember(("192.0.2.10", 443, "10.0.0.5", 51000), now=0) # the PC opened it at t=0
for t in [5, 50, 200]:
print(f"t={t:<4} reply -> {stateful(reply, t):6} table size: {len(conns)}")
Output:
t=5 reply -> ALLOW table size: 1
t=50 reply -> ALLOW table size: 1
t=200 reply -> drop table size: 0
Each entry remembers when it was last used. After 60 quiet seconds it's removed, so a late (or forged) packet for an old conversation is dropped and the table can't grow forever. Real firewalls use timeouts too, and also remove TCP entries when the connection closes (FIN or RST).
4. Write the egress anti-spoofing check (the BCP 38 idea) for Ravi's network.
Solution
import ipaddress
OUR_PREFIX = ipaddress.ip_network("192.0.2.0/24") # the addresses Ravi's network owns (documentation range)
def egress_ok(src): # BCP 38 idea: only send packets whose source address is ours
return ipaddress.ip_address(src) in OUR_PREFIX
for src, why in [("192.0.2.25", "normal shop traffic"),
("198.51.100.9", "spoofed: someone else's address"),
("10.66.0.1", "spoofed: private address")]:
print(f"{src:14} {why:33} {'forward' if egress_ok(src) else 'DROP'}")
Output:
192.0.2.25 normal shop traffic forward
198.51.100.9 spoofed: someone else's address DROP
10.66.0.1 spoofed: private address DROP
ipaddress.ip_network holds Ravi's prefix, and in checks whether an address belongs to it. A packet leaving the network with someone else's address can only be forged, so it's dropped: that's what NIST means by "outbound traffic with invalid source addresses should be blocked".
5. Fix the review from Demo 7: delete rule 2, and have the facilities team renew rule 3 until 31 March 2027. Run the review again.
Solution
from datetime import date
RULES = [ # (id, src, dst, port, action, owner, expires)
(1, "any", "web-server", 443, "allow", "web team", None),
(3, "vendors", "hvac-panel", 443, "allow", "facilities", date(2027, 3, 31)),
(4, "any", "db-server", 5432, "deny", "dba team", None),
(5, "any", "any", "any", "deny", "policy", None)]
TODAY = date(2026, 11, 2)
covers = lambda a, b: all(x == "any" or x == y for x, y in zip(a, b)) # does rule a match all that b does?
for i, (rid, src, dst, port, action, owner, expires) in enumerate(RULES):
problems = []
if action == "allow" and (src, dst, port) == ("any", "any", "any"): problems.append("ANY-ANY ALLOW")
if owner == "unknown": problems.append("no owner")
if expires and expires < TODAY: problems.append(f"expired {expires}")
if any(covers(r[1:4], (src, dst, port)) for r in RULES[:i]): problems.append(f"shadowed: never reached")
print(f"rule {rid}: {action:5} {src:8} -> {dst:10} {str(port):5} | {', '.join(problems) or 'ok'}")
Output:
rule 1: allow any -> web-server 443 | ok
rule 3: allow vendors -> hvac-panel 443 | ok
rule 4: deny any -> db-server 5432 | ok
rule 5: deny any -> any any | ok
With the any-any rule gone, nothing shadows rules 3 to 5, so the database deny and the default deny work again. Rule 5 isn't flagged as any-any because it's a deny: an any-any deny at the bottom is exactly what default deny looks like.
6. Ravi's IT person says: "We already split the network into VLANs, so we're segmented." What do you ask?
Answer
"What rules does the router (or firewall) between the VLANs apply?" VLANs only separate traffic on the switches; traffic between them goes through a router. If that router allows everything, any VLAN can reach any other and the network is still flat. Segmentation needs default-deny rules on every crossing, allowing only the ports each zone needs.
7. Comment question: what's the blast radius of your home Wi-Fi?
Answer
On most home networks every device (laptops, phones, TV, smart plugs, cameras, a guest's phone) sits on one flat network, so one hacked cheap camera can reach your work laptop. To shrink it: put smart devices and guests on a separate guest network, keep host-based firewalls switched on, and remove devices you no longer use.
Quick quiz
Goal: customers reach the web server on 443, and nothing else gets in. Remember, first match wins. Which rule order is right?
A: deny any any | allow any web:443
B: allow any web:443 | deny any any
C: allow any any | deny any web:22
D: allow any web:any | deny any any
Answer
B. Allow HTTPS to the web server, then deny everything else by default. In A the deny catches everything first, so the allow is never reached and customers are blocked. C is a denylist in spirit ("allow everything except SSH to the web server"), and it's worse than that: the any-any allow comes first, so the SSH deny is shadowed and C actually allows everything. D opens every port on the web server.
Interview questions
- What is a firewall, and how does it decide? A device or program between networks (or on a host) that applies an ordered list of rules (source, destination, port/protocol, action); the first matching rule decides, and unmatched traffic should be denied.
- Allowlist vs denylist: which and why? Allowlist with default deny. A denylist must predict every bad thing and fails open on anything forgotten; an allowlist only needs to know what the business needs and fails closed. NIST SP 800-41 Rev. 1 recommends blocking all traffic not expressly permitted.
- Stateless vs stateful firewall? A stateless packet filter judges each packet alone by addresses and ports; a stateful firewall tracks connections in a state table and allows return traffic only for connections initiated from the allowed side, so forged "replies" are dropped.
- What does an NGFW add? Application and user identification, usually an integrated IPS, threat intelligence feeds, and optional TLS inspection on managed devices.
- Why use host-based firewalls if you have a network firewall? The network firewall only sees traffic crossing it; a host firewall protects each machine from its neighbours in the same zone and still works when the device leaves the office.
- Ingress vs egress filtering? Ingress controls inbound traffic (allow only published services). Egress controls outbound traffic (servers talk only to what they need) and drops packets with source addresses that aren't yours (the BCP 38 idea). Egress rules catch C2 callbacks and exfiltration and raise alerts.
- What is a DMZ? A separate zone for internet-facing servers, firewalled from both the internet and the internal network, so a compromised public server doesn't sit inside the inner walls.
- Segmentation vs microsegmentation? Segmentation splits the network into zones with firewall rules between them; microsegmentation applies rules per workload (server, VM, container), even within a zone, to minimise lateral movement and blast radius; it's a building block of zero trust.
- Bastion host vs jump box? A bastion host is a hardened machine deliberately exposed as the single entry point; a jump box is the controlled intermediate machine admins log in to (with MFA and session recording) before reaching servers. Admin ports on servers are open only from it. The terms are often used interchangeably.
- What do you look for in a firewall rule review? Any-any allows, rules without an owner or reason, expired rules, shadowed or redundant rules (order problems), overly broad sources or ports, admin ports open widely, and rules with zero hit counts over a long period.
Glossary
| Term | Meaning in plain words | Example |
|---|---|---|
| Firewall | A device or program between networks (or on one machine) that decides which traffic may cross, using rules | The guard at the society gate |
| Rule | One line of a firewall's list: source, destination, port/protocol, action | allow any -> web-server 443 |
| Action | What a rule does when it matches: allow or deny | deny |
| Access control list (ACL) | An ordered list of allow/deny rules | DENYLIST, ALLOWLIST in Demo 2 |
| First match | Rules are checked top to bottom; the first one that matches decides | Rule 2 swallowing rules 3 to 5 |
| Denylist (blocklist) | Block known bad, allow everything else | Block 23 and 445, allow the rest |
| Allowlist | Allow known good, deny everything else | Allow 443 to the web server, deny the rest |
| Allowlist vs denylist | Fail closed vs fail open on anything you forgot | 5432: allowlist denies, denylist allows |
| Default deny | Anything not expressly allowed is blocked (NIST SP 800-41) | ("deny", "any", "any") at the bottom |
| Packet | One small chunk of network data with addresses and ports on it | A web page arrives as many packets |
| Packet filter | A stateless firewall: judges each packet alone by addresses, ports, protocol | "Allow anything from port 443" |
| Stateless | No memory of earlier packets | The packet filter in Demo 3 |
| Port | A numbered door on a machine, one per service | 443 HTTPS, 22 SSH |
| Source port | The sender's port number, chosen by the sender | 51000, or a forged 443 |
| Destination port | The receiver's port, naming the service wanted | 3389 remote desktop |
| Protocol | The kind of traffic a rule applies to | TCP, UDP |
| Stateful inspection | Tracking each connection's state and allowing only packets that belong to a known connection | The forged packet dropped |
| Connection (state) table | The stateful firewall's list of open conversations | conns in Demo 3 |
| Next-generation firewall (NGFW) | A firewall that also identifies apps and users, usually with IPS, threat feeds, TLS inspection | "That's a file-sharing app, not a website" |
| IPS (intrusion prevention system) | Recognises known attack patterns in traffic and blocks them | Built into most NGFWs |
| Threat feed | A regularly updated list of known-bad addresses and domains | A list including a C2 server |
| TLS inspection | The firewall decrypts HTTPS, inspects it and re-encrypts it, on managed devices | Company laptops trusting the firewall |
| Host-based firewall | A firewall running on the machine itself | Windows Defender Firewall, nftables, ufw |
| Ingress filtering | Controlling traffic coming in | Only 443 to the web server |
| Egress filtering | Controlling traffic going out; also dropping outbound packets with source addresses that aren't yours | Demo 5, Practice 4 |
| Command and control (C2) | The attacker's server that malware calls for orders | 203.0.113.66:4444 |
| Exfiltration | Taking stolen data out of a network | Uploading customers.csv |
| Spoofing | Faking a packet's source address | 198.51.100.9 leaving Ravi's network |
| Prefix | A block of addresses owned by one network | 192.0.2.0/24 |
| RFC 2827 / BCP 38 | The rule (May 2000) to forward traffic only if its source address is in the sender's prefix | Practice 4 |
| NIST SP 800-41 Rev. 1 | US guidelines on firewalls and firewall policy (September 2009) | "block all ... not expressly permitted" |
| Flat network | Every machine can reach every other, on any port | Demo 1 |
| Blast radius | Everything an attacker can reach from one foothold | The whole company vs one fridge panel |
| Foothold | The first machine an attacker controls | The contractor's laptop |
| Attack surface | Every way into your systems, including vendors | The contractor's login |
| Credentials | What proves who you are: username and password, keys | The contractor's stolen login |
| HVAC | Heating, ventilation and air conditioning | The fridge-temperature panel |
| Point of sale (POS) | The tills where customers pay | pos-terminal |
| Zone | A group of machines with the same job and trust level | vendors, dmz, payments |
| DMZ (demilitarised zone) | A separate zone for servers the internet must reach | The web server (the bank lobby) |
| Restricted zone | The most protected zone, reachable through very few doors | Payments (the vault) |
| VLAN | A virtual LAN: a separate network on shared switches (episode 23) | Staff VLAN, payments VLAN |
| Router | The device that forwards traffic between networks or VLANs | Where inter-VLAN rules belong |
| Network segmentation | Splitting a network into zones with firewall rules on every crossing | Demo 6 |
| Microsegmentation | Rules per workload, even inside one zone | Two DMZ web servers can't talk |
| Workload | One server, virtual machine or container doing a job | A web server |
| Container | A small packaged app with its own little environment | One app in the cloud |
| Zero trust | Being inside the network earns no trust; every connection must be allowed explicitly | Microsegmentation everywhere |
| Bastion host | One hardened machine deliberately reachable, the only way in | The guarded service entrance |
| Hardened | Unneeded software removed, patched, locked down and watched | A bastion host |
| Jump box | The machine admins log in to (with MFA, recorded) before reaching servers | The sign-in desk with an escort |
| MFA | Multi-factor authentication: a password plus something else | Password + phone code |
| SSH | Secure Shell: encrypted remote login, port 22 | Admin access to a server |
| Remote desktop | Controlling a Windows PC's screen over the network, port 3389 | hr-pc 3389 |
| Telnet | An old remote-login protocol with no encryption, port 23 | The "telnet probe" |
| SMB | Windows file sharing, port 445 | pos-terminal 445 |
| Firewall rule review | Regularly checking every rule's owner, reason, expiry, order and use | Demo 7 |
| Any-any rule | Allows any source to any destination on any port | Rule 2 |
| Shadowed rule | A rule that can never match because an earlier rule catches all its traffic | Rules 3, 4, 5 in Demo 7 |
| Rule owner / expiry | Who is responsible for a rule, and when it should end | facilities, 2026-03-31 |
| Hit count | How many times a rule actually matched traffic | hits: 0 in Practice 2 |
| Reachability matrix | A table of which zones may reach which, on which ports | The mini project |
| Alert | A message telling defenders something suspicious happened | BLOCKED, alert raised |
Summary
- A flat network gives one hacked laptop a company-sized blast radius. The Target breach (2013) began with an HVAC contractor's stolen credentials and ended on the tills.
- A firewall applies an ordered list of rules (an ACL): source, destination, port/protocol, action. First match wins, so order matters.
- Allowlist + default deny beats a denylist: list the good, deny the rest (NIST SP 800-41 Rev. 1).
- A packet filter is stateless and can be fooled by a chosen source port; stateful inspection keeps a connection table. An NGFW adds apps, users, IPS and TLS inspection; host-based firewalls lock each machine.
- Ingress filtering guards what comes in; egress filtering stops command and control and exfiltration, raises alerts, and drops spoofed source addresses (BCP 38).
- Segmentation splits the network into zones (DMZ, internal, restricted), often as VLANs, with rules on every crossing; microsegmentation puts rules around each workload.
- Admins come in through one watched door: a bastion host / jump box with MFA. Rule reviews catch any-any, unowned, expired and shadowed rules, and use hit counts.
Next episode: VPNs, remote access and wireless security: IPsec, WireGuard, split tunnelling, WPA2 vs WPA3, 802.1X and RADIUS, evil twins and guest networks.
Sources: NIST SP 800-41 Rev. 1, "Guidelines on Firewalls and Firewall Policy" (K. Scarfone, P. Hoffman, September 2009); Computerworld (6 Feb 2014), on the 2013 Target breach; RFC 2827 / BCP 38, Network Ingress Filtering (May 2000). Code outputs from Python 3.13. Fetched 2 Nov 2026.