How to Use IPTABLE *filters

What a night? Github being teased by a DDOS attack originating from an analytic script by Baidu which is probably in MITM attack by some unknown source. And slack just revel that one of their database server faces an unauthroized access where they store our user profile informations and hashed passwords. I have been using iptable rules to filter some restricted resources over a rails instance lately and came to think if I share the trick here on my blog.

Mostly you may be using a proxy server, like nginx and apache, over your application instance which is backed by php-fpm or passenger processes depending on your application stack. What I am going to do is set some suitable iptable rules which would standardize the incoming and outgoing TCP requests as mentioned below.

Most of the distro comes with IPTABLE preinstalled. But if it is not,

1
$ sudo apt-get install iptables 

Create a new file under etc with root.

1
2
$ touch /etc/iptable.server.rules
$ vi /etc/iptable.server.rules

And fill the file with these contents.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
*filter

# proxy servers make request internally to redirect some requests
# so allow local request with your system
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT

# allow web request from * 
# 443 for https 80 for http
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT

# sometimes you test the system is down >> not
# allow ping 
-A INPUT -p icmp --icmp-type echo-request -j ACCEPT


# allow all stated inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# allow ssh connection only to this specific port number
# that you configured at sshd_configure
-A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT

# and drop all inbout except allowed one above here
-A INPUT -j DROP
-A FORWARD -j DROP

COMMIT

Then load it and see if they are set.

1
2
$ sudo iptables-restore < /etc/iptable.server.rules
$ iptables -L

Lets make this reuseable since this would be gone after the system reboot.

Create a init file under netwark with the following content. Simply open the file with the command and paste the content under it.

1
2
3
4
$ vi /etc/network/if-pre-up.d/firewall
>>
#!/bin/sh
/sbin/iptables-restore < /etc/iptables.server.rules

And make it executable.

1
$ sudo chmod +x /etc/network/if-pre-up.d/firewall

If you don’t believe what is happening [ not recommended ].

1
$ shutdown -r now

Have fun

Copyright © 2016 - Tin Aung Linn. Powered by Octopress