Route OpenVPN Connections Through Floating IP

Posted on November 4, 2020 at 11:14 am

Assuming you have a Hetzner VPS with a floating IP address:

How to Configure a Floating IP in a VPS (Hetzner)

Let’s say the floating IP address is 44.44.44.44 as example.

And that you have installed OpenVPN via this guide:

How to Install OpenVPN in Debian 10 Buster

1) Edit /etc/openvpn/server.conf and add:

local 44.44.44.44

This way we bind OpenVPN server to the floating IP.

2) Restart OpenVPN service:

/etc/init.d/openvpn restart

And check that the floating IP is listening on OpenVPN port:

netstat -ltnup | grep 1194

This is the example output you should get:

udp        0      0 44.44.44.44:1194     0.0.0.0:*                           669/openvpn

3) Flush any NAT iptables rule (very important):

iptables -t nat -F

4) Add this new NAT iptables rule:

iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 44.44.44.44

4) Edit /etc/iptables/add-openvpn-rules.sh

#!/bin/sh
#iptables -t nat -I POSTROUTING 1 -s 10.8.0.0/24 -o eth0 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 44.44.44.44
iptables -I INPUT 1 -i tun0 -j ACCEPT
iptables -I FORWARD 1 -i eth0 -o tun0 -j ACCEPT
iptables -I FORWARD 1 -i tun0 -o eth0 -j ACCEPT
iptables -I INPUT 1 -i eth0 -p udp --dport 1194 -j ACCEPT

In short, we comment the default NAT rule:

#iptables -t nat -I POSTROUTING 1 -s 10.8.0.0/24 -o eth0 -j MASQUERADE

And we add this new NAT rule:

iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 44.44.44.44

5) Do same for /etc/iptables/rm-openvpn-rules.sh

#!/bin/sh
#iptables -t nat -D POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
iptables -t nat -D POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 44.44.44.44
iptables -D INPUT -i tun0 -j ACCEPT
iptables -D FORWARD -i eth0 -o tun0 -j ACCEPT
iptables -D FORWARD -i tun0 -o eth0 -j ACCEPT
iptables -D INPUT -i eth0 -p udp --dport 1194 -j ACCEPT

5) Make sure “iptables -S” outputs something like this:

-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i tun0 -j ACCEPT
-A INPUT -i eth0 -p udp -m udp --dport 1194 -j ACCEPT
-A FORWARD -i tun0 -o eth0 -j ACCEPT
-A FORWARD -i eth0 -o tun0 -j ACCEPT

6) Reboot the VPS and all should work fine:

shutdown -r now

7) Now on the client .ovpn file change “remote” as this:

remote 44.44.44.44 1194

Remember, 44.44.44.44 is the floating IP.

Now try to connect to OpenVPN and it should use the floating IP.

Then you may want to check what is your IP address.

Some links you may find useful:

Route all OpenVPN traffic through floating IP (DigitalOcean)
OpenVPN + (DigitalOcean) IP Alias

Receive updates via email

Other Posts

Updated Posts