Firewalls are a critical component of keeping your machine safe on the Internet.
This tutorial will show you how to create firewall rules from the command line.
Details of the script actions are commented in the script.
Please copy this script below and save it as firewall.
To run this script, please do the following:
chmod 700 firewall && chmod +X firewall
./firewall
———————————————-
#!/bin/bash
#Clear the screen
clear
#
#Start the iptables daemon.
service iptables start
#
#INPUT SECTION
iptables -N interfaces
#DROP ALL INCOMING CONNECTIONS
iptables -P INPUT DROP
#ALLOW PORTS FOR LOCALHOST
iptables -A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -s 127.0.0.1 -j ACCEPT
iptables -A INPUT -s 127.0.0.1 -p udp -j ACCEPT
iptables -A INPUT -s 127.0.0.1 -p tcp -j ACCEPT
#
#CONFIGURE INCOMING CONNECTIONS FROM THE OUTSIDE
iptables -A INPUT -p udp -j ACCEPT
#
#ALLOW IMAP CONNECTIONS
iptables -A INPUT -p tcp –dport 143 -j ACCEPT
#
#ALLOW SMTP CONNECTIONS
iptables -A INPUT -p tcp –dport 25 -j ACCEPT
#
#ALLOW HTTP CONNECTIONS
iptables -A INPUT -p tcp –dport 80 -j ACCEPT
#
#ALLOW SSH CONNECTIONS
iptables -A INPUT -p tcp –dport 22 -j ACCEPT
#
#ALLOW ALL OUTBOUND ACCESS
iptables -P OUTPUT ACCEPT
#
#SAVE THE CONFIGURATION SO THAT THE CHANGES TAKE EFFECT NOW.
sleep 1
iptables-save
———————————————-
How do I see all of my current rules?
Simply run the following command:
iptables -L
How do I make sure my script is working?
Easy! Simply install nmap and do the following:
nmap localhost (tests localhost connectivity)
nmap your-ip-address (tests remote connectivity)
What if I only want to allow connections from a single IP address?
All you have to do is add a source IP address to the iptables command.
Example: I only want computer “10.101.1.1” to be able to connect to my web server.
iptables -A INPUT -p tcp -s 10.101.1.1 –dport 80 -j ACCEPT
How do I undo all of my rules?
Run the following command:
iptables -F
Hi there, why not to remove the following statements…
iptables -A INPUT -s 127.0.0.1 -p udp -j ACCEPT
iptables -A INPUT -s 127.0.0.1 -p tcp -j ACCEPT
…when all these packets, regardless of the protocol, have already been accepted by:
iptables -A INPUT -s 127.0.0.1 -j ACCEPT ??
Or, is there some caveat I’m missing?