Linux IPTables: How to Add Firewall Rules (With Allow SSH Example) (2024)

Linux IPTables: How to Add Firewall Rules (With Allow SSH Example) (1)This article explains how to add iptables firewall rules using the “iptables -A” (append) command.

“-A” is for append. If it makes it easier for you to remember “-A” as add-rule (instead of append-rule), it is OK. But, keep in mind that “-A” adds the rule at the end of the chain.

Again, it is very important to remember that -A adds the rule at the end.

Typically the last rule will be to drop all packets. If you already have a rule to drop all packets, and if you try to use “-A” from the command-line to create new rule, you will end-up adding the new rule after the current “drop all packets” rule, which will make your new rule pretty much useless.

Once you’ve mastered the iptables, and when you are implementing it on production, you should use a shell script, where you use -A command to add all the rules. In that shell script, your last line should always be “drop all packets” rule. When you want to add any new rules, modify that shell script and add your new rules above the “drop all packets” rule.

Syntax:

iptables -A chain firewall-rule
  • -A chain – Specify the chain where the rule should be appended. For example, use INPUT chain for incoming packets, and OUTPUT for outgoing packets.
  • firewall-rule – Various parameters makes up the firewall rule.

If you don’t know what chain means, you better read about iptables fundamentals first.

Firewall Rule Parameters

The following parameters are available for all kinds of firewall rules.

-p is for protocol

  • Indicates the protocol for the rule.
  • Possible values are tcp, udp, icmp
  • Use “all” to allow all protocols. When you don’t specify -p, by default “all” protocols will be used. It is not a good practice to use “all”, and always specify a protocol.
  • Use either the name (for example: tcp), or the number (for example: 6 for tcp) for protocol.
  • /etc/protocols file contains all allowed protocol name and number.
  • You an also use –protocol

-s is for source

  • Indicates the source of the packet.
  • This can be ip address, or network address, or hostname
  • For example: -s 192.168.1.101 indicates a specific ip address
  • For network mask use /mask. For example: “-s 192.168.1.0/24” represents a network mask of 255.255.255.0 for that network. This matches 192.168.1.x network.
  • When you don’t specify a source, it matches all source.
  • You can also use –src or –source

-d is for destination

  • Indicates the destination of the packet.
  • This is same as “-s” (except this represents destination host, or ip-address, or network)
  • You can also use –dst or –destination

-j is target

  • j stands for “jump to target”
  • This specifies what needs to happen to the packet that matches this firewall rule.
  • Possible values are ACCEPT, DROP, QUEUE, RETURN
  • You can also specify other user defined chain as target value.

-i is for in interface

  • i stands for “input interface”
  • You might over look this and assume that “-i” is for interface. Please note that both -i and -o are for interfaces. However, -i for input interface and -o for output interface.
  • Indicates the interface through which the incoming packets are coming through the INPUT, FORWARD, and PREROUTING chain.
  • For example: -i eth0 indicates that this rule should consider the incoming packets coming through the interface eth0.
  • If you don’t specify -i option, all available interfaces on the system will be considered for input packets.
  • You can also use –in-interface

-o is for out interface

  • o stands for “output interface”
  • Indicates the interface through which the outgoing packets are sent through the INPUT, FORWARD, and PREROUTING chain.
  • If you don’t specify -o option, all available interfaces on the system will be considered for output packets.
  • You can also use –out-interface

Additional Options for Firewall Parameters

Some of the above firewall parameters in turn has it’s own options that can be passed along with them. Following are some of the most common options.

To use these parameter options, you shouldspecify the corresponding parameter in the firewall rule. For example, to use “–sport” option, you should’ve specified “-p tcp” (or “-p udp”) parameter in your firewall rule.

Note: All of these options have two dashes in front of them. For example, there are two hyphens in front of sport.

–sport is for source port (for -p tcp, or -p udp)

  • By default all source ports are matched.
  • You can specify either the port number or the name. For example, to use SSH port in your firewall rule, use either “–sport 22” or “–sport ssh”.
  • /etc/services file contains all allowed port name and number.
  • Using port number in the rule is better (for performance) than using port name.
  • To match range of ports, use colon. For example, 22:100 matches port number from 22 until 100.
  • You can also use –source-port

–dport is for destination port (for -p tcp, or -p udp)

  • Everything is same as –sport, except this is for destination ports.
  • You can also use –destination-port

–tcp-flags is for TCP flags (for -p tcp)

  • This can contain multiple values separated by comma.
  • Possible values are: SYN, ACK, FIN, RST, URG, PSH. You can also use ALL or NONE

–icmp-type is for ICMP Type (for -p icmp)

  • When you use icmp protocol “-p icmp”, you can also specify the ICMP type using “–icmp-type” parameter.
  • For example: use “–icmp-type 0” for “Echo Reply”, and “–icmp-type 8” for “Echo”.

Example Firewall Rule to Allow Incoming SSH Connections

Now that you understand various parameters (and it’s options) of firewall rule, let us build a sample firewall rule.

In this example, let us allow only the incoming SSH connection to the server. All other connections will be blocked (including ping).

WARNING: Playing with firewall rules might render your system inaccessible. If you don’t know what you are doing, you might lock yourself (and everybody else) out of the system. So, do all your learning only on a test system that is not used by anybody, and you have access to the console to restart the iptables, if you get locked out.

1. Delete Existing Rules

If you already have some iptables rules, take a backup before delete the existing rules.

Delete all the existing rules and allow the firewall to accept everything. Use iptables flush as we discussed earlier to clean-up all your existing rules and start from scratch.

Test to make sure you are able to ssh and ping this server from outside.

When we are done with this example, you’ll only be able to SSH to this server. You’ll not be able to ping this server from outside.

2. Allow only SSH

Allow only the incoming SSH connection to this server. You can ssh to this server from anywhere.

iptables -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT

The above iptables command has the following 4 components.

  • “-A INPUT” – This indicates that we are appending a new rule (or adding) to the INPUT chain. So, this rule is for incoming traffic.
  • “-i eth0” – Incoming packets through the interface eth0 will be checked against this rule.
  • “-p tcp –dport 22” – This rule is for TCP packets. This has one tcp option called “–dport 22”, which indicates that the destination port for this rule on the server is 22 (which is ssh).
  • “-j ACCEPT” – Jump to accept, which just ACCEPTS the packet.

In simple terms the above rule can be stated as: All incoming packets through eth0 for ssh will be accepted.

3. Drop all Other Packets

Once you’ve specified your custom rules to accept packets, you should also have a default rule to drop any other packets.

This should be your last rule in the INPUT chain.

To drop all incoming packets, do the following.

iptables -A INPUT -j DROP

4. View the SSH rule and Test

To view the current iptables firewall rules, use “iptables -L” command.

# iptables -LChain INPUT (policy ACCEPT)target prot opt source destinationACCEPT tcp -- anywhere anywhere tcp dpt:sshDROP all -- anywhere anywhere

As you see from the above output, it has the following two rules in sequence.

  • Accept all incoming ssh connections
  • Drop all other packets.

Instead of adding the firewall rules from the command line, it might be better to create a shell script that contains your rules as shown below.

# vi iptables.shiptables -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPTiptables -A INPUT -j DROP# sh -x iptables.sh+ iptables -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT+ iptables -A INPUT -j DROP# iptables -L INPUTChain INPUT (policy ACCEPT)target prot opt source destinationACCEPT tcp -- anywhere anywhere tcp dpt:sshDROP all -- anywhere anywhere

Similar to iptables append/add command, there are few other commands available for iptables. I’ll cover them in the upcoming articles in the iptables series. I’ll also provide several practical firewall rule examples that will be helpful in real life scenarios.

Previous articles in the iptables series:

  • Linux Firewall Tutorial: IPTables Tables, Chains, Rules Fundamentals
  • IPTables Flush: Delete / Remove All Rules On RedHat and CentOS Linux
