Skip to content

Metadata Card

  • Prerequisites: Vol 4 Networking (TCP/IP, HTTP, DNS), Chapter 1 (encryption & TLS)
  • Estimated time: 55 minutes
  • Core difficulty: Advanced
  • Completion mark: Can explain firewall stateful inspection and default deny principle, distinguish IDS from IPS, understand the core assumptions of Zero Trust

Your Progress

You've hardened every aspect of the station itself—input sanitization spells at the application layer, isolation runes at the operating formation layer. But one thing remains: the station is not isolated. It has seven magic courier routes leading to other wizard towers, with magic messengers traveling the routes daily, and cross-tower magical letters flowing through the conduits.

Every layer of the protocol stack has corresponding security issues. Network layer problems are trickier—because you can't control the other towers' code, and you can't even fully confirm whether the Cartesian coordinates of a magical source are real.

You saw the principles of the TCP three-way handshake and IP routing in Vol 4. Now we're going to set up security checkpoints on the same magic courier routes.

Your Task

Master the core defense methods of network security: firewall packet filtering and stateful inspection, VPN tunnels and encryption, IDS/IPS intrusion detection, and the paradigm shift of Zero Trust architecture.

Chapter Layers

  • Required: Firewalls (packet filtering/stateful inspection/NAT/DMZ), VPN (TLS VPN/IPsec)
  • Optional: IDS/IPS rule engines, attack patterns at each OSI layer
  • Advanced: Zero Trust architecture (NIST SP 800-207), SASE, eBPF in network security

Breaking Ground · Tracing the Origin

Problem: The fortress has seven courier routes, and not all travelers on these routes are friendly. How do you know which data packet is from an attacker and which is a normal reconnaissance report?

You can't check every packet against a trusted source IP. The network may pass through thousands of packets per second, so you need automated, rule-based defense facilities.

First Barrier: Firewall

The essence of a firewall is a packet filter—a collection of rules. It's like setting up a defensive line around the fortress, only letting through couriers who meet the entry conditions. The simplest is static packet filtering, checking each packet's source IP, destination IP, port, and protocol:

bash
# Default policy: drop all input packets, allow all output
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Allow return packets of established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow loopback
iptables -A INPUT -i lo -j ACCEPT

# Allow SSH (restrict by IP)
iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT

# Allow HTTP/HTTPS (from anywhere)
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Log and drop everything else
iptables -A INPUT -j LOG --log-prefix "DROPPED: "
iptables -A INPUT -j DROP

Stateful Inspection:

The key line you see above:

bash
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

This is the essence of a stateful firewall—it remembers established connections. When a packet is part of an established connection (ESTABLISHED) or related to one (RELATED, like FTP data connections), it's automatically allowed through. You don't need to write explicit rules for return traffic.

This is why a firewall works: you allow outbound DNS queries (udp/53), and DNS responses are automatically allowed. But if an external party actively sends a DNS query to your machine, it will be denied.

nftables (modern iptables replacement):

bash
# /etc/nftables.conf
table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;

        # Allow established connections
        ct state established,related accept

        # Allow loopback
        iif lo accept

        # Allow SSH
        tcp dport 22 ip saddr 10.0.0.0/8 accept

        # Allow HTTP/HTTPS
        tcp dport {80, 443} accept

        # Allow ICMP (ping)
        icmp type {echo-request, echo-reply} accept
    }
}

NAT and DMZ:

Firewalls don't just do packet filtering; they also do Network Address Translation (NAT):

  • SNAT (Source NAT): Maps internal IPs to a public IP for outbound access. This is the core function of home routers.
  • DNAT (Destination NAT): Maps external requests to a specific public IP:port to an internal server. This is port forwarding.
bash
# DNAT: forward external 8443 to internal web server 192.168.1.10:443
iptables -t nat -A PREROUTING -p tcp --dport 8443 \
  -j DNAT --to-destination 192.168.1.10:443

DMZ (Demilitarized Zone) is a security design pattern:

          ┌──────────┐
  Internet ───┤ Firewall ├─── DMZ (Web servers, mail servers)
               └──────────┘

                    ├─── Internal network (databases, internal apps)

                    └─── Management network (SSH, monitoring)

Servers in the DMZ are exposed to the public internet, but they cannot access the internal network. Even if a web server is compromised, attackers cannot directly access the database. If specific access is needed, the firewall is configured with explicit rules.

Second Barrier: IDS / IPS

