Skip to content
← pwnsy/blog
beginner20 min readMar 6, 2026Updated Mar 11, 2026

What Is a Firewall and How Does It Protect You?

network-security#firewall#network-security#packet-filtering#ids#defense-in-depth

Key Takeaways

  • A firewall sits between two or more network segments and makes a binary decision on each unit of traffic: allow it through or drop it.
  • Packet-filter firewalls are the simplest and oldest type.
  • Stateful firewalls add connection tracking to packet filtering.
  • Application-layer firewalls, also called proxy firewalls, operate at Layer 7.
  • NGFW is a marketing term coined by Gartner in 2003, but the underlying capabilities are real.
  • A WAF is a specialized application-layer firewall positioned in front of HTTP/HTTPS applications.

In August 2016, a hacker group calling itself "The Shadow Brokers" released a collection of NSA cyberweapons. Among them: EXTRABACON, an exploit targeting a zero-day in the authentication bypass of Cisco ASA firewalls. EXTRABACON allowed unauthenticated remote code execution on tens of thousands of Cisco ASA devices — firewalls deployed specifically to protect networks from remote code execution.

That is the first uncomfortable truth about firewalls: they are themselves complex systems running code, and they can be compromised. The second uncomfortable truth: even a perfectly functioning firewall only enforces the policy you write. A misconfigured firewall — or one running a default-allow ruleset that nobody has reviewed in three years — provides weaker protection than no firewall at all, because it creates a false sense of security.

Understanding how firewalls actually work — at the packet level, at the application layer, in the context of modern threats — is necessary before you can configure one correctly or evaluate whether one is doing its job.

What a Firewall Actually Does

A firewall sits between two or more network segments and makes a binary decision on each unit of traffic: allow it through or drop it. That decision is made by matching traffic against an ordered list of rules. Rules are evaluated top to bottom; the first match wins. Traffic that reaches the end of the ruleset without matching anything hits the default policy, which should always be deny.

[External Network] → [Firewall] → [Internal Network]

For each packet:
1. Check rule 1 → match? → ACCEPT
2. Check rule 2 → match? → DROP
3. Check rule 3 → match? → ACCEPT
4. ...
N. No rule matched → Default policy → DROP (correct) or ACCEPT (wrong)

The scope of what a firewall can inspect — and therefore what its rules can be based on — depends entirely on what layer of the network stack it operates at. This is the fundamental axis that distinguishes firewall types.

Layer 3/4: Packet-Filter Firewalls

Packet-filter firewalls are the simplest and oldest type. They inspect individual packets and make allow/deny decisions based on network-layer and transport-layer fields:

  • Source IP address (192.168.1.100)
  • Destination IP address (203.0.113.10)
  • Protocol (TCP, UDP, ICMP)
  • Source port (49532)
  • Destination port (443)

They are stateless — each packet is evaluated in isolation with no memory of previous packets. This creates exploitable blind spots.

What Stateless Means in Practice

Consider a server running an HTTPS web service. To allow inbound web traffic, you write:

# Allow inbound HTTPS
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

This works for traffic reaching the server. But outbound response traffic — the TCP replies from port 443 to the client's high-numbered ephemeral port — also needs to be allowed. With stateless filtering, you are forced to write:

# Allow outbound return traffic (high-numbered ports)
iptables -A OUTPUT -p tcp --sport 443 -j ACCEPT
# Or even worse:
iptables -A INPUT -p tcp --sport 443 -j ACCEPT  # For returns on the INPUT chain

The --sport 443 rule means "allow all inbound TCP from source port 443." An attacker who crafts TCP packets with source port 443 (trivial with tools like nmap -g 443 or hping3 --baseport 443) bypasses this rule, because the firewall sees "source port 443" and allows it, regardless of what the packet actually is.

# Attacker bypasses the "allow return traffic" rule with source port spoofing
nmap -g 443 -sS TARGET-IP  # Use port 443 as source port
hping3 --baseport 443 --scan 1-1024 TARGET-IP  # Port scan from spoofed source port

This is why stateless packet filtering is insufficient as a standalone control for any network handling real traffic.

Classic iptables Packet Filtering

Despite its limitations, iptables remains the tool for quick IP-based blocking:

# Block all traffic from a specific IP (blocklist-style)
iptables -I INPUT 1 -s 45.33.32.156 -j DROP
 
