Skip to content

Instantly share code, notes, and snippets.

@glens
Created March 17, 2020 04:28
Show Gist options
  • Save glens/ce1ba2a7d70bd027ab20eb9deb4296ac to your computer and use it in GitHub Desktop.
Save glens/ce1ba2a7d70bd027ab20eb9deb4296ac to your computer and use it in GitHub Desktop.
This script will firewall all outbound access to a single IP on TCP/443 & UDP/1194, parsed from a provided .ovpn config file. A rule is added to allow unrestricted access through the VPN connection (via tun0).
#!/bin/bash
if [ -z "$1" ];
then
cat << EOF
VPN iptables Firewall Rules Creator
author: Glen Scott (glen@glenscott.net)
This script will firewall all outbound access to a single IP on TCP/443 & UDP/1194, parsed from a provided .ovpn config file.
A rule is added to allow unrestricted access through the VPN connection (via tun0).
Usage:
Restrict FW:
./vpn_firewall.sh openvpn_config_file.ovpn
Clear all rules and reset to ACCEPT:
./vpn_firewall.sh clear
EOF
exit
fi
if [[ $1 == "clear" ]];
then
echo "Clearing iptables rules and setting to ACCEPT"
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -X
echo
iptables -L -v
exit
else
openvpn_conf=$1
if [[ -f $openvpn_conf ]];
then
echo "$openvpn_conf found."
else
echo "OpenVPN config file not found, exiting."
exit
fi
fi
# get ip from conf file
vpn_server_ip=$(grep remote $openvpn_conf | head -1 | cut -d' ' -f2)
echo "openvpn conf : " $openvpn_conf
echo "server ip : " $vpn_server_ip
echo
# IPTABLES
iptables_cmd="/sbin/iptables"
# flush existing
$iptables_cmd -F
# set default drop
$iptables_cmd -P INPUT DROP
$iptables_cmd -P FORWARD DROP
$iptables_cmd -P OUTPUT DROP
# allow access to VPN server via eth0
$iptables_cmd -A OUTPUT -o eth0 -p tcp -d $vpn_server_ip --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
$iptables_cmd -A OUTPUT -o eth0 -p udp -d $vpn_server_ip --dport 1194 -m state --state NEW,ESTABLISHED -j ACCEPT
#allow outbound on vpn
$iptables_cmd -A OUTPUT -o tun0 -m state --state NEW,ESTABLISHED -j ACCEPT
# allow all related and established
$iptables_cmd -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
$iptables_cmd -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
#allow all local
$iptables_cmd -A INPUT -i lo -j ACCEPT
$iptables_cmd -A OUTPUT -o lo -j ACCEPT
echo "Rules Created:"
iptables -v -L
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment