Firewalls
Chapter 15: Firewalls - Complete Deep Dive
Section titled “Chapter 15: Firewalls - Complete Deep Dive”Firewalls are the cornerstone of network security. This comprehensive chapter covers everything from basic packet filtering to advanced firewall architectures.
15.1 Introduction to Firewalls
Section titled “15.1 Introduction to Firewalls”What is a Firewall?
Section titled “What is a Firewall?”A firewall is a network security device or software that monitors and controls incoming and outgoing network traffic based on predetermined security rules. It establishes a barrier between trusted internal networks and untrusted external networks.
+------------------------------------------------------------------+| Firewall Overview |+------------------------------------------------------------------+
What Firewalls Do:+------------------------------------------------------------------+
1. TRAFFIC FILTERING - Allow or deny packets based on rules - Inspect packet headers - Make decisions based on source/dest IP, port, protocol
2. STATE TRACKING - Monitor active connections - Track connection state (NEW, ESTABLISHED, RELATED) - Allow return traffic for established connections
3. LOGGING AND AUDITING - Log allowed/denied connections - Audit network activity - Generate alerts for suspicious activity
4. NAT (Network Address Translation) - Hide internal IP addresses - Port forwarding - Load balancing
5. APPLICATION AWARAY (Next-Gen) - Deep Packet Inspection (DPI) - Application-layer filtering - Intrusion Prevention
Types of Firewalls:+------------------------------------------------------------------+
| Type | Layer | What It Checks ||-------------------|-------------|-------------------------------------|| Packet Filtering | L3-L4 | Source/Dest IP, Port, Protocol || Stateful | L3-L4 | Connection state || Application Proxy | L7 | Application protocol content || Next-Gen (NGFW) | L3-L7 | DPI, User ID, Application ID || Web Application | L7 | HTTP/HTTPS specific || Database Firewall| L7 | SQL query inspection || Cloud Firewall | L3-L7 | Managed cloud security |
Firewall Placement:+------------------------------------------------------------------+
INTERNET <----> FIREWALL <----> INTERNAL NETWORK | +----> DMZ (Public Servers) | - Web servers | - Email servers | - DNS servers
ZONES:+------------------------------------------------------------------+
1. Untrusted Zone (Internet) - No trust - Block everything by default - Only allow specific traffic
2. DMZ (Demilitarized Zone) - Semi-trusted - Public-facing services - Limited access to internal
3. Trusted Zone (Internal Network) - High trust - Internal users and servers - Can access DMZ with restrictions
4. Management Zone - Highly restricted - Admin access only - Isolated from regular traffic
+------------------------------------------------------------------+15.2 Packet Filtering
Section titled “15.2 Packet Filtering”The most basic form of firewall technology.
+------------------------------------------------------------------+| Packet Filtering Deep Dive |+------------------------------------------------------------------+
How Packet Filtering Works:+------------------------------------------------------------------+
Each packet is evaluated against a set of rules (Access Control List - ACL).
Packet Header Fields Checked:+------------------------------------------------------------------+
1. Source IP Address +------------------------------------------------------------------+ | Can be specific IP, range, or any | | Example: 192.168.1.10, 192.168.1.0/24, 0.0.0.0/0 | +------------------------------------------------------------------+
2. Destination IP Address +------------------------------------------------------------------+ | Where packet is going | | Example: 10.0.0.5, 8.8.8.8 | +------------------------------------------------------------------+
3. Source Port +------------------------------------------------------------------+ | Sender's port (usually ephemeral for client) | | Example: 49152, 1024-65535 | +------------------------------------------------------------------+
4. Destination Port +------------------------------------------------------------------+ | Service port | | Well-known: 80 (HTTP), 443 (HTTPS), 22 (SSH) | +------------------------------------------------------------------+
5. Protocol +------------------------------------------------------------------+ | TCP, UDP, ICMP, GRE, ESP, AH | +------------------------------------------------------------------+
6. TCP Flags +------------------------------------------------------------------+ | SYN, ACK, FIN, RST, PSH, URG | | Used for TCP connection state | +------------------------------------------------------------------+
Rule Evaluation Order:+------------------------------------------------------------------+
Packets are evaluated TOP to BOTTOM
Rule 1: permit tcp 192.168.1.0/24 host 8.8.8.8 eq 443Rule 2: deny ip any any
Result: Only HTTPS to 8.8.8.8 allowed from internal network
BEST PRACTICE: Put specific rules FIRST, general deny LAST
Example ACL (Cisco-style):+------------------------------------------------------------------+
! Allow HTTP and HTTPS from internalaccess-list 100 permit tcp 192.168.1.0 0.0.0.255 any eq 80access-list 100 permit tcp 192.168.1.0 0.0.0.255 any eq 443
! Allow SSH from admin network onlyaccess-list 100 permit tcp 10.0.0.0 0.0.0.255 any eq 22
! Allow ping (ICMP) - be careful!access-list 100 permit icmp any any echo-reply
! Deny everything elseaccess-list 100 deny ip any any
Packet Filter Limitations:+------------------------------------------------------------------+
1. NO STATE TRACKING +------------------------------------------------------------------+ | Can't tell if packet is part of legitimate connection | | Must allow all return traffic or break connectivity | +------------------------------------------------------------------+
2. IP SPOOFING +------------------------------------------------------------------+ | Can be fooled by forged source addresses | | Need additional validation | +------------------------------------------------------------------+
3. NO APPLICATION AWARENESS +------------------------------------------------------------------+ | Can't filter based on application content | | Can't block specific commands within protocol | +------------------------------------------------------------------+
4. FRAGMENT HANDLING +------------------------------------------------------------------+ | First fragment has header info | | Subsequent fragments may be harder to filter | +------------------------------------------------------------------+
+------------------------------------------------------------------+15.3 Stateful Firewall
Section titled “15.3 Stateful Firewall”Stateful inspection adds connection tracking to packet filtering.
+------------------------------------------------------------------+| Stateful Firewall Deep Dive |+------------------------------------------------------------------+
How Stateful Inspection Works:+------------------------------------------------------------------+
Firewall maintains a STATE TABLE tracking all active connections
State Table Entry:+------------------------------------------------------------------+
| Field | Value ||--------------------|-------------------------------------------|| Source IP | 192.168.1.100 || Source Port | 54321 || Destination IP | 8.8.8.8 || Destination Port | 443 || Protocol | TCP || State | ESTABLISHED || Timeout | 300 seconds || Packets In | 1234 || Bytes In | 1,234,567 |
Connection States:+------------------------------------------------------------------+
TCP States Tracked:+------------------------------------------------------------------+
| State | Meaning ||---------------|---------------------------------------------------|| NEW | First packet of new connection || ESTABLISHED | Part of already-established connection || RELATED | Related to existing connection (FTP data) || INVALID | Not recognized as valid packet || TIME_WAIT | Connection closing || CLOSE_WAIT | Received FIN, waiting for close || SYN_SENT | Only seen one SYN || SYN_RECV | Received SYN, sent SYN-ACK |
UDP States:+------------------------------------------------------------------+
UDP is connectionless, but firewall tracks "pseudo-states":+------------------------------------------------------------------+
| State | Description ||-------------|---------------------------------------------------|| NEW | First request to destination || ESTABLISHED| Response received from destination || - UDP has no real state, firewall times out entries |
ICMP States:+------------------------------------------------------------------+
| Type | State Tracking ||------------|--------------------------------------------------|| Echo Request| NEW || Echo Reply | RELATED (to NEW request) || - Similar to UDP |
Stateful Inspection Process:+------------------------------------------------------------------+
1. Packet arrives at firewall
2. Check state table: +------------------------------------------------------------------+ | If ESTABLISHED/RELATED: Allow automatically | | If NEW: Check against rules | | If no match: Drop | +------------------------------------------------------------------+
3. For NEW connections: +------------------------------------------------------------------+ | Check against ACL | | If ALLOW: Create state entry, allow | | If DENY: Drop | +------------------------------------------------------------------+
4. Log and update statistics
Example: Stateful Rules+------------------------------------------------------------------+
iptables:
# Allow established connections (automatic return traffic)iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow new HTTPS connectionsiptables -A INPUT -p tcp --dport 443 -m state --state NEW -j ACCEPT
# Allow new SSH from specific networkiptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/24 -m state --state NEW -j ACCEPT
# Default denyiptables -P INPUT DROP
Stateful vs Stateless:+------------------------------------------------------------------+
| Feature | Stateless (ACL) | Stateful ||------------------|-------------------|----------------------------|| Return traffic | Must explicitly allow | Automatic || Connection tracking| No | Yes || Resource usage | Low | Higher || Security | Weaker | Stronger || Complexity | Simple | More complex |
+------------------------------------------------------------------+15.4 Linux iptables - Complete Reference
Section titled “15.4 Linux iptables - Complete Reference”iptables is the standard Linux firewall.
+------------------------------------------------------------------+| iptables Complete Reference |+------------------------------------------------------------------+
iptables Architecture:+------------------------------------------------------------------+
TABLES:+------------------------------------------------------------------+
1. filter (default) +------------------------------------------------------------------+ | Packet filtering | | Chains: INPUT, FORWARD, OUTPUT | +------------------------------------------------------------------+
2. nat (Network Address Translation) +------------------------------------------------------------------+ | Address translation | | Chains: PREROUTING, OUTPUT, POSTROUTING | +------------------------------------------------------------------+
3. mangle +------------------------------------------------------------------+ | Packet modification | | Chains: PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING | +------------------------------------------------------------------+
4. raw +------------------------------------------------------------------+ | Bypass connection tracking | | Chains: PREROUTING, OUTPUT | +------------------------------------------------------------------+
Packet Flow Diagram:+------------------------------------------------------------------+
Incoming Packet | v[PREROUTING] (mangle, nat) | v[ROUTING DECISION] | +---> Local Process: [INPUT] (mangle, filter) --> Local App | +---> Forward: [FORWARD] (mangle, filter) --> Outgoing |[POSTROUTING] (mangle, nat) | vOutgoing Packet
Chains Explained:+------------------------------------------------------------------+
PREROUTING:+------------------------------------------------------------------+| - Before routing decision || - Used for DNAT (destination NAT) || - Port forwarding incoming |+------------------------------------------------------------------+
INPUT:+------------------------------------------------------------------+| - After routing, destined for local || - Local service access |+------------------------------------------------------------------+
OUTPUT:+------------------------------------------------------------------+| - Locally generated packets || - Outgoing from local processes |+------------------------------------------------------------------+
FORWARD:+------------------------------------------------------------------+| - Packets being routed through || - Not destined for local |+------------------------------------------------------------------+
POSTROUTING:+------------------------------------------------------------------+| - After routing, leaving the system || - Used for SNAT (source NAT), masquerading |+------------------------------------------------------------------+
Common iptables Commands:+------------------------------------------------------------------+
# View current rulessudo iptables -L -n -v # List all rulessudo iptables -L -n -v --line-numbers # With line numberssudo iptables -t nat -L -n -v # NAT table
# Allow SSH (port 22)sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP (80) and HTTPS (443)sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPTsudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow established connectionssudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Drop everything else (default policy)sudo iptables -P INPUT DROP
# Allow from specific IPsudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
# Allow specific networksudo iptables -A INPUT -s 10.0.0.0/24 -j ACCEPT
# Deny specific IPsudo iptables -A INPUT -s 192.168.1.50 -j DROP
# Delete a rulesudo iptables -D INPUT -p tcp --dport 22 -j ACCEPT
# Replace a rulesudo iptables -R INPUT 1 -p tcp --dport 22 -j ACCEPT
# Insert a rule at positionsudo iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT
# Flush rulessudo iptables -F # Flush all rulessudo iptables -X # Delete user chainssudo iptables -t nat -F # Flush NAT tablesudo iptables -Z # Zero counters
Common iptables Options:+------------------------------------------------------------------+
| Option | Description ||-------------|---------------------------------------------------|| -A | Append rule to chain || -I | Insert rule (default: position 1) || -R | Replace rule || -D | Delete rule || -L | List rules || -F | Flush (delete) all rules || -P | Set default policy || -p | Protocol (tcp, udp, icmp, all) || -s | Source IP/network || -d | Destination IP/network || --dport | Destination port || --sport | Source port || -m | Match extension || --state | Connection state (NEW, ESTABLISHED, etc.) || -j | Jump target (ACCEPT, DROP, REJECT, LOG) || -i | Input interface || -o | Output interface || -n | Numeric output (don't resolve DNS) || -v | Verbose |
Targets (Actions):+------------------------------------------------------------------+
ACCEPT:+------------------------------------------------------------------+| - Allow packet through || - Packet stops traversing this chain |+------------------------------------------------------------------+
DROP:+------------------------------------------------------------------+| - Silently discard packet || - No response to sender || - More secure (doesn't reveal firewall exists) |+------------------------------------------------------------------+
REJECT:+------------------------------------------------------------------+| - Discard packet || - Send ICMP rejection message || - Useful for troubleshooting (knows why blocked) || Example: iptables -A INPUT -p tcp --dport 22 -j REJECT --reject-with tcp-reset+------------------------------------------------------------------+
LOG:+------------------------------------------------------------------+| - Log packet to syslog || - Packet continues to next rule || Example: iptables -A INPUT -j LOG --log-prefix "IPTABLES: "+------------------------------------------------------------------+
SNAT (Source NAT):+------------------------------------------------------------------+| - Change source IP (typically for outbound) || Example: iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source 203.0.113.5+------------------------------------------------------------------+
DNAT (Destination NAT):+------------------------------------------------------------------+| - Change destination IP (typically for inbound) || Example: iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.10+------------------------------------------------------------------+
MASQUERADE:+------------------------------------------------------------------+| - Like SNAT but automatically uses outgoing IP || - Good for dynamic IPs || Example: iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE+------------------------------------------------------------------+
REDIRECT:+------------------------------------------------------------------+| - Redirect to local machine || - Example: Transparent proxy || Example: iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 3128+------------------------------------------------------------------+
Port Forwarding Example:+------------------------------------------------------------------+
# Forward external port 8080 to internal port 80sudo iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 8080 -j DNAT --to 192.168.1.10:80
# Also need to allow in filter tablesudo iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 80 -j ACCEPT
Saving and Restoring Rules:+------------------------------------------------------------------+
# Save rulessudo iptables-save > /etc/iptables/rules.v4
# Or using iptables-persistentsudo iptables-save > /etc/iptables/rules.v4sudo ip6tables-save > /etc/iptables/rules.v6
# Restore rulessudo iptables-restore < /etc/iptables/rules.v4
Make Rules Persistent on Boot:+------------------------------------------------------------------+
# On Debian/Ubuntusudo apt install iptables-persistentsudo netfilter-persistent savesudo netfilter-persistent reload
# On RHEL/CentOSsudo service iptables save
# On Arch Linuxsudo iptables-save > /etc/iptables/iptables.rules# Add to /etc/iptables/iptables.rules:*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT-A INPUT -p tcp --dport 22 -j ACCEPT-A INPUT -p tcp --dport 80 -j ACCEPT-A INPUT -p tcp --dport 443 -j ACCEPTCOMMIT
+------------------------------------------------------------------+15.5 nftables - Modern Linux Firewall
Section titled “15.5 nftables - Modern Linux Firewall”nftables is the successor to iptables, with improved performance and simpler syntax.
+------------------------------------------------------------------+| nftables Complete Guide |+------------------------------------------------------------------+
Why nftables?+------------------------------------------------------------------+
1. Single tool for IPv4 and IPv62. Faster performance (kernel-level)3. Simpler syntax4. Better support for tables and chains5. Active development
nftables vs iptables:+------------------------------------------------------------------+
| Feature | iptables | nftables ||------------------|------------------|----------------------|| Configuration | Multiple tools | Single nft tool || Tables | Separate per IP | Unified || Syntax | Complex | Simpler || Performance | Good | Better || Backward compat | N/A | iptables-nft module |
Basic nft Commands:+------------------------------------------------------------------+
# View current rulesetsudo nft list ruleset
# List tablessudo nft list tables
# List chains in a tablesudo nft list table ip filter
Create a Table and Chain:+------------------------------------------------------------------+
# Create filter table for IPv4sudo nft add table ip filter
# Add input chainsudo nft add chain ip filter input { type filter hook input priority 0 \; policy accept \; }
# Add forward chainsudo nft add chain ip filter forward { type filter hook forward priority 0 \; policy accept \; }
# Add output chainsudo nft add chain ip filter output { type filter hook output priority 0 \; policy accept \; }
Add Rules:+------------------------------------------------------------------+
# Allow SSHsudo nft add rule ip filter input tcp dport 22 accept
# Allow HTTP and HTTPSsudo nft add rule ip filter input tcp dport { 80, 443 } accept
# Allow established connectionssudo nft add rule ip filter input ct state established,related accept
# Drop invalid packetssudo nft add rule ip filter input ct state invalid drop
# Default drop inputsudo nft chain ip filter input { policy drop \; }
Complete Example:+------------------------------------------------------------------+
#!/usr/sbin/nft -f
# Flush existing rulesflush ruleset
# Create tableadd table ip filter
# Create chainsadd chain ip filter input { type filter hook input priority 0; policy drop; }add chain ip filter forward { type filter hook forward priority 0; policy drop; }add chain ip filter output { type filter hook output priority 0; policy accept; }
# Input chain rules
# Loopbackadd rule ip filter input iif lo accept
# Established/relatedadd rule ip filter input ct state established,related accept
# ICMPadd rule ip filter input icmp type echo-request accept
# SSHadd rule ip filter input tcp dport 22 accept
# HTTP/HTTPSadd rule ip filter input tcp dport { 80, 443 } accept
# Log and drop everything elseadd rule ip filter input counter drop
Save Configuration:+------------------------------------------------------------------+
# Save to filesudo nft list ruleset > /etc/nftables.conf
# Load on boot (create systemd service or add to startup)# /etc/nftables.conf should be loaded by nft.service
+------------------------------------------------------------------+15.6 UFW - Uncomplicated Firewall
Section titled “15.6 UFW - Uncomplicated Firewall”UFW provides a user-friendly interface for iptables.
+------------------------------------------------------------------+| UFW Complete Guide |+------------------------------------------------------------------+
Why UFW?+------------------------------------------------------------------+
- Simpler syntax than iptables- Good for basic firewall needs- Still uses iptables internally
Installation:+------------------------------------------------------------------+
sudo pacman -S ufw # Archsudo apt install ufw # Debian/Ubuntusudo yum install ufw # RHEL/CentOS
Basic Commands:+------------------------------------------------------------------+
# Enable firewallsudo ufw enable
# Disable firewallsudo ufw disable
# Check statussudo ufw status verbose
# Default policiessudo ufw default deny incomingsudo ufw default allow outgoing
Allow Services:+------------------------------------------------------------------+
# By service namesudo ufw allow ssh # Port 22sudo ufw allow http # Port 80sudo ufw allow https # Port 443sudo ufw allow ftp # Port 21
# By port numbersudo ufw allow 8080/tcpsudo ufw allow 53/udp
# By port rangesudo ufw allow 1000:2000/tcp
Allow from Specific Source:+------------------------------------------------------------------+
# Allow from specific IPsudo ufw allow from 192.168.1.100
# Allow from specific networksudo ufw allow from 192.168.1.0/24
# Allow specific port from networksudo ufw allow from 10.0.0.0/8 to any port 22
Allow to Specific Destination:+------------------------------------------------------------------+
# Allow to specific IPsudo ufw allow to 192.168.1.10
# Allow port to specific IPsudo ufw allow to 192.168.1.10 port 3306
Deny Rules:+------------------------------------------------------------------+
# Deny by servicesudo ufw deny ssh
# Deny from specific IPsudo ufw deny from 192.168.1.100
Delete Rules:+------------------------------------------------------------------+
# Delete by servicesudo ufw delete allow ssh
# Delete by rulesudo ufw delete allow 22/tcp
# Delete by number (show first)sudo ufw status numberedsudo ufw delete 2
Advanced Rules:+------------------------------------------------------------------+
# Rate limiting (prevent brute force)sudo ufw limit ssh
# Loggingsudo ufw logging on # Enable loggingsudo ufw logging off # Disable loggingsudo ufw logging low # Log blocked packets not matching default policysudo ufw logging medium # Log blocked packets plus valid packetssudo ufw logging high # Log all packets
View Rules:+------------------------------------------------------------------+
# Simple listsudo ufw status
# Verbosesudo ufw status verbose
# Numberedsudo ufw status numbered
# With commentssudo ufw show added
Example Configuration:+------------------------------------------------------------------+
# Reset to defaultssudo ufw reset
# Set defaultssudo ufw default deny incomingsudo ufw default allow outgoing
# Allow SSH (rate limited)sudo ufw limit ssh
# Allow HTTP/HTTPSsudo ufw allow httpsudo ufw allow https
# Allow MySQL from internal networksudo ufw allow from 192.168.1.0/24 to any port 3306
# Enablesudo ufw enable
# Check statussudo ufw status verbose
+------------------------------------------------------------------+15.7 firewalld - RHEL/CentOS Firewall
Section titled “15.7 firewalld - RHEL/CentOS Firewall”firewalld provides dynamic firewall management.
+------------------------------------------------------------------+| firewalld Complete Guide |+------------------------------------------------------------------+
Key Concepts:+------------------------------------------------------------------+
ZONES:+------------------------------------------------------------------+
firewalld uses zones to define trust levels for network connections.
| Zone | Default Trust Level | Use Case ||------------------|---------------------|-------------------------|| drop | Lowest | Block all incoming || block | Low | Reject all incoming || public | Untrusted | Public networks || external | Untrusted | External network (NAT)|| dmz | Semi-trusted | DMZ servers || work | Trusted | Work network || home | Trusted | Home network || internal | Trusted | Internal network || trusted | Highest | Trust all connections |
SERVICES:+------------------------------------------------------------------+
Predefined services with specific ports:+------------------------------------------------------------------+
| Service | Ports | Description ||----------|--------------------------|----------------------------|| ssh | 22/tcp | Secure Shell || http | 80/tcp | Web Server || https | 443/tcp | Secure Web || ftp | 21/tcp | File Transfer || mysql | 3306/tcp | MySQL Database || postgresql| 5432/tcp | PostgreSQL || dns | 53/tcp,53/udp | DNS || dhcp | 67/udp,68/udp | DHCP || samba | 137,138/udp,139,445/tcp | Windows File Sharing |
Basic Commands:+------------------------------------------------------------------+
# Check statussudo firewall-cmd --state
# List all zonessudo firewall-cmd --get-zones
# Get default zonesudo firewall-cmd --get-default-zone
# Set default zonesudo firewall-cmd --set-default-zone=home
# List active zonessudo firewall-cmd --get-active-zones
Allow Services:+------------------------------------------------------------------+
# List available servicessudo firewall-cmd --get-services
# List allowed services in current zonesudo firewall-cmd --list-services
# Add service (temporary)sudo firewall-cmd --add-service=http
# Add service (permanent)sudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --reload
# Remove servicesudo firewall-cmd --permanent --remove-service=http
Allow Ports:+------------------------------------------------------------------+
# Add port (temporary)sudo firewall-cmd --add-port=8080/tcp
# Add port (permanent)sudo firewall-cmd --permanent --add-port=8080/tcpsudo firewall-cmd --reload
# List portssudo firewall-cmd --list-ports
# Remove portsudo firewall-cmd --permanent --remove-port=8080/tcp
Allow from Source:+------------------------------------------------------------------+
# Add source (temporary)sudo firewall-cmd --add-source=192.168.1.0/24
# Add source (permanent)sudo firewall-cmd --permanent --add-source=192.168.1.0/24
# List sourcessudo firewall-cmd --list-sources
Rich Rules:+------------------------------------------------------------------+
Rich rules provide advanced configuration:
# Allow SSH from specific IPsudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="ssh" accept'
# Allow port from specific IPsudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.0/8" port port="3306" protocol="tcp" accept'
# Rate limitingsudo firewall-cmd --permanent --add-rich-rule='rule service name="ssh" limit value="10/m" accept'
# Log and rejectsudo firewall-cmd --permanent --add-rich-rule='rule service name="ssh" log prefix="SSH: " level="info" accept'
# Port forwardingsudo firewall-cmd --permanent --add-rich-rule='rule forward-port port="80" protocol="tcp" to-port="8080" to-addr="192.168.1.10"'
List Rich Rules:+------------------------------------------------------------------+
sudo firewall-cmd --list-rich-rules
Remove Rich Rules:+------------------------------------------------------------------+
sudo firewall-cmd --permanent --remove-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="ssh" accept'
Create Custom Zone:+------------------------------------------------------------------+
# Create custom zonesudo firewall-cmd --permanent --new-zone=myzone
# Add rules to custom zonesudo firewall-cmd --permanent --zone=myzone --add-service=httpsudo firewall-cmd --permanent --zone=myzone --add-source=192.168.1.0/24
# Activate zonesudo firewall-cmd --reload
+------------------------------------------------------------------+15.8 Application Layer Firewalls and Proxies
Section titled “15.8 Application Layer Firewalls and Proxies”+------------------------------------------------------------------+| Application Layer Firewalls Deep Dive |+------------------------------------------------------------------+
What is an Application Firewall?+------------------------------------------------------------------+
Operates at Layer 7 (Application Layer)- Inspects actual content of traffic- Understands application protocols- Can make decisions based on content
Types:+------------------------------------------------------------------+
1. Proxy Firewall2. Web Application Firewall (WAF)3. Next-Generation Firewall (NGFW)
Proxy Firewall:+------------------------------------------------------------------+
How Proxies Work:+------------------------------------------------------------------+
Traditional (No Proxy):+------------------------------------------------------------------+
Client <----------------> Server Direct connection Client knows server IP Server knows client IP
With Proxy:+------------------------------------------------------------------+
Client <----> Proxy Server <----> Server Request Request forwards forwards Response Response
Types of Proxies:+------------------------------------------------------------------+
FORWARD PROXY:+------------------------------------------------------------------+
+------------------------------------------------------------------+| Client --> Forward Proxy --> Internet --> Server || || Use cases: || - Hide client IP || - Content filtering || - Caching || - Access control |+------------------------------------------------------------------+
REVERSE PROXY:+------------------------------------------------------------------+
+------------------------------------------------------------------+| Client --> Internet --> Reverse Proxy --> Backend Servers || || Use cases: || - Load balancing || - SSL termination || - Web application firewall || - Cache static content || - Hide backend servers |+------------------------------------------------------------------+
Transparent Proxy:+------------------------------------------------------------------+
+------------------------------------------------------------------+| Client doesn't know proxy exists || Router redirects traffic transparently || Used for content filtering, caching |+------------------------------------------------------------------+
Common Proxy Software:+------------------------------------------------------------------+
| Software | Type | Use Case ||--------------|----------------|-----------------------------------|| Squid | Forward Proxy | Caching, web filtering || HAProxy | Reverse Proxy | Load balancing || Nginx | Reverse Proxy | Web server, load balancer || Apache | Reverse Proxy | Web server with proxy || Envoy | Service Mesh | Microservices proxy || Traefik | Reverse Proxy | Container-native |
+------------------------------------------------------------------+
Web Application Firewall (WAF):+------------------------------------------------------------------+
Purpose:+------------------------------------------------------------------+
Protects web applications from common attacks:+------------------------------------------------------------------+
- SQL Injection- Cross-Site Scripting (XSS)- Cross-Site Request Forgery (CSRF)- File Inclusion- Command Injection- DDoS
WAF Deployment:+------------------------------------------------------------------+
WAF sits between client and web server:
Client --> WAF --> Web Server --> Application --> Database
WAF Examples:+------------------------------------------------------------------+
| Product | Type | Notes ||----------------|-----------------|-------------------------------|| ModSecurity | Open Source | Apache/Nginx module || Cloudflare | Cloud WAF | Managed service || AWS WAF | Cloud | AWS integration || Azure WAF | Cloud | Azure integration || Imperva | Commercial | Enterprise || F5 ASM | Commercial | Enterprise |
WAF Rule Examples:+------------------------------------------------------------------+
# Block SQL injectionBlock requests containing: ' OR '1'='1
# Block XSSBlock requests containing: <script>
# Block path traversalBlock requests containing: ../
# Allow only specific methodsAllow: GET, POST, PUTBlock: DELETE, TRACE, OPTIONS
+------------------------------------------------------------------+
Next-Generation Firewall (NGFW):+------------------------------------------------------------------+
Traditional Firewall:+------------------------------------------------------------------+| - Layer 3-4 filtering || - Port/IP based || - No application awareness |+------------------------------------------------------------------+
NGFW Features:+------------------------------------------------------------------+
1. Deep Packet Inspection (DPI) +------------------------------------------------------------------+ | Inspect packet content beyond headers | | Can identify applications, not just ports | +------------------------------------------------------------------+
2. Application Awareness +------------------------------------------------------------------+ | Identify traffic by application (not just port) | | Can allow/block specific apps | +------------------------------------------------------------------+
3. User Identity Integration +------------------------------------------------------------------+ | Integrate with Active Directory | | Filter by user/group, not just IP | +------------------------------------------------------------------+
4. Intrusion Prevention +------------------------------------------------------------------+ | Built-in IPS | | Signatures for known attacks | +------------------------------------------------------------------+
5. SSL/TLS Inspection +------------------------------------------------------------------+ | Decrypt and inspect encrypted traffic | | Then re-encrypt | +------------------------------------------------------------------+
6. Threat Intelligence +------------------------------------------------------------------+ | Integration with threat feeds | | Block known malicious IPs/domains | +------------------------------------------------------------------+
NGFW Vendors:+------------------------------------------------------------------+
| Vendor | Product Name | Notes ||-------------|-----------------------|--------------------------|| Palo Alto | PAN-OS | Leading NGFW || Cisco | Firepower | Sourcefire acquisition || Fortinet | FortiGate | Good performance || Check Point| Quantum | Enterprise || Sophos | XGS | SMB/Enterprise || SonicWall | TZ, NSa | SMB |
+------------------------------------------------------------------+15.9 Firewall Best Practices
Section titled “15.9 Firewall Best Practices”+------------------------------------------------------------------+| Firewall Best Practices |+------------------------------------------------------------------+
Design Principles:+------------------------------------------------------------------+
1. DEFENSE IN DEPTH +------------------------------------------------------------------+ | Multiple layers of security | | Don't rely on single firewall | | Example: Firewall + WAF + Application security | +------------------------------------------------------------------+
2. LEAST PRIVILEGE +------------------------------------------------------------------+ | Only allow what's explicitly needed | | Block everything else | | Default deny | +------------------------------------------------------------------+
3. FAIL SECURE +------------------------------------------------------------------+ | If firewall fails, should block traffic | | Don't fail open | +------------------------------------------------------------------+
4. LOG EVERYTHING +------------------------------------------------------------------+ | Log all allowed and denied connections | | Regular audit | | Alert on suspicious patterns | +------------------------------------------------------------------+
Configuration Best Practices:+------------------------------------------------------------------+
1. RENAME DEFAULT ACCOUNTS +------------------------------------------------------------------+ | Change admin usernames | | Use strong passwords | +------------------------------------------------------------------+
2. DISABLE UNUSED SERVICES +------------------------------------------------------------------+ | Turn off services not needed | | Reduce attack surface | +------------------------------------------------------------------+
3. KEEP FIRMWARE UPDATED +------------------------------------------------------------------+ | Regular updates | | Security patches | +------------------------------------------------------------------+
4. BACKUP CONFIGURATION +------------------------------------------------------------------+ | Regular backups | | Document changes | +------------------------------------------------------------------+
5. TEST RULES REGULARLY +------------------------------------------------------------------+ | Verify rules work as expected | | Check for unintended access | +------------------------------------------------------------------+
Security Rules:+------------------------------------------------------------------+
DO:+------------------------------------------------------------------+| + Use stateful filtering || + Log dropped packets || + Rate limit connections || + Use encrypted management (SSH, HTTPS) || + Implement DMZ || + Use fail2ban for brute force |+------------------------------------------------------------------+
DON'T:+------------------------------------------------------------------+| - Allow management from untrusted networks || - Use default deny-all (test first!) || - Forget IPv6 traffic || - Ignore logs || - Open all ports "for testing" |+------------------------------------------------------------------+
Common Firewall Mistakes:+------------------------------------------------------------------+
1. FORGETTING RETURN TRAFFIC +------------------------------------------------------------------+ | Solution: Use stateful filtering | +------------------------------------------------------------------+
2. ALLOWING ICMP (PING) UNRESTRICTED +------------------------------------------------------------------+ | Security risk: Ping of death, reconnaissance | | Solution: Limit ICMP or disable | +------------------------------------------------------------------+
3. NOT FILTERING OUTBOUND TRAFFIC +------------------------------------------------------------------+ | Internal compromised hosts can attack others | | Solution: Filter outbound too | +------------------------------------------------------------------+
4. IPv6 BLIND SPOT +------------------------------------------------------------------+ | IPv6 traffic bypasses IPv4 rules | | Solution: Configure IPv6 firewall | +------------------------------------------------------------------+
+------------------------------------------------------------------+15.10 Chapter Summary
Section titled “15.10 Chapter Summary”In this comprehensive chapter, you learned:
- ✅ Firewall fundamentals - what firewalls do, types
- ✅ Packet filtering - stateless, ACLs
- ✅ Stateful inspection - connection tracking
- ✅ iptables - complete reference with examples
- ✅ nftables - modern alternative
- ✅ UFW - uncomplicated interface
- ✅ firewalld - dynamic firewall
- ✅ Application firewalls - proxies, WAF, NGFW
- ✅ Best practices - security and configuration
Next Chapter
Section titled “Next Chapter”Chapter 16: VPN - Virtual Private Network
Last Updated: February 2026