Skip to content

Instantly share code, notes, and snippets.

@faizal2007
Created April 27, 2021 01:21
Show Gist options
  • Save faizal2007/4775fed469f87346649c7b05771c2ed5 to your computer and use it in GitHub Desktop.
Save faizal2007/4775fed469f87346649c7b05771c2ed5 to your computer and use it in GitHub Desktop.
Basic firewall only block incoming access
#!/bin/bash
# My system IP/set ip address of server
PUBLIC_PORT=(22 80)
# comment this to disable
ENABLE_PRIVATE=1
##
# $PRIVATE_PORT must have the same array lenght
# with PRIVATE_IP
##
PRIVATE_PORT=( \
8080 \
9100 \
9113 \
)
PRIVATE_IP=( \
"192.168.1.24" \
"192.168.1.24" \
"192.168.1.24" \
)
flush_firewall() {
sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables -t nat -F
sudo iptables -t mangle -F
sudo iptables -F
sudo iptables -X
}
# Setting default filter policy
drop_firewall() {
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
}
# Allow unlimited traffic on loopback
allow_loopback() {
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT
}
# Allow port for all
allow_public() {
for PORT in ${PUBLIC_PORT[@]}; do
sudo iptables -A INPUT -p tcp --dport $PORT -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
echo "Port ${PORT} Opened."
done
}
# Allow port base on source ip
allow_private() {
for i in ${!PRIVATE_PORT[@]}; do
sudo iptables -A INPUT -s ${PRIVATE_IP[$i]} -p tcp --dport ${PRIVATE_PORT[$i]} -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
echo "${PRIVATE_IP[$i]} ${PRIVATE_PORT[$i]} Opened."
done
}
flush_firewall
allow_loopback
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
allow_public
[ $ENABLE_PRIVATE ] && allow_private
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment