Write a set of firewall rules for a server running an OpenVPN client that work as a killswitch i.e. allow Internet access only via VPN IP. Note that connecting to a VPN on the server will make it unresponsive to SSH connections, so include in the firewall rules an exception for SSH so that SSH connection to the server is still possible while the server is connected to the VPN.
Long description (and my attempts)
I have a server on which I'm trying to set up an OpenVPN client. This is alone isn't a difficult task - the command to connect is simply
sudo openvpn configuration_file.ovpn.
What was more difficult was making a killswitch i.e. a program that prevents connection made via non-VPN IP address in case the VPN tunnels disconnects for some reason. I found this script on desktop and tested it on desktop:
sudo ufw default deny outgoing sudo ufw default deny incoming sudo ufw allow out on tun0 from any to any sudo ufw allow in on tun0 from any to any sudo ufw allow out from any to VPN.SERVER.IP.ADDRESS sudo ufw enable
However, on server there is another problem - if the server connects to a VPN, it stops responding to SSH. I found this script, tested it on server and it worked - it kept the server responsive via SSH while it was connected to the VPN:
echo "201 novpn" >> /etc/iproute2/rt_tables ip rule show | grep fwmark ip rule add fwmark 65 table novpn ip route add default via GATEWAY.IP.ADDRESS dev eth0 table novpn ip route flush cache iptables -t mangle -A OUTPUT -p tcp --sport 22 -j MARK --set-mark 65
Now I need to combine those two scripts (or write a new one from scratch) i.e. have a set of firewall rules that implement a killswitch for OpenVPN client running on a server and also allow SSH connections to/from server. How would such script look like?