

However, you can also set rules that permit or block specific IP addresses.įor example, suppose you find in your server log files that there are repeated SSH login attempts from a particular IP address. The rules above define access by service (SSH, HTTP, etc.). To quickly view the line numbers for all of the rules in a chain, type the following command: iptables -L -line-numbers Blocking an IP address Now if you type the iptables -L command, you should see the following output: Chain INPUT (policy ACCEPT)ĪCCEPT tcp - anywhere anywhere tcp dpt:http This inserts our HTTP rule in the fourth line, and pushes the DROP rule down to the fifth line. We want the rule to come just before the DROP rule, which is currently the fourth rule in the chain: iptables -I INPUT 4 -p tcp -m tcp -dport 80 -j ACCEPT Let's insert a rule that allows incoming TCP connections on port 80 (HTTP). The -I option enables us to insert a new rule anywhere in the chain. Therefore, we need a way to insert new rules into the chain. Because iptables works through rules in sequence, this means that it will never get to the new rule, because the packet will have already been dropped. However, if we just add a rule using the -A option shown above, it will be the last rule in the chain, right after our DROP rule. Most likely, though, you will need to add access to services as you configure your server. If SSH is the only incoming connection you want to allow, then you're all set. The set of rules we defined above is pretty limited. Connections on any other ports, however (such as an HTTP connection on port 80) will be rejected. To test the configuration, try connecting to the server using SSH. Now if you type the iptables -L command, you should see the following output: Chain INPUT (policy ACCEPT)ĪCCEPT all - anywhere anywhere state RELATED,ESTABLISHEDĪCCEPT tcp - anywhere anywhere tcp dpt:7822

You can verify this yourself on a new server by typing the following command: iptables -L Chain INPUT (policy ACCEPT)Īs you can see, there are no targets and no destinations defined. Adding rulesīy default, iptables does not have any rules defined. The iptables program is included in most major Linux distributions by default, including Debian, Ubuntu, CentOS and Fedora. In this article we will only work with the INPUT chain to selectively block and accept incoming packets to the server. By default, iptables uses three chains: INPUT (for incoming packets), FORWARD (for forwarding packets), and OUTPUT (for outgoing packets). To do this, you define sets of rules, which are grouped together into chains. You can grant or deny access to specific network services (such as SSH, HTTP, and so on), as well as permit or block specific IP addresses from connecting to the server.

The iptables program enables you to view and modify the Linux kernel's built-in network packet filtering capabilities.
