Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 80 ยท Network Security

Firewalls, Segmentation and Zero Trust

Understand stateful firewalls, DMZs, VLAN segmentation and zero trust, and build a small first-match rule engine in Python that tests allow and deny decisions.

A firewall is a gatekeeper that decides, packet by packet or connection by connection, what may pass between two parts of a network. Used well, it turns a flat network where everything can reach everything into a set of small zones where each system can reach only what it needs. That limits what an attacker can do after the first machine falls, which is why segmentation is among the most effective defensive measures.

This lesson covers how firewalls make decisions, how to arrange networks into zones, and how zero trust changes the thinking about "inside" and "outside". You'll finish by writing a rule engine yourself. If addresses, ports and CIDR are unfamiliar, read Networking Essentials for Defenders first.

Types of firewalls

  • Packet filter (stateless): looks at each packet alone: source and destination address, protocol and port. Fast and simple, but it cannot tell whether a packet belongs to a connection someone inside started.
  • Stateful firewall: tracks connections in a state table. If an inside host opens a connection to a web server, replies are allowed automatically. Unsolicited packets from outside are dropped. Almost every modern firewall and the one built into your operating system works this way.
  • Application-layer firewall / next-generation firewall (NGFW): understands protocols and sometimes users, and can block by application or inspect content. A web application firewall (WAF) specializes in HTTP and looks for patterns such as injection attempts; you will build a tiny one in Project: A Mini Web Application Firewall.
  • Host-based firewall: runs on each machine, so a compromised neighbor on the same subnet still cannot reach its services.
sequenceDiagram
    participant I as Inside host 10.0.1.5
    participant F as Stateful firewall
    participant W as Web server
    I->>F: SYN to port 443
    F->>F: rule allows outbound 443, record in state table
    F->>W: SYN
    W->>F: SYN-ACK (matches table entry)
    F->>I: SYN-ACK
    W->>F: unsolicited packet to port 3389
    F--xW: no matching state, no allow rule: drop

Return traffic is allowed because the table remembers the connection; unrequested traffic is not.

How rules are evaluated

A rule set is an ordered list. Each rule has match conditions (source, destination, protocol, port) and an action (allow, deny or drop). The firewall walks the list from the top and applies the first rule that matches. Three consequences follow:

  1. Order matters. A broad allow placed above a specific deny makes the deny useless.
  2. Default deny. The last rule, or the firewall's default policy, should refuse everything not explicitly allowed. This is the "fail-safe defaults" principle from The CIA Triad and Core Principles.
  3. Deny vs drop. deny (reject) answers with an error so legitimate users know quickly; drop silently discards the packet, giving scanners less information. Most internet-facing rules drop.

Good rules are as narrow as possible: name the exact source network, the exact destination and the one port, and add a comment saying why the rule exists. Review them regularly, because old rules are a common cause of exposure.

Zones, DMZ and VLANs

flowchart LR
    NET(("Internet")) --> FW1["Outer firewall"]
    FW1 --> DMZ["DMZ<br/>web, mail, reverse proxy"]
    DMZ --> FW2["Inner firewall"]
    FW2 --> APP["App servers"]
    FW2 --> DB[("Database zone")]
    FW2 --> USR["Staff network"]

Internet-facing servers live in the DMZ. Nothing from the DMZ can reach staff PCs, and only app servers can reach the database.

A DMZ (demilitarized zone) is a separate network segment for services that must be reachable from the internet. If a web server there is compromised, the attacker still faces the inner firewall and does not sit on the same network as the databases or employees.

Inside, VLANs (virtual LANs) divide one physical switch into separate logical networks, and each VLAN gets its own subnet. Traffic between VLANs must pass a router or firewall where rules apply. A typical office has VLANs for staff, guests, servers, printers and IoT devices. IoT devices in particular tend to be unpatched, so giving them a segment that cannot reach the server segment contains a breach. Micro-segmentation takes the idea further, with rules per workload, often in cloud networks via security groups.

Why does this matter? Attackers rarely stop at their first victim. They look for the next machine, a technique called lateral movement (see The Attack Lifecycle and MITRE ATT&CK). Segmentation turns that from a stroll into a series of locked doors, and each blocked connection attempt is a log entry that can raise an alarm.

Zero trust

Traditional design is a castle and moat: strong perimeter, and everyone inside is trusted. It fails when an attacker gets in once through phishing, a stolen VPN login or an infected laptop. Work is also no longer inside one perimeter: staff use cloud services from home networks.

Zero trust replaces "trusted network" with "never trust, always verify". Its core ideas:

  • Verify explicitly: authenticate and authorize every request using identity, device health, location and context, not just the network address.
  • Least privilege: give each user and service the minimum access, for the minimum time (Authorization and Access Control Models).
  • Assume breach: design as if an attacker is already inside, with segmentation, encryption inside the network and thorough logging.
  • Strong identity: multi-factor authentication and phishing-resistant methods (Multi-Factor Authentication and Passkeys).

Zero trust is an approach, not a product you can buy. In practice it means identity-aware proxies in front of applications, device checks, short-lived credentials and fine-grained policies, introduced step by step, starting with the most valuable systems.

Writing a rule engine

The best way to understand first-match evaluation is to implement it. The engine below handles source and destination networks (using CIDR), protocol and port ranges. It is stateless but we will add a small state table afterwards.

Python A first-match firewall rule engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the staff PC trying to reach the database on port 5432: rule 3 does not match (wrong port), rule 4 drops it before the staff browsing rule is reached. Swap those two rules and see what changes. If rule 5 ran first with a looser pattern, the database zone would be exposed, which is the classic ordering bug.

Adding state

A stateful firewall remembers outbound connections and lets replies through. This extension keeps a table keyed by the connection's endpoints:

Python A tiny connection-tracking table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real firewalls also match sequence numbers, time out idle entries and cap the table size, because a flood of fake connections could fill the table and cause a denial of service.

Operating firewalls well

  • Default deny inbound, and deny outbound where practical. Outbound filtering stops malware from calling home on odd ports.
  • Document and review every rule with an owner and a reason. Delete the ones nobody can explain.
  • Test changes in a staging setup or with a rule-testing tool before deployment, and keep configurations in version control.
  • Log denies and send them to a central place for analysis (Logging, Log Analysis and SIEM).
  • Do not rely on a firewall alone. It cannot stop an attack coming through an allowed port, such as a SQL injection over 443, or a user who is fooled by a phishing email.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a first-match rule set, what happens if a broad allow rule sits above a specific deny rule for the same traffic?

    Evaluation stops at the first matching rule. Specific rules must therefore be placed before broader ones.
  2. 2. What does a stateful firewall do that a stateless packet filter cannot?

    The state table links return packets to an existing connection, so replies are allowed without opening the port to unsolicited traffic.
  3. 3. What is the main purpose of a DMZ?

    Public services are the most exposed. Placing them in their own segment behind an inner firewall limits how far a compromise can spread.
  4. 4. Which statement best describes zero trust?

    Zero trust removes implicit trust in network location. Every access decision is made explicitly and with least privilege.

Summary

  • Firewalls evaluate an ordered rule list, first match wins; end with default deny and keep rules narrow and documented.
  • Stateful firewalls track connections so replies pass and unsolicited traffic does not; WAFs and NGFWs add application awareness.
  • Segmentation with a DMZ, VLANs and micro-segmentation contains breaches and slows lateral movement.
  • Zero trust drops implicit trust in the network: verify explicitly, use least privilege and assume breach.
  • A firewall is one layer; it does not stop attacks that arrive over allowed ports.

Next: Common Network Attacks and Defenses, where you'll see what attackers try against these defenses.