# Block a country's IP range (requires ipset for performance)
apt-get install -y ipset
ipset create BLOCKED_COUNTRY hash:net
# Add the IP ranges — obtain from MaxMind, ip2location, or ipdeny.com
ipset add BLOCKED_COUNTRY 5.45.0.0/17
ipset add BLOCKED_COUNTRY 5.61.0.0/16
# ... (automated via a script in practice)
 
iptables -I INPUT -m set --match-set BLOCKED_COUNTRY src -j DROP
 
# Rate limit new connections (basic DoS mitigation)
iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW \
  -m limit --limit 60/min --limit-burst 100 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW -j DROP
 
# View current rules with packet and byte counters
iptables -L -v -n --line-numbers

The performance concern with iptables at scale: iptables rules are processed linearly. A ruleset with 10,000 rules evaluates every rule for every packet until it finds a match. For large blocklists, ipset with hash tables provides O(1) lookups regardless of set size — no rule-count performance degradation.

Layer 4+: Stateful Firewalls (Connection Tracking)

Stateful firewalls add connection tracking to packet filtering. The firewall maintains a state table (also called a connection tracking table) that records active network connections:

State Table Entry:
  Source:      192.168.1.100:49532
  Destination: 203.0.113.10:443
  Protocol:    TCP
  State:       ESTABLISHED
  Sequence:    [seq numbers verified]
  Last seen:   [timestamp]
  Timeout:     300s

When a new packet arrives:

  1. Look it up in the state table first
  2. If there is a matching entry in ESTABLISHED state → allow immediately (no ruleset traversal)
  3. If no matching entry → evaluate against the ruleset as a new connection

This eliminates the return-traffic blind spot. An inbound TCP packet on port 49322 is only permitted if the state table shows that this host initiated an outbound connection that received this packet as a reply. An attacker cannot inject packets into a session they are not party to, because the firewall verifies TCP sequence numbers against the state table.

nftables: The Modern Linux Standard

nftables is the replacement for iptables in all modern Linux distributions. It has a cleaner syntax, better performance for large rulesets, and is the tool you should be using for new deployments:

# /etc/nftables.conf — production-grade stateful firewall
# This is a realistic baseline for a Linux web server
 
flush ruleset
 
table inet filter {
    # Connection state table — managed by the kernel
    # We reference it with ct state (connection tracking state)
 
    chain input {
        type filter hook input priority filter; policy drop;
 
        # CRITICAL: This rule handles ALL return traffic for outbound connections
        # Without this, the server cannot receive responses to its own requests
        ct state established,related accept
 
        # Drop packets with invalid connection state
        # (fragmented, malformed, out-of-window TCP segments)
        ct state invalid drop
 
        # Loopback interface — always allow
        iifname "lo" accept
 
        # ICMP — allow but rate limit to prevent flood
        # Rate: 10 packets/second per source IP
        ip protocol icmp limit rate 10/second accept
        ip6 nexthdr icmpv6 limit rate 10/second accept
 
        # SSH — management access from specific subnets only
        # NEVER open SSH to 0.0.0.0/0 on an internet-facing server
        ip saddr 10.10.0.0/24 tcp dport 22 ct state new accept
        ip saddr 203.0.113.50/32 tcp dport 22 ct state new accept  # Office IP
 
        # Web services — public access
        tcp dport {80, 443} ct state new accept
 
        # Monitoring — from internal network only
        ip saddr 10.0.0.0/8 tcp dport {9100, 9090} ct state new accept
 
        # Log dropped packets with rate limiting (prevents log flooding)
        limit rate 5/second burst 20 packets log prefix "nftables DROP: " flags all
 
        # Default drop (policy above handles this, explicit is clearer)
        drop
    }
 
    chain forward {
        type filter hook forward priority filter; policy drop;
        # This server does not route between segments
        # If it did, add explicit rules here
    }
 
    chain output {
        type filter hook output priority filter; policy accept;
        # Consider restricting output for hardened servers:
        # ct state established,related accept
        # tcp dport {80, 443, 53} accept  # Web + DNS
        # udp dport 53 accept             # DNS
        # drop                            # Block unexpected outbound
    }
}

Apply the configuration:

# Validate syntax before applying (won't activate the rules, just checks them)
nft -c -f /etc/nftables.conf
 
# Apply rules
nft -f /etc/nftables.conf
 
