Startup Firewall Script on Ubuntu

If you want to create a firewall script, or any other script to automatically execute on startup create /etc/init.d/firewall, where “firewall” is the script. Then add your commands:

#!/bin/bash

#delete all rules from all chains
iptables -F
iptables -X

#permit loopback
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

#set DROP policy on INPUT and OUTPUT. 
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -A INPUT -m state --state INVALID -j DROP
iptables -A OUTPUT -m state --state INVALID -j DROP

#permit packets to leave the localhost(if state is NEW,ESTABLISHED or RELATED)
iptables -A OUTPUT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

#permit packets to return to the host(if state is ESTABLISHED or RELATED)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#SSH
iptables -A INPUT -p tcp --dport 2222 -m mac --mac-source 00:0c:29:55:2e:4f -j ACCEPT

#DNS
iptables -A INPUT -s 192.168.2.0/24 -p udp --dport 53 -j ACCEPT

#SMTP
iptables -A INPUT -s 192.168.2.0/24 -p tcp --dport 25 -j ACCEPT

#POP3
iptables -A INPUT -s 192.168.2.0/24 -p tcp --dport 110 -j ACCEPT

#IMAP
iptables -A INPUT -s 192.168.2.0/24 -p tcp --dport 143 -j ACCEPT

#HTTP
iptables -A INPUT -s 192.168.2.0/24 -p tcp --dport 80 -j ACCEPT

#FTP
iptables -A INPUT -s 192.168.2.0/24 -p tcp --dport 21 -j ACCEPT
iptables -A INPUT -s 192.168.2.0/24 -p tcp --dport 20 -j ACCEPT
iptables -A INPUT -s 192.168.2.0/24 -p tcp --dport 64152:64252 -j ACCEPT

Then you need to allow this file to be executed, so:

chmod 755 /etc/init.d/firewall

The following command creates the files that will be executed every time the system boots:

update-rc.d firewall defaults

Now you can reboot the computer and check the configuration with iptables -L -n -v

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s