Using IP Tables to Setup Firewall on Ubuntu Servers

By Default a new server on Digital Ocean or any other provider accepts incoming requests from every IP and of all types. We can filter the request types or whitelist IP to accept requeest.

On Terminal

sudo iptables -L

gives details about rules defined in IP Table

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

It clearly shows that no rules are defined by default. Now we start adding rules to the IP Table. To add a rule

    sudo /sbin/iptables -A INPUT -i eth0 -s 10.5.1.3  -p tcp --destination-port 3306 -j ACCEPT

    sudo /sbin/iptables -I INPUT 2 -i eth0 -p tcp --destination-port 80 -j ACCEPT

-s –> Source IP.

-A –> To insert a rule set

-I –> To insert a rule set at a specific poistion e.g 4 here

-INPUT –> To specify the group for inserting rule

---destination-port –> Port to accept the connections. 3036 for mysql, 80 for http requests

-j –> To specify what action to perform on request. It can be -ACCEPT, -REJECT, -DROP, -LOG

sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  10.5.1.3             anywhere            tcp dpt:mysql
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:http

T0 delete a Rule we simply do

sudo iptables -D INPUT 2

-D –> Delete a rule at mentioned place.

sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  10.5.1.3             anywhere            tcp dpt:mysql

Now rule with http is deleted.

As soon as our server restarts, our IP Table resets to defaults. To make it persistent and permanent we use a package IP-Tables persistent.

sudo apt-get install iptables-persistent

After installation run

sudo service iptables-persistent start

Now after any server reboot we will still have our IP Table rules.

Sources :

Comments