Linux IPTables: How to Add Firewall Rules (With Allow SSH Example) (2024)

FAQs

Linux IPTables: How to Add Firewall Rules (With Allow SSH Example)? ›

Example Firewall Rule to Allow Incoming SSH Connections
  1. Delete Existing Rules. If you already have some iptables rules, take a backup before delete the existing rules. ...
  2. Allow only SSH. Allow only the incoming SSH connection to this server. ...
  3. Drop all Other Packets. ...
  4. View the SSH rule and Test.
Feb 14, 2011

How do I add firewall rules to iptables? ›

To insert a new rule above a specific existing rule, simply use the index number of that existing rule. For example to insert a new rule to the top of the chain, use the following command with index number 1. It's also possible to flush all rules of a specific chain or even the whole iptables using the -F -parameter.

How do I enable ssh in iptables? ›

Firewall iptables rules
  1. Allow SSH session to firewall 2 by using the following command: iptables -A INPUT -p tcp --dport 22 -s 0/0 -j ACCEPT.
  2. Allow ICMP traffic to firewall 2 by using the following command: ...
  3. Allow all related and established traffic for firewall 2 by using the following command:

How do I add a rule to my firewall in Linux? ›

The flag -A is used to append a rule to the end of a chain. This part of the command tells the iptable that we want to add a rule to the end of the INPUT chain. In this flag the rules are added to the top of the chain. This specifies what the iptable should do with the packet.

What are the commands to set up iptables rules to allow all SSH traffic coming in? ›

Allowing All Incoming SSH

To allow all incoming SSH connections run these commands: sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT. sudo iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT.

How do I allow a port in iptables? ›

Individual commands method
  1. Run the following command to allow traffic on port 80: sudo iptables -I INPUT -p tcp -m tcp --dport 80 -j ACCEPT.
  2. Run the following command to allow traffic on port 443: sudo iptables -I INPUT -p tcp -m tcp --dport 443 -j ACCEPT.
Mar 27, 2020

How set iptables rule in Linux? ›

Configuring IPtables
  1. Using SSH, log in to your Linux Server as a root user.
  2. Edit the IPtables file in the following directory: ...
  3. Review the file to determine the IPtables rule you want to log. ...
  4. Insert a matching rule immediately before each rule you want to log:

How do I open a port for SSH? ›

To change the port for the SSH server, follow these steps:
  1. Log in to the server as root using SSH.
  2. Open the /etc/ssh/sshd_config file in your preferred text editor (nano, vi, etc.).
  3. Locate the following line: Port 7822. ...
  4. Change 7822 to the new port number that you want to use.

Why is my SSH connection refused? ›

Typos or incorrect credentials are common reasons for a refused SSH connection. Make sure you are not mistyping the username or password. Then, check whether you are using the correct IP address of the server.

How do I check firewall rules in Linux? ›

How to list all iptables rules on Linux
  1. Open the terminal app or login using ssh command: $ ssh user@server-name.
  2. To list all IPv4 rules: $ sudo iptables -S.
  3. Get list of all IPv6 rules: $ sudo ip6tables -S.
  4. To list all tables rules: $ sudo iptables -L -v -n | more.
  5. Just list all rules for INPUT tables:
Aug 11, 2022

How do you set firewall rules? ›

Description
  1. On the client operating system, go to Start > Run and type firewall. ...
  2. Click on the “Advanced Settings” link on the left pane. ...
  3. Click on the “Inbound Rules” option.
  4. On the left pane, click on “New rule”.
  5. Under “Rule Type” select the option “Port” and click next.
  6. Select “TCP”and “specific local ports” options.
Jul 20, 2021

How do I create a firewall rule? ›

Add a new rule
  1. Create a new rule. Click New > New Firewall Rule.
  2. Import a rule from an XML file. Click New > Import From File.
  3. Copy and then modify an existing rule. Right-click the rule in the Firewall Rules list and then click Duplicate. To edit the new rule, select it and then click Properties.

How do I allow access to firewall ports in Linux? ›