# Enable persistent across reboots
systemctl enable --now nftables
 
# Monitor rule hit counts (how many packets matched each rule)
nft list ruleset -a | grep -E "packets|bytes"
 
# Watch firewall drops in real time
journalctl -f -k | grep "nftables DROP"
 
# Save current ruleset
nft list ruleset > /etc/nftables.conf.backup

State Table Attack: SYN Flood

The state table is also an attack surface. SYN floods target it directly by sending millions of SYN packets with spoofed source IPs. The firewall creates a state table entry for each SYN, waiting for the SYN-ACK/ACK to complete the handshake. The spoofed source never responds. The table fills. Legitimate connections are rejected.

SYN cookies make the firewall's state tracking optional for the initial handshake:

# Enable SYN cookies at the OS level (prevents state table exhaustion)
# This applies to the server's TCP stack, complementing the firewall
echo "net.ipv4.tcp_syncookies = 1" >> /etc/sysctl.conf
echo "net.ipv4.tcp_max_syn_backlog = 65536" >> /etc/sysctl.conf
echo "net.ipv4.tcp_synack_retries = 2" >> /etc/sysctl.conf
sysctl -p
 
# Add SYN rate limiting in nftables
# Limit new TCP connections to 1000 per second, burst 5000
nft add rule inet filter input \
  tcp flags syn \
  ct state new \
  limit rate over 1000/second burst 5000 packets \
  drop

Layer 7: Application-Layer Firewalls

Application-layer firewalls, also called proxy firewalls, operate at Layer 7. Instead of passing traffic through, they terminate the connection from the client, inspect the application-layer content, and — if policy allows — establish a new connection to the destination.

Because the firewall fully parses the application protocol (HTTP, DNS, SMTP, FTP), it can make decisions based on application content, not just addressing:

  • Allow HTTP GET to example.com but block POST
  • Block DNS queries for specific domains
  • Strip executable attachments from email
  • Allow HTTPS traffic only if the TLS certificate chain is valid

The trade-off is significant: full protocol parsing is expensive in CPU and latency, and a separate proxy component is needed for each protocol. The firewall must also handle TLS decryption if it needs to inspect encrypted traffic.

TLS Inspection: The Man-in-the-Middle Architecture

Normal HTTPS connection:
Client ←→ [Direct TLS] ←→ Server
Client trusts server's certificate

TLS Inspection:
Client ←→ [TLS Session 1] ←→ Firewall ←→ [TLS Session 2] ←→ Server
Client trusts TLS Session 1 because firewall's CA cert is trusted (via group policy)
Firewall decrypts, inspects, re-encrypts

Setting up TLS inspection in a corporate environment requires:

  1. A certificate authority (CA) that the firewall controls
  2. The firewall's CA certificate distributed to all endpoints (via Active Directory GPO, MDM, or manual installation)
  3. Handling of certificate pinning (apps that hardcode a specific certificate will fail — typically banking apps, Signal, some Google services)
  4. Legal review of whether TLS inspection is permissible for your use case and jurisdiction

The security risk of TLS inspection: the firewall's private key, if compromised, allows decryption of all traffic the firewall has inspected. This makes the firewall a high-value target. The key must be stored in an HSM with strictly limited access.

Next-Generation Firewalls: Beyond Port-Based Policy

NGFW is a marketing term coined by Gartner in 2003, but the underlying capabilities are real. The differentiating features are not defined by price — evaluate specific capability claims.

Application Awareness: Identifying Traffic Beyond Port

The fundamental premise of port-based firewall policy broke down when applications started running on arbitrary ports, particularly 80 and 443. Today:

  • An NGFW can identify Slack, Zoom, Teams, and 3,000 other applications by their traffic fingerprint — TLS SNI, protocol patterns, certificate characteristics
  • It can allow "HTTPS to Microsoft 365" while blocking "HTTPS to anonymous file sharing sites" — even though both use port 443
  • It can detect Tor browser, cryptocurrency mining, and C2 beacons using port 443 — patterns that are invisible to a port-based firewall

Application-level policy examples (Palo Alto Networks syntax for illustration):

# Allow specific applications, not ports
security policy "Allow-Business-SaaS" {
    application ["office365" "salesforce" "slack" "zoom"]
    service application-default
    action allow
}

# Block high-risk categories regardless of port
security policy "Block-High-Risk" {
    application ["tor" "bittorrent" "freegate" "ultrasurf"]
    service any
    action drop
    log-end yes
}

# Granular: allow Dropbox for finance team only
security policy "Dropbox-Finance-Only" {
    source-user ["finance-team@company.com"]
    application ["dropbox"]
    action allow
}

User-Identity Integration

Traditional firewalls write rules against IP addresses. NGFWs integrate with Active Directory or an identity provider to write rules against user accounts or groups.

Why this matters: a laptop assigned 192.168.1.100 today might have a different IP tomorrow. A user account does not change. Rules like "allow Finance group to access ERP server on port 5000" survive IP changes without rule updates.

The integration uses WMI probing (Windows) or RADIUS accounting to map usernames to IP addresses as they log in. The firewall's policy engine references these mappings in real time.

Integrated IPS and Threat Intelligence

An NGFW with IPS applies Snort/Suricata-equivalent signature matching inline — blocking traffic that matches exploit signatures rather than just alerting. Combined with regularly updated threat intelligence feeds (blocking known-malicious IPs, domains, and file hashes), this provides detection capabilities that pure packet filtering cannot.

The operational consideration: inline IPS with aggressive rulesets generates false positives. A legitimate application that behaves similarly to a signature pattern gets blocked. Start with detection mode, tune the ruleset against your traffic baseline, then enable blocking.

Web Application Firewalls: HTTP-Specific Defense

A WAF is a specialized application-layer firewall positioned in front of HTTP/HTTPS applications. It inspects:

  • HTTP methods and versions
  • URL paths and query parameters
  • Cookie values and headers
  • POST body content
  • Response headers and content

And blocks patterns associated with:

  • SQL injection
  • Cross-site scripting (XSS)
  • Remote and local file inclusion
  • Server-side request forgery (SSRF)
  • Command injection
  • Protocol-level abuse (HTTP request smuggling)

ModSecurity with OWASP CRS: The Open-Source Standard

ModSecurity is the most widely deployed open-source WAF. Combined with the OWASP Core Rule Set (CRS), it provides comprehensive protection against OWASP Top 10 attacks.

# Install ModSecurity with nginx on Ubuntu
apt-get install -y nginx libnginx-mod-modsecurity
 
# Download OWASP Core Rule Set
git clone https://github.com/coreruleset/coreruleset.git /etc/nginx/owasp-crs
cp /etc/nginx/owasp-crs/crs-setup.conf.example /etc/nginx/owasp-crs/crs-setup.conf
 
# ModSecurity configuration
cat > /etc/nginx/modsec/main.conf << 'EOF'
# Load ModSecurity configuration
Include /etc/nginx/modsec/modsecurity.conf
 
# Set detection mode first — analyze logs before blocking
SecRuleEngine DetectionOnly
 
# Enable request/response body inspection
SecRequestBodyAccess On
SecResponseBodyAccess On
SecResponseBodyMimeType text/plain text/html text/xml application/json
 
# Audit log for all blocked requests
SecAuditLog /var/log/nginx/modsec_audit.log
SecAuditLogType Concurrent
SecAuditLogParts ABIJDEFHZ
SecAuditLogRelevantStatus "^(?:5|4(?!04))"
 
