Firewalls
Chapter 23: Firewalls - iptables, nftables, firewalld
Section titled “Chapter 23: Firewalls - iptables, nftables, firewalld”Comprehensive Linux Firewall Management for Production Environments
Section titled “Comprehensive Linux Firewall Management for Production Environments”23.1 Understanding Linux Firewall Architecture
Section titled “23.1 Understanding Linux Firewall Architecture”The Linux Packet Filtering Stack
Section titled “The Linux Packet Filtering Stack”Linux firewalls operate at multiple layers of the networking stack, providing defense-in-depth protection for your systems. Understanding how packets flow through the Linux kernel is crucial for effective firewall management.
Linux Packet Flow Through Netfilter+------------------------------------------------------------------+| || Incoming Packet || | || v || +------------------+ || | Network Card | (Physical layer - eth0, wlan0) || +------------------+ || | || v || +------------------+ || | PREROUTING | (mangle/nat - Before routing decision) || | (mangle table) | || | (nat table) | || +------------------+ || | || v || +------------------+ || | Routing Decision| (Local or Forward?) || +------------------+ || | | || | v || | +------------------+ || | | FORWARD Chain | (routed to another || | | (filter table) | interface) || | +------------------+ || | | || v v || +------------------+ +------------------+ || | INPUT Chain | | POSTROUTING | || | (filter table) | | (nat table) | || +------------------+ +------------------+ || | | || v v || +------------------+ +------------------+ || | Local Process | | Outgoing Packet | || +------------------+ +------------------+ || || Tables (in order of processing): || 1. mangle - Packet modification (TTL, marks) || 2. nat - Network Address Translation || 3. filter - Packet filtering (default) || 4. security - SELinux contexts || 5. raw - Connection tracking exemptions || |+------------------------------------------------------------------+Tables and Their Purposes
Section titled “Tables and Their Purposes” iptables Tables Overview+------------------------------------------------------------------+| || Table | Chains Available | Purpose || -------------|---------------------------|---------------------|| filter | INPUT, OUTPUT, FORWARD | Packet filtering || nat | PREROUTING, OUTPUT, | Port forwarding, || | POSTROUTING | Masquerading || mangle | PREROUTING, OUTPUT, | Packet alteration || | INPUT, FORWARD | (TTL, marks, TOS) || raw | PREROUTING, OUTPUT | Disable tracking || security | INPUT, OUTPUT, FORWARD | SELinux marks || || Default table for most operations is 'filter' || |+------------------------------------------------------------------+23.2 iptables - The Classic Firewall
Section titled “23.2 iptables - The Classic Firewall”Basic iptables Command Structure
Section titled “Basic iptables Command Structure”The iptables command follows a consistent pattern that you’ll use for most operations:
iptables Command Syntax+------------------------------------------------------------------+| || iptables [-t table] -A|-I|-D|-R|-L [chain] [options] [-j target]| || Flags: || +----------------------------------------------------------+ || | -t, --table | Table to use (filter, nat, mangle, raw) | || | -A, --append | Add rule to end of chain | || | -I, --insert | Insert rule at position | || | -D, --delete | Delete rule | || | -R, --replace | Replace rule at position | || | -L, --list | List all rules | || | -F, --flush | Flush all rules | || | -N, --new-chain| Create new chain | || | -X, --delete-chain| Delete custom chain | || | -P, --policy | Set default policy | || | -v, --verbose | Verbose output | || | -n, --numeric | Don't resolve hostnames | || | --line-numbers | Show line numbers | || +----------------------------------------------------------+ || || Jump Targets (-j): || +----------------------------------------------------------+ || | ACCEPT | Allow packet | || | DROP | Silently discard | || | REJECT | Reject with error | || | LOG | Log to syslog | || | SNAT | Source NAT (post-routing) | || | DNAT | Destination NAT (pre-routing) | || | MASQUERADE| Auto-SNAT (dynamic IPs) | || | REDIRECT | Local redirect | || | RETURN | Return from custom chain | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Matching Options
Section titled “Matching Options” iptables Match Criteria+------------------------------------------------------------------+| || Protocol Matches: || -p, --protocol tcp|udp|icmp|all || || Source/Destination: || -s, --source IP address or network || -d, --destination IP address or network || || Port Matches: || --sport, --source-port Source port (with -p) || --dport, --destination-port Destination port (with -p) || -m multiport --dports 80,443,8080 (multiple ports) || || Interface: || -i, --in-interface Input interface (eth0, lo) || -o, --out-interface Output interface || || TCP Flags: || --tcp-flags SYN,ACK,FIN,RST,URG,PSH || || ICMP Type: || --icmp-type echo-request, echo-reply, destination-unreachable|| || Connection State: || -m conntrack --ctstate NEW,ESTABLISHED,RELATED,INVALID || || Additional Matches: || -m limit --limit 3/minute Rate limiting || -m string --string "attack" Content matching || -m time --timestart 09:00 --timestop 17:00 Time-based || -m layer7 --l7proto http Application layer || |+------------------------------------------------------------------+Common iptables Examples
Section titled “Common iptables Examples”1. Basic Server Hardening
Section titled “1. Basic Server Hardening”# Flush existing rules firstsudo iptables -Fsudo iptables -Xsudo iptables -t nat -Fsudo iptables -t mangle -F
# Set default policies (DROP everything by default)sudo iptables -P INPUT DROPsudo iptables -P FORWARD DROPsudo iptables -P OUTPUT ACCEPT
# Allow loopback interfacesudo iptables -A INPUT -i lo -j ACCEPTsudo iptables -A OUTPUT -o lo -j ACCEPT
# Allow established and related connectionssudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow SSH (change default port if needed)sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
# Allow HTTP and HTTPSsudo iptables -A INPUT -p tcp --dport 80 -j ACCEPTsudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow ICMP (ping) - limit rate to prevent ping floodsudo iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT
# Allow specific IP rangessudo iptables -A INPUT -s 10.0.0.0/8 -j ACCEPTsudo iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT
# Log dropped packetssudo iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables-dropped: " --log-level 42. Rate Limiting Connections
Section titled “2. Rate Limiting Connections”# Limit new SSH connections to prevent brute force (max 3 per minute)sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW \ -m recent --set --name SSHsudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW \ -m recent --update --seconds 60 --hitcount 4 --name SSH -j DROPsudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
# Limit HTTP requests per IP (100 connections per minute)sudo iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW \ -m hashlimit --hashlimit-above 100/min --hashlimit-burst 50 \ --hashlimit-htable-size 100000 --hashlimit-name http_limit -j DROP
# Protect against SYN floodsudo iptables -A INPUT -p tcp --syn -m conntrack --ctstate NEW \ -m limit --limit 1/s --limit-burst 3 -j ACCEPTsudo iptables -A INPUT -p tcp --syn -j DROP3. Port Forwarding (NAT)
Section titled “3. Port Forwarding (NAT)”# Enable IP forwardingecho 1 > /proc/sys/net/ipv4/ip_forward
# Forward port 8080 to internal web server at 10.0.0.10:80sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 10.0.0.10:80sudo iptables -A FORWARD -p tcp --dport 80 -d 10.0.0.10 -j ACCEPT
# Masquerade for outbound traffic (NAT for internal network)sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
# Port forwarding for Docker (if using docker0 bridge)sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 804. Custom Chains for Organization
Section titled “4. Custom Chains for Organization”# Create custom chains for better organizationsudo iptables -N TCPsudo iptables -N UDPsudo iptables -N INVALID_DROP
# Route protocol-specific traffic to custom chainssudo iptables -A INPUT -p tcp -j TCPsudo iptables -A INPUT -p udp -j UDPsudo iptables -A INPUT -m conntrack --ctstate INVALID -j INVALID_DROP
# In TCP chain - allow specific portssudo iptables -A TCP -p tcp --dport 22 -j ACCEPTsudo iptables -A TCP -p tcp --dport 80 -j ACCEPTsudo iptables -A TCP -p tcp --dport 443 -j ACCEPTsudo iptables -A TCP -p tcp -j RETURN
# In UDP chain - allow DNSsudo iptables -A UDP -p udp --dport 53 -j ACCEPTsudo iptables -A UDP -p udp -j RETURN
# In INVALID_DROP chainsudo iptables -A INVALID_DROP -j DROPSaving and Restoring iptables Rules
Section titled “Saving and Restoring iptables Rules”# Save rules (Debian/Ubuntu)sudo iptables-save > /etc/iptables/rules.v4
# Save rules (RHEL/CentOS)sudo iptables-save > /etc/sysconfig/iptables
# Restore rules (Debian/Ubuntu)sudo iptables-restore < /etc/iptables/rules.v4
# Restore rules (RHEL/CentOS)sudo iptables-restore < /etc/sysconfig/iptables
# Make rules persistent across reboots (Ubuntu)sudo apt-get install iptables-persistent# or on RHELsudo systemctl enable iptablesiptables Service Configuration
Section titled “iptables Service Configuration”# RHEL/CentOS - iptables servicesudo systemctl start iptablessudo systemctl enable iptablessudo systemctl status iptablessudo systemctl restart iptables
# View current rulessudo iptables -L -n -v --line-numberssudo iptables -t nat -L -n -vsudo iptables -t mangle -L -n -v
# Check specific chainsudo iptables -L INPUT -n -vsudo iptables -L OUTPUT -n -v
# Delete rules by line numbersudo iptables -D INPUT 5
# Replace rule by line numbersudo iptables -R INPUT 3 -p tcp --dport 22 -j ACCEPT23.3 nftables - The Modern Replacement
Section titled “23.3 nftables - The Modern Replacement”Why nftables?
Section titled “Why nftables?”nftables is the modern successor to iptables, designed to address several limitations of the legacy tool:
iptables vs nftables Comparison+------------------------------------------------------------------+| || Feature | iptables | nftables || -----------------|------------------|-------------------------|| Architecture | Separate binaries | Single tool (nft) || Tables | Separate tables | Unified framework || Ruleset | Fragmented | Single file || Performance | Linear lookup | Fast lookup (hash) || Backward compat | N/A | iptables compatibility || Extensibility | Kernel modules | Netlink API || Numeric output | IP-only | Handles, sets, maps || || nftables Advantages: || +----------------------------------------------------------+ || | 1. Single tool for IPv4, IPv6, ARP, bridge, inet | || | 2. Atomic rule set replacement | || | 3. Built-in sets and maps for efficient matching | || | 4. Better performance with rule set numbering | || | 5. Simplified syntax | || | 6. Improved debugging and tracing | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+nftables Command Structure
Section titled “nftables Command Structure” nft Command Syntax+------------------------------------------------------------------+| || nft [options] [command] [rule-specification] || || Commands: || +----------------------------------------------------------+ || | -a, --add | Add rule | || | -d, --delete | Delete rule or table | || | -l, --list | List rules or tables | || | -f, --file | Read from file | || | -i, --interactive | Interactive mode | || | -I, --insert | Insert rule | || | -r, --replace | Replace rule | || | -F, --flush | Flush rules | || | -T, --table | Table name | || | -c, --check | Check rules without applying | || | -v, --verbose | Verbose output | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+nftables Tables and Chains
Section titled “nftables Tables and Chains” nftables Table/Chain Structure+------------------------------------------------------------------+| || Family | Table Prefix | Example || ------------|--------------|---------------------------------|| ip | ip | table ip filter || ip6 | ip6 | table ip6 filter || inet | inet | table inet filter (both v4/v6) || arp | arp | table arp filter || bridge | bridge | table bridge filter || || Chain Types: || +----------------------------------------------------------+ || | filter | Packet filtering | || | nat | Network Address Translation | || | route | Routing decisions (FORWARD) | || +----------------------------------------------------------+ || || Chain Hooks: || +----------------------------------------------------------+ || | prerouting | Before routing decision | || | input | Incoming packets to local | || | forward | Packets being forwarded | || | output | Outgoing packets from local | || | postrouting| After routing decision | || +----------------------------------------------------------+ || || Priorities (lower = first): || +----------------------------------------------------------+ || | raw -10000 | filter 0 | || | dstnat -100 | security 50 | || | prerouting -100 | out 100 | || | native 0 (default) | | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Basic nftables Configuration
Section titled “Basic nftables Configuration”1. Creating Tables and Chains
Section titled “1. Creating Tables and Chains”# Create a basic filter tablesudo nft add table ip filter
# Create chains with hooks and prioritiessudo nft add chain ip filter input { type filter hook input priority 0; policy drop; }sudo nft add chain ip filter forward { type filter hook forward priority 0; policy drop; }sudo nft add chain ip filter output { type filter hook output priority 0; policy accept; }
# For both IPv4 and IPv6 (inet family)sudo nft add table inet my_firewallsudo nft add chain inet my_firewall input { type filter hook input priority 0; policy drop; }2. Adding Rules
Section titled “2. Adding Rules”# Allow loopbacksudo nft add rule ip filter input iif lo accept
# Allow established/related connectionssudo nft add rule ip filter input ct state established,related accept
# Allow SSHsudo nft add rule ip filter input tcp dport 22 ct state new accept
# Allow HTTP/HTTPSsudo nft add rule ip filter input tcp dport { 80, 443 } accept
# Allow ICMP (ping)sudo nft add rule ip filter input icmp type echo-request limit rate 1/second accept
# Allow specific IPsudo nft add rule ip filter input ip saddr 10.0.0.5 accept
# Log and drop everything elsesudo nft add rule ip filter input counter drop3. Using Sets and Maps
Section titled “3. Using Sets and Maps”# Define a set of blocked IPssudo nft add set ip filter blocked_ips { type ipv4_addr; }
# Add IPs to the setsudo nft add element ip filter blocked_ips { 192.168.1.100, 10.0.0.50 }
# Block traffic from blocked IPssudo nft add rule ip filter input ip saddr @blocked_ips drop
# Define a set of allowed portssudo nft add set ip filter allowed_ports { type inet_service; }
# Dynamic port forwarding with mapsudo nft add table ip natsudo nft add chain ip nat prerouting { type nat hook prerouting priority -100; }sudo nft add rule ip nat prerouting tcp dport 8080 dnat to 10.0.0.10:804. NAT Configuration
Section titled “4. NAT Configuration”# NAT table for port forwardingsudo nft add table ip nat
# DNAT - Port forward 8080 to internal serversudo nft add chain ip nat prerouting { type nat hook prerouting priority -100; }sudo nft add rule ip nat prerouting iif eth0 tcp dport 8080 dnat to 10.0.0.10:80
# SNAT - Masquerade for outbound trafficsudo nft add chain ip nat postrouting { type nat hook postrouting priority 100; }sudo nft add rule ip nat postrouting oif eth0 masqueradeComplete nftables Script
Section titled “Complete nftables Script”#!/usr/sbin/nft -f
# Flush existing rulesflush ruleset
# Create tablestable inet filter { # INPUT chain chain input { type filter hook input priority 0; policy drop;
# Loopback iif lo accept
# Established/related ct state established,related accept
# Invalid ct state invalid drop
# ICMP ip protocol icmp accept ip6 nexthdr ipv6-icmp accept
# SSH with rate limiting tcp dport 22 ct state new limit rate 3/minute accept
# HTTP/HTTPS tcp dport { 80, 443 } accept
# Log dropped counter drop }
# FORWARD chain chain forward { type filter hook forward priority 0; policy drop; ct state established,related accept counter drop }
# OUTPUT chain chain output { type filter hook output priority 0; policy accept; }}Managing nftables
Section titled “Managing nftables”# List all rulessudo nft list rulesetsudo nft list table ip filtersudo nft list chain ip filter input
# View with handles (for deletion)sudo nft -a list table ip filtersudo nft -a list chain ip filter input
# Delete specific rule by handlesudo nft delete rule ip filter input handle 5
# Save rules to filesudo nft list ruleset > /etc/nftables.conf
# Load rules from filesudo nft -f /etc/nftables.conf
# Make persistent (systemd)sudo systemctl enable nftablessudo systemctl start nftables23.4 firewalld - The Dynamic Firewall Manager
Section titled “23.4 firewalld - The Dynamic Firewall Manager”Understanding firewalld
Section titled “Understanding firewalld”firewalld provides a dynamically managed firewall with support for network zones. It’s the default firewall on RHEL, CentOS, and Fedora systems.
firewalld Architecture+------------------------------------------------------------------+| || firewalld Components || || +-------------------------------------------------------------+|| | firewalld daemon ||| | +------------------------------------------------------+ ||| | | Firewall Backend (nftables or iptables) | ||| | +------------------------------------------------------+ ||| | | ||| | +---------v--------+ ||| | | D-Bus API | (For configuration) ||| | +-----------------+ ||| | | ||| | +---------v--------+ ||| | | firewall-cmd | (Command line) ||| | | firewall-config | (GUI) ||| | +-----------------+ ||| +------------------------------------------------------------+|| || Zones (Predefined Security Levels): || +----------------------------------------------------------+ || | drop | Block all, allow only outgoing | || | block | Reject all, allow only outgoing | || | public | Untrusted, selective incoming | || | external | For routers, with NAT | || | dmz | Public servers, limited internal access | || | work | Mostly trusted, limited incoming | || | home | Home network, more trust | || | internal | Internal network, most trust | || | trusted | Allow everything | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+firewalld Command Line (firewall-cmd)
Section titled “firewalld Command Line (firewall-cmd)”# Check statussudo firewall-cmd --statesudo firewall-cmd --list-allsudo firewall-cmd --list-all-zones
# Get current zonesudo firewall-cmd --get-active-zonessudo firewall-cmd --get-default-zone
# Change default zonesudo firewall-cmd --set-default-zone=work
# Add interface to zonesudo firewall-cmd --zone=public --add-interface=eth0sudo firewall-cmd --zone=public --change-interface=eth0sudo firewall-cmd --zone=public --remove-interface=eth0
# Reload firewall (lose runtime changes)sudo firewall-cmd --reload
# Complete reloadsudo firewall-cmd --complete-reloadManaging Services
Section titled “Managing Services”# List allowed servicessudo firewall-cmd --list-services
# Add/remove servicessudo firewall-cmd --zone=public --add-service=sshsudo firewall-cmd --zone=public --remove-service=sshsudo firewall-cmd --zone=public --add-service=httpsudo firewall-cmd --zone=public --add-service=https
# List available servicessudo firewall-cmd --get-services
# Add custom service (create in /etc/firewalld/services/)sudo firewall-cmd --zone=public --add-service=custom-appManaging Ports
Section titled “Managing Ports”# List open portssudo firewall-cmd --list-ports
# Add/remove portssudo firewall-cmd --zone=public --add-port=8080/tcpsudo firewall-cmd --zone=public --remove-port=8080/tcp
# Add port rangesudo firewall-cmd --zone=public --add-port=1000-2000/tcp
# Permanent changes (survive reload)sudo firewall-cmd --permanent --zone=public --add-port=8080/tcpsudo firewall-cmd --reload # Apply permanent changesManaging Rich Rules
Section titled “Managing Rich Rules” Rich Rule Syntax+------------------------------------------------------------------+| || firewalld rich rule format: || || rule [family="ipv4|ipv6"] || [source address="address[/mask]"] || [destination address="address[/mask]"] || [service name="service_name"] || [port port="portid" protocol="tcp|udp"] || [icmp-block name="icmptype"] || [masquerade] || [forward-port port="portid" protocol="tcp|udp" || to-addr="address" to-port="portid"] || [log [prefix="text"] [level="log|emerg|alert|crit|error| || warning|notice|info"]] || [audit [limit value="rate/duration"]] || [accept | reject [type="reject_type"] | drop] || |+------------------------------------------------------------------+Rich Rule Examples
Section titled “Rich Rule Examples”# Allow SSH from specific IPsudo firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="10.0.0.5" service name="ssh" accept'
# Rate limit SSH connectionssudo firewall-cmd --zone=public --add-rich-rule='rule service name="ssh" accept limit value="3/m"'
# Block specific IPsudo firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.100" drop'
# Port forwardingsudo firewall-cmd --zone=external --add-forward-port=port=8080:proto=tcp:toport=80:toaddr=10.0.0.10
# Masqueradingsudo firewall-cmd --zone=external --add-masquerade
# Log and rejectsudo firewall-cmd --zone=public --add-rich-rule='rule service name="ssh" log prefix="SSH: " level="info" accept'
# List rich rulessudo firewall-cmd --zone=public --list-rich-rulesPort Forwarding with firewalld
Section titled “Port Forwarding with firewalld”# Enable forwarding in kernelecho 1 > /proc/sys/net/ipv4/ip_forward
# Make permanentecho "net.ipv4.ip_forward=1" >> /etc/sysctl.confsysctl -p
# Forward port 80 to internal serversudo firewall-cmd --zone=external --add-forward-port=port=80:proto=tcp:toport=80:toaddr=10.0.0.10sudo firewall-cmd --zone=external --add-masquerade
# Permanent (survive reboot)sudo firewall-cmd --permanent --zone=external --add-forward-port=port=80:proto=tcp:toport=80:toaddr=10.0.0.10sudo firewall-cmd --permanent --zone=external --add-masqueradesudo firewall-cmd --reloadDirect Interface (for advanced rules)
Section titled “Direct Interface (for advanced rules)”# Add direct iptables rulesudo firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 22 -j ACCEPT
# Add rule to chainsudo firewall-cmd --direct --add-chain ipv4 filter my_custom_chain
# List direct rulessudo firewall-cmd --direct --get-all-rulessudo firewall-cmd --direct --list-rules ipv4 filter INPUT
# Remove direct rulesudo firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 -p tcp --dport 22 -j ACCEPTCreating Custom Services
Section titled “Creating Custom Services”# Create custom service filesudo vi /etc/firewalld/services/custom-app.xml
# Content:<?xml version="1.0" encoding="utf-8"?><service> <short>Custom App</short> <description>Custom application service</description> <port port="9000" protocol="tcp"/> <port port="9001" protocol="udp"/></service>
# Reload and usesudo firewall-cmd --reloadsudo firewall-cmd --zone=public --add-service=custom-app23.5 UFW - Uncomplicated Firewall
Section titled “23.5 UFW - Uncomplicated Firewall”UFW Basics
Section titled “UFW Basics”UFW provides a simplified interface for managing iptables rules. It’s the default on Ubuntu and Debian systems.
# Enable/disable UFWsudo ufw enablesudo ufw disable
# Check statussudo ufw statussudo ufw status verbosesudo ufw status numbered
# Default policiessudo ufw default deny incomingsudo ufw default allow outgoingsudo ufw default deny routed # For forward chainBasic UFW Commands
Section titled “Basic UFW Commands”# Allow SSH (both)sudo ufw allow sshsudo ufw allow 22/tcp
# Allow specific portssudo ufw allow 80/tcpsudo ufw allow 443/tcpsudo ufw allow 8000:9000/tcp # Port range
# Deny specific portsudo ufw deny 23/tcp # Telnet
# Allow from specific IPsudo ufw allow from 10.0.0.5sudo ufw allow from 10.0.0.0/24
# Allow specific IP to portsudo ufw allow from 10.0.0.5 to any port 22
# Deny from specific IPsudo ufw deny from 192.168.1.100
# Delete rulessudo ufw delete allow 22/tcpsudo ufw delete deny from 192.168.1.100UFW with Application Profiles
Section titled “UFW with Application Profiles”# List available profilessudo ufw app listsudo ufw app info "Nginx Full"
# Allow using profilesudo ufw allow "Nginx Full"sudo ufw allow "OpenSSH"
# Create custom profilesudo vi /etc/ufw/applications.d/custom-app
[Custom App]title=Custom Applicationdescription=Custom app portsports=9000,9001/tcpUFW Configuration Files
Section titled “UFW Configuration Files”# Main configsudo vi /etc/ufw/ufw.conf
# Rules location/etc/ufw/user.rules # IPv4/etc/ufw/user6.rules # IPv6/etc/ufw/before.rules # Before user rules/etc/ufw/after.rules # After user rules
# Loggingsudo ufw logging onsudo ufw logging offsudo ufw logging low|medium|high
# View logssudo tail -f /var/log/ufw.log23.6 Production Firewall Best Practices
Section titled “23.6 Production Firewall Best Practices”Server Hardening Checklist
Section titled “Server Hardening Checklist” Production Firewall Checklist+------------------------------------------------------------------+| || Initial Setup: || +----------------------------------------------------------+ || | □ Default deny all incoming traffic | || | □ Default allow all outgoing traffic | || | □ Log and drop invalid packets | || | □ Rate limit new connections | || | □ Allow only necessary ports | || | □ Restrict SSH to known IPs or use key-based auth | || +----------------------------------------------------------+ || || Essential Rules: || +----------------------------------------------------------+ || | □ Allow loopback interface | || | □ Allow established/related connections | || | □ Allow SSH (port 22 or custom) | || | □ Allow HTTP/HTTPS (80, 443) | || | □ Allow ICMP with rate limiting | || | □ Block common attack ports (telnet 23, rpc 111) | || +----------------------------------------------------------+ || || Security Enhancements: || +----------------------------------------------------------+ || | □ SYN flood protection | || | □ Port scanning detection | || | □ Connection tracking limits | || | □ Application-layer filtering | || | □ Fail2Ban integration | || | □ Regular audit of firewall rules | || +----------------------------------------------------------+ || || High Availability: || +----------------------------------------------------------+ || | □ Document all rules | || | □ Backup firewall configuration | || | □ Test restore procedures | || | □ Automate deployment with configuration management | || | □ Monitor rule changes | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Fail2Ban Integration
Section titled “Fail2Ban Integration”# Install Fail2Bansudo apt-get install fail2ban # Debian/Ubuntusudo yum install fail2ban # RHEL/CentOS
# Configure jail.localsudo vi /etc/fail2ban/jail.local
[DEFAULT]bantime = 3600findtime = 600maxretry = 3
[sshd]enabled = trueport = sshaction = %(action_mwl)s
[nginx-http-auth]enabled = true
[nginx-noscript]enabled = true
# Start servicesudo systemctl enable fail2bansudo systemctl start fail2ban
# Check statussudo fail2ban-client statussudo fail2ban-client status sshdFirewall Rules for Common Services
Section titled “Firewall Rules for Common Services” Common Service Firewall Rules+------------------------------------------------------------------+| || Web Server (Apache/Nginx): || +----------------------------------------------------------+ || | iptables: | || | iptables -A INPUT -p tcp --dport 80 -j ACCEPT | || | iptables -A INPUT -p tcp --dport 443 -j ACCEPT | || | | || | firewalld: | || | firewall-cmd --permanent --add-service=http | || | firewall-cmd --permanent --add-service=https | || +----------------------------------------------------------+ || || Database Server (MySQL/PostgreSQL): || +----------------------------------------------------------+ || | iptables (allow only app server): | || | iptables -A INPUT -p tcp -s 10.0.0.5 --dport 3306 -j ACCEPT | || | | || | firewalld: | || | firewall-cmd --permanent --add-port=3306/tcp | || | firewall-cmd --permanent --add-rich-rule='rule family="ipv4" | || | source address="10.0.0.5" port port="3306" protocol="tcp" accept' | || +----------------------------------------------------------+ || || Mail Server: || +----------------------------------------------------------+ || | iptables: | || | iptables -A INPUT -p tcp --dport 25 -j ACCEPT | || | iptables -A INPUT -p tcp --dport 587 -j ACCEPT | || | iptables -A INPUT -p tcp --dport 993 -j ACCEPT | || | | || | firewalld: | || | firewall-cmd --permanent --add-service=smtp | || | firewall-cmd --permanent --add-service=smtps | || | firewall-cmd --permanent --add-service=imap | || | firewall-cmd --permanent --add-service=imaps | || +----------------------------------------------------------+ || || Docker: || +----------------------------------------------------------+ || | # Docker modifies iptables automatically | || | # Restrict container network access: | || | docker network create --internal internal-net | || | | || | # Expose only necessary ports | || | docker run -p 8080:80 mywebapp | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Troubleshooting Firewall Issues
Section titled “Troubleshooting Firewall Issues”# Check if firewall is blockingsudo iptables -L -n -v | grep DROPsudo iptables -L -n -v | grep REJECT
# Check connection statessudo conntrack -Lsudo conntrack -L | grep ESTABLISHED
# Monitor dropped packetssudo tcpdump -i eth0 -n | grep DROP
# Check system logssudo journalctl -u firewalldsudo tail -f /var/log/ufw.logsudo dmesg | grep iptables
# Test connectivitync -zv target_host porttelnet target_host portcurl -v http://target:port
# Verify listening portssudo ss -tulpnsudo netstat -tulpn23.7 Interview Questions
Section titled “23.7 Interview Questions”Basic Questions
Section titled “Basic Questions”-
What is the difference between iptables and firewalld?
- iptables is a direct interface to netfilter, using separate tables and chains
- firewalld is a dynamic wrapper that manages rules dynamically with zones
-
What are the default chains in the filter table?
- INPUT: For packets destined for local socket
- OUTPUT: For locally generated packets
- FORWARD: For packets being routed through the system
-
What is the difference between DROP and REJECT?
- DROP silently discards the packet (no response)
- REJECT sends an ICMP error message back to the source
-
What is Connection Tracking (conntrack)?
- Tracks the state of network connections (NEW, ESTABLISHED, RELATED, INVALID)
- Essential for stateful packet filtering
Intermediate Questions
Section titled “Intermediate Questions”-
Explain the packet flow through iptables chains
- Packet arrives → PREROUTING (mangle, nat) → Routing Decision → INPUT/FORWARD → OUTPUT → POSTROUTING
-
How do you forward traffic from port 80 to an internal server?
- Using DNAT:
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 10.0.0.10:80 - Using firewalld:
firewall-cmd --add-forward-port=port=80:proto=tcp:toport=80:toaddr=10.0.0.10
- Using DNAT:
-
What is NAT? Types of NAT?
- Network Address Translation
- SNAT: Source NAT (outbound traffic)
- DNAT: Destination NAT (inbound traffic)
- MASQUERADE: Dynamic SNAT
-
How do you rate limit connections in iptables?
- Using limit module:
-m limit --limit 1/s --limit-burst 3 - Using recent module:
-m recent --set --name SSHand--update --seconds 60 --hitcount 4
- Using limit module:
Advanced Questions
Section titled “Advanced Questions”-
What are the advantages of nftables over iptables?
- Single tool for all families (IPv4, IPv6, ARP, bridge)
- Better performance with built-in sets and maps
- Atomic rule set replacement
- Simplified syntax and improved debugging
-
How do you secure SSH against brute force attacks?
- Use key-based authentication
- Rate limit with iptables/firewalld
- Change default port
- Use Fail2Ban
- Configure TCP wrappers
- Disable root login
-
Explain the concept of zones in firewalld
- Zones define trust levels for network connections
- Each zone has its own set of rules
- Interfaces can be assigned to zones
- Predefined zones: drop, block, public, external, dmz, work, home, internal, trusted
-
How would you debug firewall rule issues?
- Check current rules:
iptables -L -n -v - Use logging:
-j LOG --log-prefix - Check conntrack state:
conntrack -L - Monitor with tcpdump
- Check system logs
- Use rule counters to identify matching rules
- Check current rules:
23.8 Real-World Scenarios
Section titled “23.8 Real-World Scenarios”Scenario 1: Web Server Firewall Setup
Section titled “Scenario 1: Web Server Firewall Setup” Web Server Firewall Configuration+------------------------------------------------------------------+| || Requirements: || - Allow HTTP (80) and HTTPS (443) from anywhere || - Allow SSH (22) from admin network only || - Allow ping for monitoring || - Block all other incoming traffic || || iptables solution: || +----------------------------------------------------------+ || | #!/bin/bash | || | # Flush rules | || | iptables -F | || | iptables -X | || | | || | # Default policies | || | iptables -P INPUT DROP | || | iptables -P FORWARD DROP | || | iptables -P OUTPUT ACCEPT | || | | || | # Loopback | || | iptables -A INPUT -i lo -j ACCEPT | || | | || | # Established | || | iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT | || | | || | # SSH from admin network only | || | iptables -A INPUT -p tcp -s 10.0.0.0/24 --dport 22 -m conntrack --ctstate NEW -j ACCEPT | || | | || | # HTTP/HTTPS | || | iptables -A INPUT -p tcp --dport 80 -j ACCEPT | || | iptables -A INPUT -p tcp --dport 443 -j ACCEPT | || | | || | # ICMP (ping) with rate limit | || | iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT | || +----------------------------------------------------------+ || || firewalld solution: || +----------------------------------------------------------+ || | firewall-cmd --set-default-zone=public | || | firewall-cmd --permanent --add-service=http | || | firewall-cmd --permanent --add-service=https | || | firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.0/24" service name="ssh" accept' | || | firewall-cmd --reload | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Scenario 2: NAT Router Configuration
Section titled “Scenario 2: NAT Router Configuration” NAT Router Setup+------------------------------------------------------------------+| || Network Setup: || +----------------------------------------------------------+ || | External: eth0 (WAN) - 203.0.113.10 | || | Internal: eth1 (LAN) - 192.168.1.1 | || +----------------------------------------------------------+ || || Requirements: || - NAT for all outbound traffic (masquerade) || - Forward port 8080 to internal web server || - Forward port 2201 to internal SSH server || || iptables solution: || +----------------------------------------------------------+ || | # Enable forwarding | || | echo 1 > /proc/sys/net/ipv4/ip_forward | || | | || | # NAT (masquerade) | || | iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE | || | | || | # Port forwarding: Web server | || | iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.10:80 | || | iptables -A FORWARD -p tcp --dport 80 -d 192.168.1.10 -j ACCEPT | || | | || | # Port forwarding: SSH server | || | iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 2201 -j DNAT --to-destination 192.168.1.20:22 | || | iptables -A FORWARD -p tcp --dport 22 -d 192.168.1.20 -j ACCEPT | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Scenario 3: Multi-Tier Application Firewall
Section titled “Scenario 3: Multi-Tier Application Firewall” Multi-Tier Application Architecture+------------------------------------------------------------------+| || +-------------+ +-------------+ +-------------+ || | Internet |----->| Load Balancer|---->| Web Servers | || | | | (DMZ) | | (DMZ) | || +-------------+ +-------------+ +-------------+ || | || v || +-------------+ || |App Servers | || | (Internal) | || +-------------+ || | || v || +-------------+ || | Database | || | (Internal) | || +-------------+ || || Firewall Rules: || +----------------------------------------------------------+ || | Load Balancer (DMZ): | || | - Allow 80/443 from Internet | || | - Allow SSH (22) from Admin IPs | || | | || | Web Servers (DMZ): | || | - Allow 80/443 from Load Balancer | || | - Allow SSH from Admin IPs | || | - Allow 8080 (app) from Web Servers | || | | || | App Servers (Internal): | || | - Allow 8080 from Web Servers | || | - Allow SSH from App Servers | || | - Allow 3306 (MySQL) from App Servers | || | | || | Database (Internal): | || | - Allow 3306 from App Servers only | || | - No direct access from Internet | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Summary
Section titled “Summary”Linux firewalls are essential for securing systems in production environments. Here’s a quick reference:
Firewall Tool Comparison+------------------------------------------------------------------+| || Tool | Best For | Complexity | Pros || ------------|--------------------|------------|---------------|| iptables | Full control | High | Complete || | Legacy systems | | flexibility || ------------|--------------------|------------|---------------|| nftables | Modern systems | Medium | Better || | Performance | | performance || ------------|--------------------|------------|---------------|| firewalld | RHEL/CentOS | Low | Dynamic, || | Enterprise | | zone-based || ------------|--------------------|------------|---------------|| ufw | Debian/Ubuntu | Very Low | Simple, || | Beginners | | human-readable|| || Key Commands: || +----------------------------------------------------------+ || | iptables -L -n -v | List rules | || | iptables -A INPUT -p tcp --dport 80 | Allow HTTP | || | iptables -t nat -L -n | List NAT rules | || | nft list ruleset | List nft rules | || | firewall-cmd --list-all | List firewalld | || | ufw status | List UFW rules | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+