How to do it...

We will configure Iptables to deny everything, except the traffic that has been initiated from inside our system (for example, the web browsers have web traffic, or some downloading has already been initiated earlier for updating the package or any other software):

  1. As in the previous examples, our first rule in Iptables will be to allow access to localhost data. Run the following command to do this:
    iptables -A INPUT -i lo -j ACCEPT  

  1. Our next rule will be for accepting all traffic related to outbound connections. This also includes the responses from the remote server to which our system is connecting:

  1. Next, we will add the rule to accept Time Exceeded ICMP packets. This is important for time-restricted connection setups:
    iptables -A INPUT -p icmp -m icmp --icmp-type 11 -j ACCEPT   
  1. After this, we will add the rule to accept Destination Unreachable ICMP packets coming from remote servers:
    iptables -A INPUT -p icmp -m icmp --icmp-type 3/4 -j ACCEPT
  1. Next, add the rule to accept PING requests/responses (Echo ICMP) to keep our system's connections alive to those web services that may require PING:
    iptables -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT  
  1. Once the preceding rules have been added, we check the list in Iptables by running the following command:
    iptables -L 

  1. Now, we will create a table of iptables, which will contain a list of acceptable rules and services:
    iptables -N allowed_ip  

We will then add this table to the INPUT chain of Iptables:

    iptables -A INPUT -j allowed_ip  
  1. Now, let's add a rule so that access to SSH is allowed on the system. To do so, we can run the following command:
    iptables -A allowed_ip -p tcp --dport 22 -j ACCEPT
  1. Now, if we check the list of rules in iptables, we get the following result:
 iptables -L 

  1. Once we have added the rules to accept the traffic we want to, we now want to reject all other traffic for which no rules have been set. To do so, we add the following rule:
    iptables -A INPUT -j REJECT --reject-with icmp-host-unreachable
  

By doing this, whenever anyone tries to connect to the server, a Host Unreachable ICMP packet will be sent to them that would then terminate the connection attempt.

  1. After adding all the aforementioned given rules, our iptables will now look like what's shown in the following screenshot: