Skip to content

Instantly share code, notes, and snippets.

@jhazelwo
Last active March 5, 2024 02:52
Show Gist options
  • Save jhazelwo/ce9a9fa9baa331fa455675d7927e939a to your computer and use it in GitHub Desktop.
Save jhazelwo/ce9a9fa9baa331fa455675d7927e939a to your computer and use it in GitHub Desktop.
iptables rules to only allow VPN traffic AND let user SSH to VPN server itself.
#!/bin/sh
# by: "John Hazelwood" <jhazelwo@users.noreply.github.com>
#
# iptables rules to only allow VPN traffic AND let user SSH to VPN server itself.
# Use this on a CentOS/RedHat server you have set up to be a NAT firewall for your network.
# This will force ALL Internet traffic to go over the VPN
# and will BLOCK ALL Internet TRAFFIC if VPN is not running!
#
# use `service iptables save` to save the rules to /etc/sysconfig/iptables
# made
#
VPNServer="172.217.3.256" # Change to ip or host of your VPN server
wan="eth0" # interface connected to the Internet
lan="eth1" # interface to your workstation or router
tun="tun0" # tunnel interface created by VPN client
# Flush rules
/sbin/iptables -F
/sbin/iptables -F -t nat
# Enable NAT
/sbin/iptables -t nat -A POSTROUTING -o $tun -j MASQUERADE
/sbin/iptables -t nat -A POSTROUTING -o $wan -j MASQUERADE # Needed to SSH to VPN server
# Allow SSH to the VPN server itself
/sbin/iptables -A FORWARD -o $wan --destination $VPNServer --protocol tcp --dport 22 -j ACCEPT
/sbin/iptables -A FORWARD -i $wan --source $VPNServer --protocol tcp --sport 22 -j ACCEPT
# Allow VPN traffic
/sbin/iptables -A FORWARD -i $lan --destination $VPNServer --protocol udp --dport 1194 -o $tun -j ACCEPT
/sbin/iptables -A FORWARD -i $tun --source $VPNServer --protocol udp --sport 1194 -o $lan -j ACCEPT
# Block non-VPN traffic across the WAN (Internet) interface (after VPN setup)
/sbin/iptables -A FORWARD -i $wan -j DROP
/sbin/iptables -A FORWARD -o $wan -j DROP
# Allow VPN client to connect to VPN server
/sbin/iptables -A INPUT -i $wan --source $VPNServer --protocol udp --sport 1194 -j ACCEPT
/sbin/iptables -A OUTPUT -o $wan --destination $VPNServer --protocol udp --dport 1194 -j ACCEPT
# Block non-VPN traffic across the WAN (Internet) interface (before VPN setup)
/sbin/iptables -A INPUT -i $wan -j DROP
/sbin/iptables -A OUTPUT -o $wan -j DROP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment