Firewalls and ACLs
From packet filters to next-generation firewalls: how network access control works, how rules are evaluated, and how to design a zone-based security architecture that actually holds.
The First Firewall: A Packet Filter in a Crisis
A firewall is a network security device that monitors and controls incoming and outgoing traffic based on predefined rules. The word comes from the fireproof wall in a building that prevents a fire from spreading between compartments. The network analogy: a firewall prevents threats from spreading from untrusted zones (the internet) to trusted zones (the internal network).
Firewalls have evolved through four distinct generations over 35 years. Understanding each generation — what problem it solved and what it left unsolved — explains why modern NGFWs are designed the way they are.
ACLs: The Building Block of All Access Control
ACL Structure and Processing
An ACL is an ordered list of permit/deny rules. Each rule specifies match criteria — protocol, source IP/range, source port, destination IP/range, destination port. The ACL processor evaluates rules sequentially from top to bottom. The first rule that matches determines the action. If no rule matches, the implicit deny all applies — traffic not explicitly permitted is dropped.
This "first-match, top-to-bottom" model has a critical implication: rule order matters. A broad deny rule placed before a specific permit rule will catch and deny traffic that should have been permitted. Most firewall misconfigurations stem from incorrect rule ordering.
ACL Rule Simulator
Select a test packet and watch which rule it matches (top-to-bottom, first-match wins).
Standard vs. Extended ACLs
Standard ACLs (Cisco: numbered 1-99) match only on source IP address. They are placed close to the destination to avoid blocking traffic unnecessarily early. Limited use — primarily for routing policy decisions.
Extended ACLs (Cisco: numbered 100-199) match on source IP, destination IP, protocol, source port, destination port. These are the ACLs used for security filtering. Place them close to the source to drop traffic early.
! Cisco IOS Extended ACL
ip access-list extended OUTBOUND-FILTER
permit tcp 10.0.1.0 0.0.0.255 any eq 443 ! allow HTTPS
permit tcp 10.0.1.0 0.0.0.255 any eq 80 ! allow HTTP
deny ip 10.0.1.0 0.0.0.255 192.168.99.0 0.0.0.255 ! block access to mgmt VLAN
permit ip any any ! allow everything else
! Apply to interface (inbound = filter traffic entering the router interface)
interface GigabitEthernet0/1
ip access-group OUTBOUND-FILTER in0.0.0.255 in an ACL is NOT the same as 255.255.255.0 subnet mask — they are mathematically complementary.Stateful Inspection: Tracking Connections
The Connection State Table
A stateful firewall maintains a connection state table (also called a connection tracking table or session table). For every TCP connection it permits, it records:
— Source IP, Source Port, Destination IP, Destination Port, Protocol (the 5-tuple)
— Connection state (SYN_SENT, ESTABLISHED, FIN_WAIT_1, etc.)
— Timeout timer (removed from table after idle period)
When an inbound packet arrives with ACK set (a "reply"), the firewall checks the state table. If it matches an ESTABLISHED connection that was permitted outbound, the reply is automatically allowed — without needing an explicit inbound allow rule.
# Linux iptables with conntrack (stateful)
# Allow outbound HTTP/HTTPS
iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT
# Allow established connections back in (no explicit inbound rules needed for replies)
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
# Default deny
iptables -P INPUT DROP
iptables -P FORWARD DROPConnection States in Stateful Firewalls
NEW: first packet of a new connection (TCP SYN). The firewall checks rules to permit or deny.
ESTABLISHED: connection is active. Packets matching the 5-tuple are automatically permitted.
RELATED: associated with an established connection (e.g., FTP data channel related to FTP control session, ICMP error related to TCP session).
INVALID: malformed packets, out-of-state packets (RST for non-existent connection). Should be dropped.
State Table Exhaustion
The state table has a finite size (hardware memory). If an attacker can exhaust it by sending millions of SYN packets (SYN flood), the firewall can no longer track new connections. Legitimate new connections are denied even while existing ones work. Mitigation: SYN cookies, rate limiting new connections per source IP, aggressive state table timeouts.
Firewall Generation Comparator
Select a firewall generation to compare inspection depth, capabilities, and limitations.
Deep Packet Inspection and Application-Layer Firewalls
Application Identification (App-ID)
NGFWs use multiple techniques to identify applications regardless of port:
— Protocol decoders: understand application-layer protocols (HTTP, DNS, TLS). Can identify Dropbox traffic over HTTPS, Facebook over HTTPS, YouTube over HTTPS — same port, very different risk profiles.
— Behavioral patterns: traffic timing, packet sizes, connection patterns. BitTorrent has a distinctive pattern even when encrypted.
— TLS SNI inspection: the Server Name Indication field in the TLS ClientHello reveals the hostname being accessed, even before the certificate is exchanged.
— Certificate subject: the server certificate reveals organization and domain.
TLS Inspection (SSL Decryption)
NGFWs can perform TLS inspection: acting as a man-in-the-middle with the organization's own CA. The firewall decrypts TLS traffic from clients (presenting its CA-signed certificate), inspects the plaintext content, then re-encrypts to the server. This allows inspection of malware, DLP policy enforcement, and URL filtering inside HTTPS.
TLS inspection requires:
1. A CA certificate deployed to all clients (via MDM or Group Policy).
2. Exclusion lists for sites where inspection is legally prohibited (banking, healthcare, attorney-client) or technically problematic (certificate pinning will break).
3. Privacy disclosures to users (intercepting encrypted traffic has legal implications in many jurisdictions).
Zone-Based Firewall Architecture
Firewall Zone Architecture
Select a zone to understand what it contains and what traffic is allowed in/out.
- Web servers
- Reverse proxies
- Email gateways
- Public APIs
- Load balancers
- Internet (to specific ports: 80, 443, 25)
- Management zone (admin access)
- Internal (read app responses)
- Cannot initiate connections to Internal zone
- Cannot reach database zone directly
Zone Design Principles
1. Trust levels increase inward: Internet (untrusted) → DMZ (limited trust) → Internal (medium trust) → Database (high trust). Traffic is permitted from less trusted to more trusted zones only for specific, necessary purposes.
2. Default deny between zones: no traffic crosses a zone boundary unless explicitly permitted. The firewall policy is a whitelist, not a blacklist.
3. Least privilege: DMZ web servers can reach specific database servers on specific ports — not the entire database zone. Specificity reduces blast radius.
4. No bypass paths: ensure no routing path exists that bypasses the firewall. VLAN configurations, routing decisions, and firewall placement must all align.
The Two-Firewall DMZ
Best practice for sensitive environments: two firewalls with the DMZ between them. The outer firewall separates the internet from the DMZ. The inner firewall separates the DMZ from the internal network. Compromising the DMZ requires defeating both firewalls. The outer and inner firewalls should be from different vendors — a vulnerability in one vendor's product doesn't compromise both layers.
# Two-firewall DMZ architecture
Internet
│ (443, 25 allowed)
[Outer FW — Vendor A]
│
DMZ: Web servers, Email gateways, Load balancers
│ (only app→DB on port 5432)
[Inner FW — Vendor B]
│
Internal: Corporate LAN
│
[Database segment — additional ACLs]
│
Databasesiptables and nftables: Linux Firewalling
iptables Tables and Chains
iptables organizes rules into tables, each with predefined chains:
filter: primary security filtering. Chains: INPUT (packets destined for the local host), OUTPUT (packets originating from the local host), FORWARD (packets routed through the host).
nat: Network Address Translation. Chains: PREROUTING (DNAT — change destination IP), POSTROUTING (SNAT/MASQUERADE — change source IP).
mangle: modify packet headers (TTL, TOS, mark for policy routing).
raw: bypass conntrack for high-performance applications.
# Minimal server hardening iptables ruleset
# Flush existing rules
iptables -F && iptables -X
# Default policies: DROP everything
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT # or DROP if you want strict egress filtering
# Allow loopback
iptables -A INPUT -i lo -j ACCEPT
# Allow established/related connections (stateful)
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
# Allow SSH from admin VLAN only
iptables -A INPUT -p tcp -s 10.0.5.0/24 --dport 22 -m conntrack --ctstate NEW -j ACCEPT
# Allow HTTPS
iptables -A INPUT -p tcp --dport 443 -m conntrack --ctstate NEW -j ACCEPT
# Rate-limit new SSH connections (anti-brute-force)
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m limit --limit 3/min --limit-burst 5 -j ACCEPT
# Save rules
iptables-save > /etc/iptables/rules.v4nftables: The Modern Replacement
nftables replaced iptables in Linux 5.2+ as the default (though iptables still works via nf_tables compatibility layer). nftables advantages: single tool for IPv4+IPv6, atomic rule updates (no mid-update inconsistency), better performance, cleaner syntax.
# nftables equivalent
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
ct state established,related accept
ct state invalid drop
iif lo accept
tcp dport 22 ip saddr 10.0.5.0/24 ct state new accept
tcp dport 443 ct state new accept
tcp dport 22 ct state new limit rate 3/minute burst 5 packets accept
}
chain forward {
type filter hook forward priority 0; policy drop;
}
chain output {
type filter hook output priority 0; policy accept;
}
}Cloud Firewalling: Security Groups and NACLs
AWS Security Groups (Stateful)
AWS Security Groups are stateful virtual firewalls applied per-ENI (Elastic Network Interface). Rules specify inbound and outbound traffic. The connection tracking table is maintained by the hypervisor — return traffic for permitted connections is automatically allowed without explicit outbound rules.
# AWS Security Group (Terraform)
resource "aws_security_group" "web" {
name_prefix = "web-"
vpc_id = aws_vpc.main.id
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # internet HTTPS
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
security_groups = [aws_security_group.bastion.id] # SSH only from bastion SG
}
egress {
from_port = 5432
to_port = 5432
protocol = "tcp"
security_groups = [aws_security_group.database.id] # DB access only
}
}AWS Network ACLs (Stateless)
NACLs (Network Access Control Lists) are stateless subnet-level filters applied at the VPC subnet boundary. Because they are stateless, you must explicitly allow both inbound and outbound directions (including ephemeral ports for replies). NACLs are evaluated in rule-number order; the first matching rule wins. Use NACLs as a coarse second layer of defense, not as a replacement for security groups.
Cloud-Native Firewall Products
AWS Network Firewall: stateful inspection with Suricata-based rule engine. Inspects VPC-to-internet, east-west, and VPN traffic with stateful protocol tracking and IPS signatures.
Azure Firewall: managed FQDN filtering, network rules, application rules. DNAT for inbound. Threat intelligence-based filtering.
GCP Cloud Firewall: VPC-level rules with service account-based source/destination (instead of just IPs). Hierarchical policies across organizations.
Firewall Rule Management and Best Practices
Rule Design Principles
1. Default deny, explicit permit: start from zero, add only what is needed. Never start from permit-all and add denies.
2. Specificity over generality: permit TCP from app-server-subnet to db-server:5432 — not "permit tcp any any".
3. Documentation: every rule needs a comment explaining why it exists, who requested it, and when it can be removed.
4. Expiry dates: temporary rules (for testing, emergency access) should have removal dates set in the ticket system.
5. Rule review cadence: audit firewall rules quarterly. Use firewall rule analysis tools (Tufin, AlgoSec) to identify unused, shadowed, or overly permissive rules.
Common Firewall Mistakes
Shadow rules: a broader rule above a specific rule catches everything the specific rule would catch. The specific rule never fires.
Any-any rules: permit ip any any defeats the purpose of the firewall. Often added by frustrated admins when troubleshooting and never removed.
Inbound management from internet: SSH, RDP, or management interfaces accessible from the internet. Default in many cloud deployments. Always restrict management to specific source IPs or a VPN/bastion.
No egress filtering: most organizations control inbound traffic but ignore outbound. Egress filtering catches malware calling home, data exfiltration, and DNS amplification from internal hosts.
NAT: Network Address Translation and Its Security Implications
How NAT Works
SNAT (Source NAT): when a packet leaves the private network, the firewall replaces the source IP (private) with the public IP and records the mapping (src_private_IP:src_port → public_IP:nat_port) in the NAT table. When the reply arrives at the public IP, the firewall translates back to the private address.
DNAT (Destination NAT): for inbound connections to published services. The firewall translates the destination public IP:port to an internal private IP:port. Used for port forwarding and load balancing.
# iptables NAT for internet-sharing
# MASQUERADE: auto-uses the outgoing interface's IP as SNAT source
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# DNAT: forward port 443 to internal web server
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j DNAT --to-destination 192.168.1.10:443
iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 443 -j ACCEPTNAT is Not a Firewall
NAT provides implicit protection: internal hosts are not directly addressable from the internet. But this is a side effect, not a security feature. NAT does not:
— Filter traffic by port or protocol
— Inspect packet content
— Prevent outbound connections to malicious destinations
— Protect against compromised hosts on the inside
IPv6 eliminates the need for NAT (every device gets a globally routable address). IPv6 networks require explicit firewall rules to protect internal hosts — the "behind NAT = protected" assumption doesn't apply.
Web Application Firewalls (WAF)
WAF vs. NGFW
NGFWs understand protocols up to Layer 7 and can identify applications, but they operate on policy (allow/deny Dropbox, allow/deny YouTube). WAFs inspect the content of HTTP/HTTPS requests and responses for application-layer attack patterns. They are complementary, not alternatives.
WAF Rule Types
Signature-based: match known attack patterns. OWASP ModSecurity Core Rule Set (CRS) contains hundreds of signatures for SQLi, XSS, LFI, RFI, SSRF. Updated regularly as new attack patterns emerge.
Positive model (allowlist): learn normal application behavior — valid URLs, expected parameter formats, allowed methods. Block everything that deviates. Lower false-positive rate but requires training period.
Rate limiting: block IPs making excessive requests. Defeats brute force and credential stuffing.
Bot detection: CAPTCHAs, browser fingerprinting, behavioral analysis to distinguish human users from automated bots.
# ModSecurity / OWASP CRS (Apache/NGINX)
# Block SQL injection attempts
SecRule ARGS "@detectSQLi" "id:942100,phase:2,block,t:none,t:urlDecodeUni,msg:'SQL Injection Attack Detected'"
# Block XSS attempts
SecRule ARGS "@detectXSS" "id:941100,phase:2,block,msg:'XSS Attack Detected'"
# AWS WAF managed rule (Terraform)
resource "aws_wafv2_web_acl" "main" {
rule {
name = "AWSManagedRulesCommonRuleSet"
priority = 1
override_action { none {} }
statement {
managed_rule_group_statement {
name = "AWSManagedRulesCommonRuleSet"
vendor_name = "AWS"
}
}
}
}Firewall High Availability and Failover
Active-Passive HA
One firewall is active and handles all traffic. A second is in standby, receiving synchronized connection state. A heartbeat link between them detects failure. On failover (active fails to respond), the passive firewall becomes active, inherits the connection state, and traffic resumes with minimal interruption. Existing TCP connections survive failover because the new active firewall already knows their state.
Active-Active HA
Both firewalls handle traffic simultaneously, sharing load. More complex — requires asymmetric routing to be handled carefully (both firewalls must see both directions of each connection). Used when throughput exceeds a single unit's capacity.
State Synchronization
Firewalls synchronize: connection state table, NAT table, authentication sessions, and VPN tunnels. The sync link should be dedicated (not shared with user traffic) and isolated. Some vendors support multi-site HA for geographic redundancy.
Firewall Bypasses and Evasion Techniques
Protocol Tunneling
Any protocol can carry another protocol's traffic inside it:
— DNS tunneling: encode data in DNS query labels (e.g., base64data.attacker.com). DNS is nearly always permitted outbound. Tools: iodine, dnscat2. Detection: query rate monitoring, response size analysis.
— HTTPS tunneling: legitimate-looking HTTPS from a browser-embedded payload on port 443. TLS inspection needed to detect.
— ICMP tunneling: encode data in ICMP echo request/reply payloads. Tools: icmpsh. Detection: unusual payload sizes in ICMP, rate limiting ICMP.
Firewall Bypass via Allowed Protocols
IPv6 bypass: if IPv4 is filtered but IPv6 is not explicitly blocked, an attacker can tunnel over IPv6 if the network supports it.
HTTPS proxy bypass: CONNECT method on port 443 can tunnel any TCP protocol. A firewall that allows HTTPS without deep inspection allows arbitrary TCP tunnels.
The lesson: firewalls that filter by port and protocol are defeated by any protocol running on an allowed port. TLS inspection and application-level detection are necessary to close these gaps — but come with their own costs and complexities.
Misconceptions About Firewalls and ACLs
IQ Depth Check: Firewall and ACL Mastery
A stateless packet filter evaluates each packet independently based on its headers (src/dst IP, ports, protocol). It cannot tell if a packet is part of an established connection or a new attack. A stateful firewall maintains a connection state table and tracks TCP/UDP sessions. It automatically permits return traffic for established connections without explicit inbound rules. A stateless filter would need a broad "permit inbound TCP from any port > 1024" to allow web browsing replies; a stateful firewall automatically permits these replies while blocking uninitiated inbound connections.
Most firewalls and routers use first-match, top-to-bottom ACL processing. The packet is compared against each rule in order; the first matching rule's action (permit or deny) is applied. Processing stops — subsequent rules are not checked. The implicit deny is a virtual rule at the bottom of every ACL: if no rule matches, the packet is dropped. This means: (1) more specific rules should come before broader rules that would shadow them; (2) a missing explicit permit means traffic is denied; (3) troubleshoot connectivity by checking which rule the packet hits — if it's the implicit deny, a permit rule is missing.
TLS inspection: the NGFW acts as an SSL/TLS proxy. For outbound HTTPS, the firewall intercepts the TLS ClientHello, establishes its own TLS session to the destination server (verifying its certificate), then presents a newly generated certificate (signed by the corporate CA) to the client. The client trusts the firewall's CA because it was installed via MDM/GPO. The firewall decrypts, inspects, and re-encrypts. Applications that break: (1) certificate pinning (mobile banking, Duo, corporate apps that hardcode expected certificates); (2) mutual TLS (client certificates don't chain through the firewall's CA); (3) HPKP-enabled sites (deprecated but still seen); (4) services with their own CA trust chains (Apple APNs, Google FCM). The exclusion list must cover these, or the applications silently fail or show cert errors.
Stateful firewalls allocate a state table entry for every new connection: a 5-tuple (src IP, src port, dst IP, dst port, protocol) plus metadata (state, timers, sequence numbers for TCP). The table lives in TCAM (Ternary Content Addressable Memory) or DRAM. TCAM enables O(1) lookup but is expensive and limited in size (1-4M entries typical on enterprise firewalls). An attacker sending 100,000 SYN packets/second from spoofed IPs creates 100,000 half-open entries per second. With 1M table size and 60-second half-open timeout, 100k/s × 60s = 6M entries — the table exhausts in seconds. Hardware-based solutions: (1) SYN cookies offloaded to network processors — no state allocated for SYN-only packets; state created only when ACK arrives with valid cookie (verified in hardware); (2) per-source rate limiting in hardware (CAM-based packet rate tracking per /32 source) before packets reach the state engine; (3) tiered storage — hot connections in TCAM, warm connections in DRAM, session offload to NP (Network Processor) with dedicated connection memory. Modern firewall ASICs (Palo Alto's CN-series, Fortinet's NP7) process 100M+ packets/second with hardware-enforced rate limiting, removing the state exhaustion vulnerability from software-only implementations.
🎯 Key Takeaways
- ✓ACLs are ordered permit/deny rules evaluated top-to-bottom with first-match wins; the implicit deny all at the bottom drops everything not explicitly permitted.
- ✓Stateless packet filters evaluate each packet independently; stateful firewalls track connection state and automatically permit return traffic for established sessions.
- ✓NGFWs add application identification (App-ID), user awareness, TLS inspection, and threat intelligence to stateful inspection — identifying applications regardless of port.
- ✓TLS inspection breaks certificate pinning; maintain an exclusion list for banking apps, MDM agents, and mutual-TLS endpoints.
- ✓Zone-based design: Internet (trust 0) → DMZ (trust 1) → Internal (trust 2) → Database (trust 3) → Management (admin). Default deny between zones; explicit permit only.
- ✓Two-firewall DMZ from different vendors provides defense-in-depth; a vulnerability in one vendor does not compromise both layers.
- ✓NAT hides internal IPs as a side effect of address translation — it is not a firewall. IPv6 networks without NAT require explicit firewall rules.
- ✓State table exhaustion (SYN flood against firewall itself) is mitigated by SYN cookies, per-source rate limiting, and hardware-offloaded connection tracking.
- ✓DNS tunneling, HTTPS C2, and protocol tunneling bypass port-based firewalls; TLS inspection and application-layer detection are needed to close these gaps.
- ✓WAFs complement NGFWs: NGFWs allow/deny applications; WAFs inspect HTTP content for SQLi, XSS, and OWASP Top 10 attacks within permitted HTTPS traffic.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.