Simple Bash Iptables Firewall Script

Posted on May 17, 2017 at 9:31 pm

Sample firewall script with iptables to allow only trusted traffic:

#!/bin/bash
 
# Simple firewall script to allow only trusted inbound connections
# Useful for load balanced servers to allow only inbound traffic on port 80 from the load balancer
# Using /etc/crontab you can run the firewall script at every reboot:
# @reboot root /path/to/firewall.sh
# Proudly created by http://www.queryadmin.com/
 
IPTABLES="$(which iptables)"
 
# Accept all ICMP inbound traffic
$IPTABLES -A INPUT -p icmp -j ACCEPT
# Allow only the load balancer IP on port 80 HTTP
$IPTABLES -A INPUT -p tcp -m tcp --dport 80 -s LOAD_BALANCER_IP_HERE -j ACCEPT
# Allow only the load balancer IP on port 443 HTTPS
$IPTABLES -A INPUT -p tcp -m tcp --dport 443 -s LOAD_BALANCER_IP_HERE -j ACCEPT
# Allow only your static IP address on port 22 SSH
$IPTABLES -A INPUT -p tcp -m tcp --dport 22 -s YOUR_STATIC_IP_HERE -j ACCEPT
# Accept related and already established connections
$IPTABLES -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# Accept local connections
$IPTABLES -A INPUT -i lo -j ACCEPT
# Drop all other inbound connections
$IPTABLES -P INPUT DROP

To run the firewall at every reboot add this line to /etc/crontab:

@reboot root /path/to/firewall.sh

To reset (flush) iptables rules use this script:
Reset (flush) Iptables rules Linux

Updated on November 11, 2017 at 11:21 pm

Other Posts

Updated Posts