Today I am going to show you how I secure my OpenVZ guest container which is running Ubuntu 12.04 LTS. When using OpenVZ I use iptables directly as applications such as UFW won't work for various reasons (but I'm sure someone will have a hack for it). Knowing how to use iptables is always good as it is quite powerful. Also, using UFW for managing your firewall is like using Phpmyadmin to administer your database instead of using the MySQL command line tool.
Steps
Write the following lines to a file and execute it with bash
#!/bin/bash
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# Allow our trusted IPs
iptables -A INPUT -s [MY STATIC IP HERE]/30 -p tcp -j ACCEPT
#iptables -A OUTPUT -d [MY STATIC IP HERE]/30 -p tcp -j ACCEPT
# Allow web traffic to the public
iptables -A INPUT -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
#iptables -A OUTPUT -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
# Allow secure web traffic to the public
iptables -A INPUT -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
#iptables -A OUTPUT -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP
Don't forget to replace the [MY STATIC IP HERE] placeholders with an IP you are going to connect with SSH from, and not the IP of the server you are configuring.
It is probably a good idea if you add multiple trusted IPs to the Allow our trusted IPs section.
The OUTPUT statements are commented out in case you want to switch to enabling them and changing the OUTPUT policy to DROP
Make sure those rules are viewable if you run iptables -L
Now we need to set up a location to store our iptables rules. Personally, I create a folder in root for everything to do with iptables but you can just save to a file anywhere as long as you adjust the path in the next step.
sudo mkdir /root/iptables
sudo iptables-save > /root/iptables/rules.txt
sudo iptables-save > /root/iptables/rules.txt
Now add the following line to /etc/rc.local
/sbin/iptables-restore < /root/iptables/rules.txt
That's it! However, if you ever need a "reset" script, then you may want to add the following lines to reset.sh in the iptables folder we made.
#!/bin/bash
sudo iptables -X
sudo iptables -t nat -F
sudo iptables -t nat -X
sudo iptables -t mangle -F
sudo iptables -t mangle -X
sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables --flush
No comments:
Post a Comment