Firewalls are based on preset rules—"these are the good guys, these are the bad guys." But some attacks disguise themselves as normal traffic. For example, a SQL injection attack looks like a normal HTTP POST request, just with ' OR 1=1 -- in the body.

IDS (Intrusion Detection System) monitors traffic and alerts on suspicious patterns.

IPS (Intrusion Prevention System) can also actively block in addition to detecting.

FeatureIDSIPS
DeploymentBypass (copy of traffic)Inline (traffic passes through)
Latency impactNoYes (adds latency)
False positive impactGenerates alertsBlocks legitimate traffic
Update strategyMore relaxedNeeds more reliable rules

Snort Rule Example:

Snort is the most popular open-source IDS/IPS engine. A sample Snort rule:

# Alert on SQL injection attempts
alert tcp $EXTERNAL_NET any -> $HTTP_SERVERS $HTTP_PORTS
  (msg:"SQL Injection - UNION SELECT";
   content:"UNION"; nocase;
   content:"SELECT"; nocase;
   distance:0;
   pcre:"/UNION\s+SELECT/i";
   sid:1000001;
   rev:1;)

Explanation:

  • This rule checks TCP traffic to and from HTTP servers
  • Looks for payloads containing "UNION" + "SELECT" patterns
  • Uses the regex UNION\s+SELECT for precise matching
  • Alerts on match

Detection Methods:

MethodPrincipleAdvantageDisadvantage
Signature-basedMatch known attack signaturesHigh accuracy, good performanceCan't detect unknown attacks (zero-day)
Anomaly-basedEstablish baseline, alert on deviationCan find unknown attacksHigh false positive rate
Protocol analysisCheck conformance to protocol specsCan find protocol-level attacksRequires deep protocol parsing

Third Barrier: VPN

VPN (Virtual Private Network) solves two core problems:

  1. Communication security: Establishing encrypted tunnels over insecure links
  2. Network reachability: Making remote nodes appear as if they're on the same local network
┌─────────┐    Encrypted Tunnel     ┌─────────┐
│ Remote   │─────║═══════║──────│   Fortress   │
│ Outpost  │     ║  VPN  ║      │ Headquarters  │
│ (VPN     │     ╚═══════╝      │ (VPN Gateway)│
│  Client) │                    │              │
└─────────┘                    └─────────┘

                   Internet

Three Main VPN Implementations:

TypeProtocolAdvantagesDisadvantages
TLS VPNOpenVPN, WireGuardApplication layer, flexible, good for remote accessSlightly complex for site-to-site
IPsec VPNIKEv2 + ESP/AHNetwork layer, good for site-to-siteComplex configuration, MTU issues
WireGuardNoise protocol frameworkSmall codebase (4000 lines), high performance, simple configNewer, smaller ecosystem

WireGuard (as a modern VPN representative):