Click Security and Users > Firewall. Select the Allowed Services tab and click Advanced.... Enter the desired port range in the from-port-start:to-port-end format and specify the protocol (TCP or UDP). For example, enter 60000:60010 to open ports 60000 to 60010.

Do I need to restart iptables after adding a rule? ›

Yes, once you have added a rule to iptables it becomes active immediately - this is why you should be careful with your rules as it is possible to lock yourself out.

How do I set inbound and outbound rules in Linux? ›

Linux IPTables: Incoming and Outgoing Rule Examples (SSH and HTTP)
  1. Delete all existing rules: “iptables -F”
  2. Allow only incoming SSH: “iptables -A INPUT -i eth0 -p tcp –dport 22 -j ACCEPT”
  3. Drop all other incoming packets: “iptables -A INPUT -j DROP”
Mar 15, 2011

What is iptables firewall in Linux? ›

Iptables is a Linux command line firewall that allows system administrators to manage incoming and outgoing traffic via a set of configurable table rules. Iptables uses a set of tables which have chains that contain set of built-in or user defined rules.

How do I enable port 8080 in iptables? ›

As stated above first have to disable selinux.
  1. Step 1 nano /etc/sysconfig/selinux. ...
  2. Step 2 iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT.
  3. Step 3 sudo service iptables save.
  4. For Cent OS 7.
  5. step 1 firewall-cmd --zone=public --permanent --add-port=8080/tcp.
  6. Step 2 firewall-cmd --reload.
Sep 26, 2013

What port does SSH use? ›

By default, the SSH server still runs in port 22.

How do I whitelist a port in Linux? ›

Steps
  1. Log in to your Linux server and/or open a Terminal window. ...
  2. Run service iptables status to make sure your firewall is active. ...
  3. Use sudo iptables -L to list the current firewall rules. ...
  4. Use sudo iptables -I INPUT -p tcp -m tcp --dport 22 -j ACCEPT to open a port. ...
  5. Use sudo service iptables save to save your changes.
Aug 10, 2022

What is the difference between iptables and firewalld? ›

The firewall

On the one hand, iptables is a tool for managing firewall rules on a Linux machine. On the other hand, firewalld is also a tool for managing firewall rules on a Linux machine.

How do I check firewall settings on Linux? ›

1. Check Firewall setup
  1. Verify Firewall running state and settings:
  2. Firewall status: (should reply running) $ sudo firewall-cmd --state output. running.
  3. Firewall default and active zone: $ firewall-cmd --get-default-zone output. public $ firewall-cmd --get-active-zones output. public. interfaces: eth0.

How do I configure an iptables firewall to enable remote access to services in Linux? ›

Ubuntu: Install the iptables-persistent package, which will load the rules saved in the /etc/iptables/rules. v4 file. CentOS: Add the following 2 lines to /etc/sysconfig/iptables-config file. OpenSUSE: List allowed ports, protocols, addresses, and so forth (separated by commas) in /etc/sysconfig/SuSEfirewall2.

How do I enable SSH on my firewall? ›

Configure the Windows Firewall
  1. Click on Start --> Control Panel --> Windows Firewall --> Exceptions Tab.
  2. Click the Add Port... button.
  3. Name: SSH.
  4. Port Number: 22.
  5. TCP.
  6. Click OK to add the SSH exception to the firewall.
  7. Click OK to close the Windows Firewall screen.

How do I check if port 22 is open on Linux? ›

How to check if port 22 is open in Linux
  1. Run the ss command and it will display output if port 22 opened: sudo ss -tulpn | grep :22.
  2. Another option is to use the netstat: sudo netstat -tulpn | grep :22.
  3. We can also use the lsof command to see if ssh port 22 status: sudo lsof -i:22.
Sep 21, 2020

How do I enable SSH on Linux server? ›

Enable the ssh service by typing: # sudo systemctl enable ssh. Start the ssh service by typing: # sudo systemctl start ssh. Test it by login into the system using:# ssh userName@Your-server-name-IP.