# Load OWASP CRS
Include /etc/nginx/owasp-crs/crs-setup.conf
Include /etc/nginx/owasp-crs/rules/*.conf
EOF
# /etc/nginx/sites-enabled/your-app.conf
server {
    listen 443 ssl http2;
    server_name your-app.com;
 
    # Enable ModSecurity
    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;
 
    location / {
        proxy_pass http://backend:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Testing your WAF (legitimate test — does not attack anything):

# Test SQL injection detection
curl "https://your-app.com/api/users?id=1' OR '1'='1"
# Should return 403 Forbidden (or be logged in DetectionOnly mode)
 
# Test XSS detection
curl "https://your-app.com/search?q=<script>alert(1)</script>"
# Should be blocked
 
# Test directory traversal
curl "https://your-app.com/download?file=../../../../etc/passwd"
# Should be blocked
 
# Check ModSecurity audit log for what was detected
tail -f /var/log/nginx/modsec_audit.log | grep -A5 "BLOCKED\|[SQL\|XSS]"

Tuning to Reduce False Positives

The OWASP CRS operates on an anomaly scoring system. Each rule that triggers adds a score. A request is blocked when the total score exceeds a threshold (default: 5 for inbound, 4 for outbound):

# In /etc/nginx/owasp-crs/crs-setup.conf
 
# Paranoia Level 1-4 (higher = more rules = more false positives)
# Start with 1, increase gradually
SecAction \
  "id:900000,\
   phase:1,\
   nolog,\
   pass,\
   t:none,\
   setvar:tx.paranoia_level=1"
 
# Anomaly scoring thresholds
SecAction \
  "id:900110,\
   phase:1,\
   nolog,\
   pass,\
   t:none,\
   setvar:tx.inbound_anomaly_score_threshold=5,\
   setvar:tx.outbound_anomaly_score_threshold=4"

When legitimate application behavior triggers a CRS rule, you can add exceptions:

# Exception: Allow a specific legitimate parameter that triggers a rule
# Use this ONLY for well-understood false positives
SecRuleUpdateTargetById 942100 "!ARGS:legitimate_param_name"
 
# Disable a rule that generates too many false positives for your app
SecRuleRemoveById 942100
 
# Allow a specific URL to bypass WAF inspection entirely (for file uploads, etc.)
location /api/upload {
    modsecurity off;  # Disable WAF for this endpoint only
    proxy_pass http://backend:3000;
}
Warning

A WAF is a defense-in-depth layer. It is not a substitute for secure code. A skilled attacker given time and the ability to probe the WAF will find bypass techniques — especially against signature-based rules. Fix the SQL injection vulnerability in your code. Run the WAF as a detection layer and to catch opportunistic exploitation of vulnerabilities you have not yet discovered.

Host-Based Firewalls vs. Network-Based Firewalls

Network-based firewalls sit at a network boundary — a physical appliance or virtual instance between segments. They protect multiple hosts and are transparent to those hosts. The limitation: they only see traffic crossing the boundary. Traffic between two hosts on the same VLAN, same switch, same network segment — east-west traffic — never crosses the perimeter firewall. An attacker who compromises a workstation and attempts to lateral-move to a database server on the same VLAN bypasses the perimeter firewall entirely.

Host-based firewalls run on the individual endpoint — Windows Defender Firewall, Linux nftables, macOS pf. They enforce policy on all traffic entering and leaving that specific host, regardless of where the traffic originates. They see east-west traffic. They protect against lateral movement from compromised hosts on the same network segment.

The Wannacry ransomware outbreak in May 2017 spread through networks primarily via lateral movement using EternalBlue (MS17-010, an SMB vulnerability). Organizations with host-based firewalls blocking SMB traffic between workstations limited the spread. Organizations with only perimeter firewalls watched workstations on the same segment encrypt each other.

The correct answer is both. The complementary coverage:

| Scenario | Network Firewall | Host Firewall | |---|---|---| | External attack via internet | Blocks at perimeter | Backup if perimeter fails | | Lateral movement within segment | Does not see it | Blocks based on per-host policy | | Compromised endpoint with tampered firewall | Still controls segment boundary | May be disabled by attacker | | Portable device on untrusted network | Not present | Still enforces policy |

Windows Defender Firewall: Corporate Configuration

# Set default policies: block inbound, allow outbound
Set-NetFirewallProfile -Profile Domain,Public,Private -DefaultInboundAction Block -DefaultOutboundAction Allow
 
# Allow Remote Desktop only from management subnet
New-NetFirewallRule `
  -DisplayName "RDP - Management Only" `
  -Direction Inbound `
  -Protocol TCP `
  -LocalPort 3389 `
  -RemoteAddress "10.10.0.0/24" `
  -Action Allow
 
# Block SMB from non-domain-controller addresses (limits Wannacry-style spread)
# Allow SMB only from file servers and domain controllers
New-NetFirewallRule `
  -DisplayName "Block SMB from Non-DC" `
  -Direction Inbound `
  -Protocol TCP `
  -LocalPort 445 `
  -RemoteAddress "!10.10.10.5,!10.10.10.6"  # DC IPs only `
  -Action Block
 
# Audit all blocked connections (essential for incident investigation)
Set-NetFirewallProfile -LogBlocked True -LogFileName %systemroot%\system32\LogFiles\Firewall\pfirewall.log
 
# Prevent local admins from modifying firewall policy (GPO enforcement)
# This requires Group Policy, not PowerShell:
# Computer Configuration > Windows Settings > Security Settings >
# Windows Firewall with Advanced Security > Properties > Settings >
# Set "Apply local firewall rules" to No

macOS pf Firewall

# /etc/pf.conf — macOS packet filter configuration
 
# Define interfaces
ext_if = "en0"          # External interface (ethernet or WiFi)
vpn_if = "utun0"        # VPN tunnel interface
 
# Loopback — always allow
pass on lo0
 
# Block all inbound by default
block in on $ext_if
 
# Allow established outbound connections to receive responses
pass out on $ext_if proto tcp modulate state
pass out on $ext_if proto udp keep state
 
# Allow SSH only from specific IP (change to your management IP)
pass in on $ext_if proto tcp from 203.0.113.50 to any port 22
 
# Allow VPN traffic
pass in on $vpn_if from any to any
 
# Enable pf
pfctl -ef /etc/pf.conf
 
# Check status
pfctl -s info
pfctl -s rules

Common Firewall Misconfigurations and How to Audit Them

Default-Allow Outbound

The single most exploited gap in perimeter defenses. Malware, ransomware C2 beacons, and data exfiltration all need outbound connectivity. A firewall that allows all outbound provides no impedance to post-exploitation activities.

Auditing your current outbound policy:

# On Linux: view current outbound rules
nft list chain inet filter output
 
# If this returns just "policy accept" with no rules, you have default-allow outbound
# This is wrong for any production server
 
# Correct outbound policy for a web server:
nft flush chain inet filter output
nft add chain inet filter output { policy drop \; }
nft add rule inet filter output ct state established,related accept  # Return traffic
nft add rule inet filter output ip daddr 1.1.1.1 udp dport 53 accept  # DNS to Cloudflare
nft add rule inet filter output ip daddr 8.8.8.8 udp dport 53 accept  # DNS to Google
nft add rule inet filter output tcp dport {80, 443} accept  # Outbound web
nft add rule inet filter output tcp dport 25 ip daddr MAIL-RELAY-IP accept  # SMTP to mail relay
# Drop everything else outbound
nft add rule inet filter output drop

Rule Accumulation

Enterprise firewalls accumulate rules over years. Rules are added for contractors, projects, temporary requirements — and never removed. After a few years, most enterprise firewalls have hundreds of rules that nobody can explain.

# Find rules that have never matched any traffic
# (zero packet count = never used)
iptables -L -v -n | awk '$1 == "0" {print NR": "$0}' | head -30
 
# In nftables with counters:
nft list ruleset -a | grep -B2 "packets 0 bytes 0" | grep -v "^--$"
 
# Audit script: list all rules and query team for business justification
# Schedule this as a quarterly review process
nft list ruleset > /tmp/current-rules-$(date +%Y%m%d).txt
# Compare with previous quarter:
diff /tmp/current-rules-PREVIOUS.txt /tmp/current-rules-$(date +%Y%m%d).txt

Overly Broad Rules

# These are signs of overly broad rules — audit and tighten each one:
 
# BAD: Allow all traffic from a /8 when you only need a /32
iptables -A INPUT -s 10.0.0.0/8 -j ACCEPT
# Better: specify the actual IP
iptables -A INPUT -s 10.10.0.5/32 -j ACCEPT
 
# BAD: Allow all traffic on a port without state tracking
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Better: only allow new and established connections
iptables -A INPUT -p tcp --dport 443 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
 
# BAD: Allow a large port range
iptables -A INPUT -p tcp --dport 1024:65535 -j ACCEPT
# This was done to allow return traffic — use stateful tracking instead
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Management Interface Exposure

Shodan, a search engine for internet-connected devices, indexes firewall admin interfaces. The query product:"Cisco ASA" returns thousands of Cisco firewall admin panels accessible from the internet. The query http.title:"Palo Alto" finds Palo Alto management interfaces. Firewall vendors routinely release critical vulnerabilities in their management interfaces — PAN-OS CVE-2024-3400 (CVSS 10.0, April 2024), Fortinet CVE-2024-21762 (CVSS 9.6, February 2024), Cisco ASA CVE-2023-20269.

# Verify your firewall management interface is not internet-accessible
# Check from an external IP (or use an online port scanner)
nmap -sV -p 443,4443,8443,8080,8888 YOUR-FIREWALL-PUBLIC-IP
 
# The only correct answer: all management ports should return filtered/closed
# Management access should require:
# 1. VPN connection to the management network
# 2. Or a dedicated out-of-band management interface on a physically separate network
# 3. Never direct internet access
 
# If you find management ports exposed:
# Immediate remediation: firewall rule blocking those ports from internet
iptables -I INPUT 1 -p tcp --dport 443 -s ! MANAGEMENT-IP -j DROP
# This is a temporary fix — proper fix is network architecture change

Firewall Placement: Defense in Depth

A single firewall protecting a flat network provides one opportunity to stop an attacker. Once through, the attacker has unrestricted access to everything. Defense in depth means multiple enforcement points, each limiting the blast radius of the previous layer failing.

Internet
   ↓
[Perimeter Firewall/NGFW]
   ↓
DMZ (web servers, load balancers, mail gateway)
   ↓
[Internal Firewall]
   ↓
Internal Network
├── [Segmentation Firewalls between VLANs]
├── Application Servers ← [Host Firewall on each server]
├── Database Servers    ← [Host Firewall on each server]
└── Workstations        ← [Windows Defender Firewall / OS firewall]
   ↓
[WAF in front of all HTTP applications]

Each layer:

  • Perimeter NGFW: Blocks inbound threats from internet, enforces egress policy for outbound C2 and data exfiltration
  • Internal firewall: DMZ servers (which face the internet directly) cannot initiate connections to internal servers — prevents compromise of DMZ server from becoming compromise of internal network
  • Segmentation firewalls: Application tier can query database tier on specific ports; workstations cannot query database directly
  • Host firewalls: Catch lateral movement within segments; protect servers that have been moved or are behind a shared firewall

Testing Your Firewall Configuration

# From the internet (use a VPS or cloud instance for external testing):
# Test that only expected ports are open
nmap -sS -sU -p 1-65535 --max-retries 1 YOUR-PUBLIC-IP 2>&1 | grep "open"
# Expected: only 80, 443 (and perhaps 22 if intentional)
 
# Test management interface is not reachable
nmap -sS -p 22,443,4443,8080,8443 FIREWALL-MANAGEMENT-IP
# Expected: all filtered/closed from internet-sourced test
 
# From inside DMZ (simulate compromised DMZ server):
# Verify cannot reach internal database directly
nc -zv DATABASE-INTERNAL-IP 5432  # Should fail — connection refused
nc -zv DATABASE-INTERNAL-IP 3306  # Should fail
 
# Test that internal firewall policy is enforced
# From workstation:
telnet APPLICATION-SERVER 8080     # Should succeed (if policy allows)
telnet DATABASE-SERVER 5432        # Should fail (if policy denies workstation→database)
 
# Verify firewall logging is working
# Attempt a blocked connection, then check logs
nc -zv DATABASE-SERVER 5432
grep "DROPPED" /var/log/syslog | tail -5  # Should show the blocked attempt
Note

Schedule firewall ruleset reviews quarterly at minimum. Each review should include: removing rules whose business justification cannot be articulated, tightening broad source/destination ranges, verifying management interfaces are not internet-exposed, and confirming default-deny policy is in place on all chains. Treat the firewall ruleset as code — version control it in Git, require peer review for changes, and document the business justification for each rule.

Summary: Choosing and Configuring the Right Firewall

| Type | What It Sees | Best Use Case | Limitation | |---|---|---|---| | Packet filter | IP, port, protocol | Coarse blocking, upstream filtering | Stateless; bypassable | | Stateful | Connection state + above | Server and network perimeter | Layer 7 content invisible | | NGFW | Application, user identity, TLS content | Enterprise perimeter, egress control | Complex; TLS inspection risks | | WAF | HTTP headers, body, parameters | In front of web applications | Only HTTP/HTTPS | | Host-based | All traffic to/from this host | East-west protection, portable devices | Can be disabled by attacker |

Every production network should run:

  • A stateful firewall (at minimum) at every segment boundary
  • Host-based firewalls on every endpoint (server and workstation)
  • A WAF in front of every HTTP application accessible from untrusted networks

The rules matter more than the hardware. A misconfigured NGFW costing $100,000 provides weaker protection than a correctly configured nftables ruleset on a $5 VPS. Audit rulesets regularly. Enforce default-deny. Log all denied traffic. And never mistake a firewall for a complete security solution — it is one control among several that must work together.

Sharetwitterlinkedin

Related Posts