WireGuard's design philosophy is completely different from traditional VPNs—it's only 4000 lines of code (compared to OpenVPN's hundreds of thousands), uses the latest cryptographic primitives (Curve25519, ChaCha20, BLAKE2s), and is extremely simple to configure. Imagine you want to dig an encrypted tunnel between a remote outpost and headquarters—WireGuard does it in the simplest way:

bash
# Server config (/etc/wireguard/wg0.conf)
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = <server-private-key>

# Allow forwarding
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT

# Client (remote outpost)
[Peer]
PublicKey = <client-public-key>
AllowedIPs = 10.0.0.2/32

# Client config (/etc/wireguard/wg0.conf)
[Interface]
Address = 10.0.0.2/24
PrivateKey = <client-private-key>

[Peer]
PublicKey = <server-public-key>
Endpoint = borderfortress.com:51820
AllowedIPs = 10.0.0.0/24, 192.168.1.0/24
PersistentKeepalive = 25

After startup, the remote outpost can directly access the fortress headquarters' 192.168.1.x resources via 10.0.0.2. All traffic is encrypted through the UDP tunnel.

bash
# Start WireGuard
wg-quick up wg0

# View status
wg show

# Example output:
# interface: wg0
#   public key: ...
#   private key: (hidden)
#   listening port: 51820
# peer: <client-public-key>
#   endpoint: 203.0.113.5:45678
#   allowed ips: 10.0.0.2/32
#   latest handshake: 1 minute ago
#   transfer: 1.2 MiB received, 3.4 MiB sent

Fourth Barrier: Zero Trust Architecture

Traditional network security relies on one core assumption: "The internal network is safe; the outside is dangerous."

This line of defense is called the Castle-and-Moat model—you have a strong outer wall (firewall), and everything inside the wall is trusted.

But this model has been proven insufficient in the 2020s:

  • Attackers gain internal network access via phishing emails and can move laterally inside
  • Cloud services and remote work make the "internal/external" boundary unclear
  • Zero-day exploits can penetrate perimeter defenses

Zero Trust core principles:

Never Trust, Always Verify

NIST SP 800-207 defines seven core principles for Zero Trust architecture:

  1. All data sources and computing services are resources. Every device, every flow must be verified.
  2. All communications must be encrypted. Whether internal or external.
  3. Authorize per session. Not "logged in = access all resources"; each request is authorized individually.
  4. Dynamic access policies. Assess based on user identity, device state, location, time, and other dimensions.
  5. Monitor all resource access. Audit all traffic, detect anomalous behavior.
  6. Least privilege. Users and processes get only the minimum permissions needed.
  7. Network location does not equal trust. A request coming from inside the network is not automatically allowed.

Zero Trust in Practice: Micro-segmentation

Traditional firewalls protect the data center perimeter. Under Zero Trust, Micro-segmentation shrinks the security boundary to each workload:

yaml
# Kubernetes NetworkPolicy example (micro-segmentation)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: patrol-api-policy
spec:
  podSelector:
    matchLabels:
      app: patrol-api
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: patrol-db
    ports:
    - protocol: TCP
      port: 5432

This policy says:

  • Only pods with the frontend label can access patrol-api on port 8080
  • patrol-api can only access patrol-db on port 5432
  • All other traffic is denied

—No need to configure firewall rules or declare internal/external boundaries. Each service only knows the other service it needs to communicate with.


Common Pitfalls

  • "Firewalls can detect all attacks." Firewalls can only match known rules. Attacks within encrypted traffic (HTTPS) can't be detected by firewalls—they need TLS decryption (Decryption/MITM) to see the payload.
  • Forgetting the default deny principle. "Allow what I know, deny everything else" should be the last rule. If you only write "allow SSH, HTTP" and forget the default deny, you might as well have no firewall.
  • VPN tunnel exists, but other traffic doesn't go through it. You configured the VPN, but DNS requests, IPv6 traffic might go through the physical interface (VPN split-tunnel configuration). Confirm all traffic goes through the encrypted tunnel.
  • IDS false positives cause operator fatigue. If the IDS generates thousands of alerts daily, real attacks get lost in the noise. Regularly adjust rules and establish alert severity levels.
  • Using traditional firewalls in peer-to-peer network environments. In Kubernetes or multi-cloud environments, traditional network firewalls can't effectively control service-to-service traffic. Need micro-segmentation or service mesh (like istio's mTLS + authorization).
  • Sending plaintext internally after TLS termination. The load balancer decrypts TLS and sends plaintext HTTP to the backend. If an attacker performs ARP spoofing on the internal network, they can see all requests. Ensure backend communication also uses TLS (end-to-end TLS).

Pass Challenges

  • Warm-up: On your development machine, use iptables -L -n -v to view current firewall rules. Understand the counters (packets / bytes) for each rule—can you see which rules are frequently hit?
  • Challenge: Use Vagrant or Docker Compose to set up a small network topology: an "external client," a "firewall," and an "internal server." Configure NAT and port forwarding on the firewall so that the external client can only access the internal server through specific firewall ports.
  • Observe: Use tcpdump -i any -n port 53 to observe your machine's DNS queries. How does the firewall allow the DNS query and response interaction? Use Wireshark's follow UDP stream feature to inspect.
  • Troubleshoot: A remote outpost can ping the headquarters server (10.0.0.1) over WireGuard VPN, but can't access the headquarters' HTTP service (192.168.1.10:80). Diagnose possible causes (routing config? iptables FORWARD policy? IP forwarding disabled?).

Traveler's Notes

  • Firewalls are the network's first line of defense: IP/port-based stateful inspection (default deny)
  • IDS detects intrusions (bypass), IPS prevents intrusions (inline); both need continuously updated rules
  • VPN establishes encrypted tunnels over insecure networks: WireGuard is a modern, simple, efficient choice
  • Zero Trust architecture abandons the "internal network is safe" assumption, requiring verification for every request by default
  • Micro-segmentation shrinks the security boundary from the data center to each workload

Next Stop Preview

With network defenses in place, let's pull the perspective back to the engineering process itself. Security isn't an ops patch; it should be embedded throughout the full development lifecycle. Next chapter, we look at how the Security Development Lifecycle (SDL) is done.

Built with VitePress | Software Systems Atlas