How do I know if SSH is enabled? ›

To check if the client is available on your Linux-based system, you will need to:
  1. Load an SSH terminal. You can either search for “terminal” or press CTRL + ALT + T on your keyboard.
  2. Type in ssh and press Enter in the terminal.
  3. If the client is installed, you will receive a response that looks like this:
Sep 24, 2018

How do I fix SSH port 22 connection refused? ›

  1. First check openssh-server installed in that system.
  2. check the status of ssh service, make ssh service start. sudo service ssh status sudo service ssh start.
  3. Check whether port 22 in that system is blocked by iptables . Just allow port in iptables and then check. ...
  4. Else change port number of ssh from 22 to 2222 by editing.

Why is port 22 often blocked by the firewall? ›

Sometimes while connecting to SSH servers, users often encounter “Connection refused” error by port 22. It happens because of several reasons like SSH service is not running, the port is blocked by the firewall, or the server is using a different port. It can also occur because of the IP conflict issue.

Which command is used for firewall in Linux? ›

All of these firewalls have their own configuration interface. This article covers the firewall-cmd terminal command found on most Linux distributions. Firewall-cmd is a front-end tool for managing the firewalld daemon, which interfaces with the Linux kernel's netfilter framework.

How do I check if a firewall is blocking a port Linux? ›

You can check if a process listens on a TCP or UDP port with netstat -tuplen . To check whether some ports are accessible from the outside (this is probably what you want) you can use a port scanner like Nmap from another system.

Can you use firewalld and iptables? ›

The firewalld service implements its firewall policies using normal iptables rules.It accomplishes this by building a management framework using iptables chains. Most of the rules you are likely to see will be used to create these management chains and direct the flow of traffic in and out of these structures.

How do I add a firewall exception? ›

Click Start and select Control Panel. Double-click Windows Firewall to open the Windows Firewall window. Click the Exceptions tab. Click the Add Port button.

How do I allow a port through my firewall? ›

Go to System Preferences, and choose the Security and Privacy Tab. From here, click on the Firewall Tab, and the Firewall options button. You will then be taken to a page that shows you the applications that are allowed access through your firewall, and can add new applications to the list by clicking on the plus icon.

Does firewalld use iptables? ›

The firewalld service implements its firewall policies using normal iptables rules.It accomplishes this by building a management framework using iptables chains. Most of the rules you are likely to see will be used to create these management chains and direct the flow of traffic in and out of these structures.

Do I need to restart iptables after adding a rule? ›

Yes, once you have added a rule to iptables it becomes active immediately - this is why you should be careful with your rules as it is possible to lock yourself out.

What iptables parameter is used to instruct the firewall to block packets? ›

Block or Allow Traffic by Port Number to Create an iptables Firewall. Let's break down the example above. The first two commands add or append rules to the INPUT chain in order to allow access on specific ports. The -p tcp and -p udp options specify either UDP or TCP packet types.

How do I set inbound and outbound rules in Linux? ›

Linux IPTables: Incoming and Outgoing Rule Examples (SSH and HTTP)
  1. Delete all existing rules: “iptables -F”
  2. Allow only incoming SSH: “iptables -A INPUT -i eth0 -p tcp –dport 22 -j ACCEPT”
  3. Drop all other incoming packets: “iptables -A INPUT -j DROP”
Mar 15, 2011

Top Articles
Latest Posts
Article information

Author: Pres. Lawanda Wiegand

Last Updated:

Views: 5724

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Pres. Lawanda Wiegand

Birthday: 1993-01-10

Address: Suite 391 6963 Ullrich Shore, Bellefort, WI 01350-7893

Phone: +6806610432415

Job: Dynamic Manufacturing Assistant

Hobby: amateur radio, Taekwondo, Wood carving, Parkour, Skateboarding, Running, Rafting

Introduction: My name is Pres. Lawanda Wiegand, I am a inquisitive, helpful, glamorous, cheerful, open, clever, innocent person who loves writing and wants to share my knowledge and understanding with you.