Skip to content

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.


  • 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. iptables interacts 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. ufw still relies on iptables under 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.

Terminal window
iptables [-t table] command [chain] [rule-specification] [options]
  • -t table: Specifies the table to use (e.g., filter, nat, mangle, raw). Default is filter.
  • 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).
Terminal window
ufw command [options]
  • command: Action to perform (e.g., enable, disable, allow, deny, status).
  • options: Additional options (e.g., numbered, logging).

Example 1: Allow SSH traffic (port 22) on the INPUT chain:

Terminal window
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Expected Output: (None, unless there is an error)

Example 2: Drop all traffic from a specific IP address:

Terminal window
sudo iptables -A INPUT -s 192.168.1.100 -j DROP

Expected Output: (None, unless there is an error)

Example 3: List all rules in the INPUT chain of the filter table:

Terminal window
sudo iptables -L INPUT -v -n

Expected 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/0

Example 4: Delete the first rule in the INPUT chain:

Terminal window
sudo iptables -D INPUT 1

Expected Output: (None, unless there is an error)

Example 5: Save iptables rules (important to persist rules after reboot):

Terminal window
# Debian/Ubuntu
sudo iptables-save > /etc/iptables/rules.v4
# RHEL/CentOS
sudo iptables-save > /etc/sysconfig/iptables

Expected Output: (None, unless there is an error). Check the file to confirm rules are saved.

Example 1: Enable the firewall:

Terminal window
sudo ufw enable

Expected Output:

Firewall is active and enabled on system startup

Example 2: Allow SSH traffic:

Terminal window
sudo ufw allow ssh
# or
sudo ufw allow 22
# or
sudo ufw allow proto tcp to any port 22

Expected Output:

Rule added
Rule added (v6)

Example 3: Allow HTTP traffic:

Terminal window
sudo ufw allow http
# or
sudo ufw allow 80

Expected Output:

Rule added
Rule added (v6)

Example 4: Deny all traffic from a specific IP address:

Terminal window
sudo ufw deny from 192.168.1.100

Expected Output:

Rule added
Rule added (v6)

Example 5: Show the firewall status:

Terminal window
sudo ufw status

Expected Output:

Status: active
To Action From
-- ------ ----
22 ALLOW Anywhere
80 ALLOW Anywhere
192.168.1.100 DENY Anywhere
22 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
192.168.1.100 (v6) DENY Anywhere (v6)

Example 6: Show numbered rules:

Terminal window
sudo ufw status numbered

Expected 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):

Terminal window
sudo ufw delete 1

Expected Output:

Deleting:
allow 22
Proceed with operation (y|n)? y
Rule deleted
Rule deleted (v6)

Example 8: Disable the firewall:

Terminal window
sudo ufw disable

Expected Output:

Firewall stopped and disabled on system startup

  • -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 from ufw 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!

Example 1: Allow established and related connections (essential for outgoing connections to work):

Terminal window
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Example 2: Limit the rate of incoming SSH connections to prevent brute-force attacks:

Terminal window
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m limit --limit 3/minute --limit-burst 5 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -j DROP

Explanation:

  • 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:

Terminal window
sudo iptables -A INPUT -j LOG --log-prefix "IPTABLES DROP: "
sudo iptables -A INPUT -j DROP

Explanation:

  • The LOG target writes a message to the system log (/var/log/syslog or /var/log/messages).
  • The --log-prefix option 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):

Terminal window
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

Explanation:

  • This rule uses the nat table and the PREROUTING chain.
  • 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.conf by uncommenting net.ipv4.ip_forward=1 and then running sudo sysctl -p.

Example 5: Block a specific country using ipset and country code:

First, install ipset:

Terminal window
sudo apt-get install ipset #Debian/Ubuntu
sudo yum install ipset #CentOS/RHEL

Then, create a set and populate it with the country’s IP ranges (example: China - CN):

Terminal window
sudo ipset create china hash:net
wget -O - 'http://www.ipdeny.com/ipblocks/data/countries/cn.zone' | while read ip; do sudo ipset add china $ip; done

Finally, block the IPs in the china set:

Terminal window
sudo iptables -A INPUT -m set --match-set china src -j DROP

Explanation:

  • ipset allows you to efficiently manage and match large sets of IP addresses.
  • This example downloads IP ranges for China and adds them to the china set.
  • The iptables rule drops all traffic originating from any IP address in the china set.

Example 1: Allow a specific IP address to access a specific port:

Terminal window
sudo ufw allow from 192.168.1.100 to any port 22 proto tcp

Example 2: Allow a range of ports:

Terminal window
sudo ufw allow 30000:30010/tcp

Example 3: Limiting connections (similar to iptables, but simpler syntax):

Terminal window
sudo ufw limit ssh

This limits SSH connections to six attempts within 30 seconds, preventing brute-force attacks.

Example 4: Allowing a specific subnet access to a port:

Terminal window
sudo ufw allow from 192.168.1.0/24 to any port 3306

Example 5: Setting default policies (use with caution):

Terminal window
sudo ufw default deny incoming
sudo ufw default allow outgoing

This 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!


  • 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 iptables itself doesn’t directly support comments, you can use shell scripting to achieve this:

    Terminal window
    # Allow SSH traffic
    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  • Back up your rules: Before making significant changes, back up your existing iptables rules.

  • Reload rules without rebooting: You can reload your iptables rules without rebooting the system:

    Terminal window
    sudo iptables-restore < /etc/iptables/rules.v4 # Debian/Ubuntu
    sudo iptables-restore < /etc/sysconfig/iptables # RHEL/CentOS
  • Use iptables-persistent (Debian/Ubuntu): This package automatically saves and restores your iptables rules on reboot. Install it with sudo apt-get install iptables-persistent.

  • Use firewalld (CentOS/RHEL): firewalld is a dynamic firewall manager that provides a more user-friendly interface than iptables directly. It’s the default firewall on many modern RHEL-based systems. If you’re using CentOS 7 or later, consider using firewalld instead of iptables directly. However, this cheatsheet focuses on iptables for its widespread use and fundamental understanding.

  • Resetting ufw: Use sudo ufw reset to 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 on to enable logging. This can help you troubleshoot firewall issues. Set the logging level with sudo ufw logging level.
  • Use application profiles: ufw comes with pre-defined application profiles for common services. List them with sudo ufw app list and allow them with sudo 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 status before 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.

  • Connectivity issues: If you’re experiencing connectivity issues after adding iptables rules, 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 iptables rules correctly (using iptables-save and the appropriate configuration file for your distribution) and that the iptables-persistent package (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 -n to 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 numbered to see the rule numbers and then use sudo ufw delete <rulenum> to remove the problematic rule.
  • Logging: Enable logging with sudo ufw logging on and 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 the conntrack module is loaded.
  • “ufw: command not found”: Make sure ufw is installed on your system. Use sudo apt-get install ufw (Debian/Ubuntu) or sudo 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.

  • netstat: Displays network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.
  • ss: Another utility to investigate sockets. ss can display more TCP and state information than netstat and 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!