Skip to content

Instantly share code, notes, and snippets.

@jfstenuit
Last active June 23, 2021 14:44
Show Gist options
  • Save jfstenuit/bda12966aaf175c4a82a1f176a8ca70e to your computer and use it in GitHub Desktop.
Save jfstenuit/bda12966aaf175c4a82a1f176a8ca70e to your computer and use it in GitHub Desktop.
OpenVPN server on a machine with a dynamic IP

The need

You want to run an OpenVPN server on a debian-like system with a dynamic IP address (f.i. behind a consumer cable modem access)

The problem

You need to provide a fixed IP address in the openvpn configuration

The solution

Ensure the OpenVPN configuration is updated with each IP address change and reload the server

In order to run an application upon IP address change, you need to create a hook inside /etc/dhcp/dhclient-exit-hooks.d .

Create a file called /etc/dhcp/dhclient-exit-hooks.d/openvpn with this content :

#!/bin/sh

RUN="yes"

LOGFILE=/var/log/dynopenvpn.log
OVPNCFG=/etc/openvpn/server.conf

export LC_ALL=C

if [ "$RUN" = "yes" ]; then
        echo "$(date '+%Y-%m-%d %H:%M:%S :') DynOpenVPN called" >>$LOGFILE

        if [ "x$reason" = "x" ]; then
                echo "$(date '+%Y-%m-%d %H:%M:%S :') Not called by dhclient" >>$LOGFILE
                new_ip_address=`ip -4 -o addr | grep eth0 |awk '{print $4}' | sed 's@/.*@@'`
        else
                echo "$(date '+%Y-%m-%d %H:%M:%S :') dhclient $reason" >>$LOGFILE
        fi

        if [ "x$new_ip_address" != "x" ]; then
                echo -n "$(date '+%Y-%m-%d %H:%M:%S : ')" >>$LOGFILE
                current_ip=`awk '$1=="local" {print $2}' <$OVPNCFG`
                if [ "$current_ip" != "$new_ip_address" ]; then
                        sed -i -e "s/local .*/local $new_ip_address/" $OVPNCFG
                        echo -n "New config file : " >>$LOGFILE
                        head -1 $OVPNCFG >>$LOGFILE
                        systemctl restart [email protected]
                else
                        echo "Not updating server.conf as $new_ip_address is already registered" >>$LOGFILE
                fi
        fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment