Firewall Management (iptables, ufw)
Category: Advanced Linux Administration
Type: Linux Commands
Generated on: 2025-07-10 03:15:27
For: System Administration, Development & Technical Interviews
Firewall Management Cheatsheet: iptables & ufw (Linux)
Section titled “Firewall Management Cheatsheet: iptables & ufw (Linux)”Purpose: This cheatsheet provides a comprehensive guide to managing firewalls on Linux using iptables and ufw. It covers basic and advanced usage, troubleshooting, and best practices for securing your systems. Choose ufw for ease of use and iptables for fine-grained control and complex configurations.
1. Command Overview
Section titled “1. Command Overview”-
iptables: The traditional Linux firewall administration tool. It allows you to define rules that govern network traffic based on various criteria (source/destination IP, port, protocol, etc.). Rules are organized into tables and chains.
iptablesinteracts directly with the kernel’s netfilter framework. -
ufw (Uncomplicated Firewall): A user-friendly front-end for
iptables. It simplifies common firewall tasks and provides a more intuitive interface.ufwstill relies oniptablesunder the hood.
When to Use:
- iptables:
- When you need very fine-grained control over firewall rules.
- When dealing with complex network configurations.
- When you require advanced features not available in
ufw. - When you need to script firewall configurations.
- ufw:
- For simple firewall configurations.
- When you prefer an easier-to-use interface.
- For quick setup and common tasks like allowing SSH or HTTP traffic.
- When you want a more readable rule syntax.
2. Basic Syntax
Section titled “2. Basic Syntax”iptables
Section titled “iptables”iptables [-t table] command [chain] [rule-specification] [options]-t table: Specifies the table to use (e.g.,filter,nat,mangle,raw). Default isfilter.command: Action to perform (e.g.,-A,-I,-D,-L,-F).chain: The chain to apply the command to (e.g.,INPUT,OUTPUT,FORWARD).rule-specification: Conditions that must be met for the rule to apply (e.g.,-s,-d,-p,--dport).options: Additional options (e.g.,-j,-m).
ufw command [options]command: Action to perform (e.g.,enable,disable,allow,deny,status).options: Additional options (e.g.,numbered,logging).
3. Practical Examples
Section titled “3. Practical Examples”iptables
Section titled “iptables”Example 1: Allow SSH traffic (port 22) on the INPUT chain:
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPTExpected Output: (None, unless there is an error)
Example 2: Drop all traffic from a specific IP address:
sudo iptables -A INPUT -s 192.168.1.100 -j DROPExpected Output: (None, unless there is an error)
Example 3: List all rules in the INPUT chain of the filter table:
sudo iptables -L INPUT -v -nExpected Output:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 10 600 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 0 0 DROP all -- * * 192.168.1.100 0.0.0.0/0Example 4: Delete the first rule in the INPUT chain:
sudo iptables -D INPUT 1Expected Output: (None, unless there is an error)
Example 5: Save iptables rules (important to persist rules after reboot):
# Debian/Ubuntusudo iptables-save > /etc/iptables/rules.v4
# RHEL/CentOSsudo iptables-save > /etc/sysconfig/iptablesExpected Output: (None, unless there is an error). Check the file to confirm rules are saved.
Example 1: Enable the firewall:
sudo ufw enableExpected Output:
Firewall is active and enabled on system startupExample 2: Allow SSH traffic:
sudo ufw allow ssh# orsudo ufw allow 22# orsudo ufw allow proto tcp to any port 22Expected Output:
Rule addedRule added (v6)Example 3: Allow HTTP traffic:
sudo ufw allow http# orsudo ufw allow 80Expected Output:
Rule addedRule added (v6)Example 4: Deny all traffic from a specific IP address:
sudo ufw deny from 192.168.1.100Expected Output:
Rule addedRule added (v6)Example 5: Show the firewall status:
sudo ufw statusExpected Output:
Status: active
To Action From-- ------ ----22 ALLOW Anywhere80 ALLOW Anywhere192.168.1.100 DENY Anywhere22 (v6) ALLOW Anywhere (v6)80 (v6) ALLOW Anywhere (v6)192.168.1.100 (v6) DENY Anywhere (v6)Example 6: Show numbered rules:
sudo ufw status numberedExpected Output:
Status: active
To Action From -- ------ ----[ 1] 22 ALLOW Anywhere[ 2] 80 ALLOW Anywhere[ 3] 192.168.1.100 DENY Anywhere[ 4] 22 (v6) ALLOW Anywhere (v6)[ 5] 80 (v6) ALLOW Anywhere (v6)[ 6] 192.168.1.100 (v6) DENY Anywhere (v6)Example 7: Delete a rule (using the number from ufw status numbered):
sudo ufw delete 1Expected Output:
Deleting: allow 22Proceed with operation (y|n)? yRule deletedRule deleted (v6)Example 8: Disable the firewall:
sudo ufw disableExpected Output:
Firewall stopped and disabled on system startup4. Common Options
Section titled “4. Common Options”iptables
Section titled “iptables”-A chain: Append a rule to the end of the chain.-I chain [rulenum]: Insert a rule at the beginning (or specified position) of the chain.-D chain [rulenum]: Delete a rule from the chain (by rule number or rule specification).-L chain: List rules in the chain.-v(verbose),-n(numeric IP addresses),--line-numbers(show rule numbers).-F chain: Flush (delete all rules) in the chain. WARNING: Use with caution!-X chain: Delete a user-defined chain. WARNING: Use with caution!-P chain target: Set the default policy for the chain (e.g.,ACCEPT,DROP,REJECT). WARNING: Use with caution!-s source: Specify the source IP address or network.-d destination: Specify the destination IP address or network.-p protocol: Specify the protocol (e.g.,tcp,udp,icmp).--sport port: Specify the source port.--dport port: Specify the destination port.-j target: Specify the target action (e.g.,ACCEPT,DROP,REJECT,LOG).-m module: Load an extension module (e.g.,state,limit,conntrack).--state state: Match connection state (e.g.,NEW,ESTABLISHED,RELATED). Requires-m conntrack.
enable: Enable the firewall.disable: Disable the firewall.allow: Allow traffic. Can specify port, protocol, and source/destination.deny: Deny traffic. Can specify port, protocol, and source/destination.reject: Reject traffic (sends an ICMP error message). Can specify port, protocol, and source/destination.status: Show the firewall status.status numbered: Show the firewall status with rule numbers.delete [rulenum]: Delete a rule by its number (obtained fromufw status numbered).reset: Reset the firewall to its default state. WARNING: This will delete all existing rules!logging on|off: Enable or disable logging.logging level: Set the logging level (e.g.,off,low,medium,high).default allow|deny incoming|outgoing: Set the default policy for incoming or outgoing traffic. WARNING: Setting a default deny policy without allowing essential services can lock you out!
5. Advanced Usage
Section titled “5. Advanced Usage”iptables
Section titled “iptables”Example 1: Allow established and related connections (essential for outgoing connections to work):
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPTExample 2: Limit the rate of incoming SSH connections to prevent brute-force attacks:
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m limit --limit 3/minute --limit-burst 5 -j ACCEPTsudo iptables -A INPUT -p tcp --dport 22 -j DROPExplanation:
- The first rule allows a maximum of 3 new SSH connections per minute, with a burst of 5.
- The second rule drops any SSH connections that exceed the limit.
Example 3: Log dropped packets:
sudo iptables -A INPUT -j LOG --log-prefix "IPTABLES DROP: "sudo iptables -A INPUT -j DROPExplanation:
- The
LOGtarget writes a message to the system log (/var/log/syslogor/var/log/messages). - The
--log-prefixoption allows you to easily identify the logged packets. - This example logs all dropped packets; you can refine the rule to log specific traffic.
Example 4: Forward traffic from port 80 to port 8080 (port forwarding):
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080Explanation:
- This rule uses the
nattable and thePREROUTINGchain. - It redirects all TCP traffic on port 80 to port 8080 on the same machine.
- Important: You may need to enable IP forwarding in
/etc/sysctl.confby uncommentingnet.ipv4.ip_forward=1and then runningsudo sysctl -p.
Example 5: Block a specific country using ipset and country code:
First, install ipset:
sudo apt-get install ipset #Debian/Ubuntusudo yum install ipset #CentOS/RHELThen, create a set and populate it with the country’s IP ranges (example: China - CN):
sudo ipset create china hash:netwget -O - 'http://www.ipdeny.com/ipblocks/data/countries/cn.zone' | while read ip; do sudo ipset add china $ip; doneFinally, block the IPs in the china set:
sudo iptables -A INPUT -m set --match-set china src -j DROPExplanation:
ipsetallows you to efficiently manage and match large sets of IP addresses.- This example downloads IP ranges for China and adds them to the
chinaset. - The
iptablesrule drops all traffic originating from any IP address in thechinaset.
Example 1: Allow a specific IP address to access a specific port:
sudo ufw allow from 192.168.1.100 to any port 22 proto tcpExample 2: Allow a range of ports:
sudo ufw allow 30000:30010/tcpExample 3: Limiting connections (similar to iptables, but simpler syntax):
sudo ufw limit sshThis limits SSH connections to six attempts within 30 seconds, preventing brute-force attacks.
Example 4: Allowing a specific subnet access to a port:
sudo ufw allow from 192.168.1.0/24 to any port 3306Example 5: Setting default policies (use with caution):
sudo ufw default deny incomingsudo ufw default allow outgoingThis denies all incoming connections and allows all outgoing connections. Make sure to allow SSH and other necessary services before setting these defaults, or you risk locking yourself out!
6. Tips & Tricks
Section titled “6. Tips & Tricks”iptables
Section titled “iptables”-
Test your rules before saving them: Add a rule and test it before saving it. If it breaks your connectivity, you can easily revert it.
-
Use comments: Add comments to your rules to explain their purpose. While
iptablesitself doesn’t directly support comments, you can use shell scripting to achieve this:Terminal window # Allow SSH trafficsudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT -
Back up your rules: Before making significant changes, back up your existing
iptablesrules. -
Reload rules without rebooting: You can reload your
iptablesrules without rebooting the system:Terminal window sudo iptables-restore < /etc/iptables/rules.v4 # Debian/Ubuntusudo iptables-restore < /etc/sysconfig/iptables # RHEL/CentOS -
Use
iptables-persistent(Debian/Ubuntu): This package automatically saves and restores youriptablesrules on reboot. Install it withsudo apt-get install iptables-persistent. -
Use
firewalld(CentOS/RHEL):firewalldis a dynamic firewall manager that provides a more user-friendly interface thaniptablesdirectly. It’s the default firewall on many modern RHEL-based systems. If you’re using CentOS 7 or later, consider usingfirewalldinstead ofiptablesdirectly. However, this cheatsheet focuses oniptablesfor its widespread use and fundamental understanding.
- Resetting
ufw: Usesudo ufw resetto return the firewall to its default state. This is useful if you’ve made a mistake and want to start over. WARNING: This will delete all existing rules! - Enable logging: Use
sudo ufw logging onto enable logging. This can help you troubleshoot firewall issues. Set the logging level withsudo ufw logging level. - Use application profiles:
ufwcomes with pre-defined application profiles for common services. List them withsudo ufw app listand allow them withsudo ufw allow <app_profile>. For example:sudo ufw allow "Nginx HTTP". - Check default policies before enabling: Always verify the default incoming/outgoing policies with
sudo ufw statusbefore enabling the firewall, especially after making changes. - Use symbolic names: When possible, use symbolic names for services instead of port numbers (e.g.,
ssh,http,https). This makes your rules more readable and easier to understand.
7. Troubleshooting
Section titled “7. Troubleshooting”iptables
Section titled “iptables”- Connectivity issues: If you’re experiencing connectivity issues after adding
iptablesrules, check the following:- Are you allowing established and related connections?
- Are you blocking necessary ports?
- Is the rule order correct? Rules are processed in order, so a more general rule might be blocking traffic before a more specific rule can allow it.
- Rules not persisting after reboot: Make sure you’re saving your
iptablesrules correctly (usingiptables-saveand the appropriate configuration file for your distribution) and that theiptables-persistentpackage (or equivalent) is installed and configured to load the rules on boot. - Conflicting rules: Carefully review your rules to ensure they don’t conflict with each other. Use
iptables -L -v -nto see the rules and their counters. - Logging: Enable logging to see which packets are being dropped or rejected.
- Firewall not enabled: Verify that the firewall is enabled with
sudo ufw status. - Connectivity issues: If you’re experiencing connectivity issues after enabling
ufw, check the following:- Are you allowing SSH traffic?
- Are you blocking necessary ports?
- Did you set the default policies correctly?
- Rules not working as expected: Use
sudo ufw status numberedto see the rule numbers and then usesudo ufw delete <rulenum>to remove the problematic rule. - Logging: Enable logging with
sudo ufw logging onand check the system logs for firewall-related messages. - Resetting the firewall: If you’re completely stuck, try resetting the firewall with
sudo ufw reset. WARNING: This will delete all existing rules!
Common Errors and Solutions:
- “iptables: No chain/target/match by that name”: This usually means that the specified chain, target, or module is not available. Double-check the spelling and make sure the necessary kernel modules are loaded. For example, if you’re using
--state, make sure theconntrackmodule is loaded. - “ufw: command not found”: Make sure
ufwis installed on your system. Usesudo apt-get install ufw(Debian/Ubuntu) orsudo yum install ufw(CentOS/RHEL) to install it. - “ufw: Firewall is disabled”: Enable the firewall using
sudo ufw enable. - Locked out of your server: If you accidentally lock yourself out of your server by blocking SSH traffic, you’ll need to access the server through a console (e.g., through your cloud provider’s web interface) to fix the firewall configuration. Alternatively, if you have scheduled tasks to run, you can use them to re-enable the firewall or allow your IP.
8. Related Commands
Section titled “8. Related Commands”netstat: Displays network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.ss: Another utility to investigate sockets.sscan display more TCP and state information thannetstatand it is faster.tcpdump: A powerful command-line packet analyzer. It allows you to capture and inspect network traffic.traceroute: Traces the route packets take to a destination.ping: Tests network connectivity to a host.firewalld: Another firewall management tool, often used on CentOS/RHEL systems.sysctl: Used to configure kernel parameters, including network settings like IP forwarding.
This cheatsheet provides a solid foundation for managing firewalls using iptables and ufw. Remember to always test your rules thoroughly and back up your configuration before making significant changes. Good luck!