Usable OpenVPN in CentOS/Fedora/RHEL

Guide for easy use of OpenVPN in RHEL7 family of Linux:

Create a wrapper script vpnstart:

#!/bin/bash
name=$1
if [ -z "$name" ]; then
	echo "Specify a configuration"
	exit 1
fi

# change the terminal title
printf "\\033]0;VPN Session\\007"

cfg=/home/$SUDO_USER/bin/vpnstart.${name}.ovpn

if [ `id -u` != 0 ]; then
    echo "exec: sudo $0 $name"
    sleep 1
    sudo $0 $name
else
    export PATH=/usr/local/sbin:/usr/local/bin:$PATH
    openvpn --config $cfg
fi

I usually put this in /app/local/bin/vpnstart

Next, setup to get DNS working with open vpn declarations. Copy the following into /etc/openvpn/update-resolv-conf:

#!/bin/bash
# 
# Adjusted for CentOS7/RHEL/Fedora
#
# Note: ideally networKManager would handle this via dnsmasq, but it doesn't
# appear to handle this dynamically as of yet.  So we'll just clobber it.
# We run the risk that NeworkManager will replace it later..
#
# Parses DHCP options from openvpn to update resolv.conf
# To use set as 'up' and 'down' script in your openvpn *.conf:
# up /etc/openvpn/update-resolv-conf
# down /etc/openvpn/update-resolv-conf
#
# Used snippets of resolvconf script by Thomas Hood and Chris Hanson.
# Licensed under the GNU GPL.  See /usr/share/common-licenses/GPL. 
# 
# Example envs set from openvpn:
#
#     foreign_option_1='dhcp-option DNS 193.43.27.132'
#     foreign_option_2='dhcp-option DNS 193.43.27.133'
#     foreign_option_3='dhcp-option DOMAIN be.bnc.ch'
#

split_into_parts()
{
    part1="$1"
    part2="$2"
    part3="$3"
}

case "$script_type" in
  up)
    NMSRVRS=""
    SRCHS=""
        for optionvarname in ${!foreign_option_*} ; do
        option="${!optionvarname}"
        echo "Found Option: $option"
        split_into_parts $option
        if [ "$part1" = "dhcp-option" ] ; then
            if [ "$part2" = "DNS" ] ; then
                NMSRVRS="${NMSRVRS:+$NMSRVRS }$part3"
            elif [ "$part2" = "DOMAIN" ] ; then
                SRCHS="${SRCHS:+$SRCHS }$part3"
            fi
        fi
    done
    R=""
    [ "$SRCHS" ] && R="search $SRCHS
"
    for NS in $NMSRVRS ; do
            R="${R}nameserver $NS
"
    done
	cp /etc/resolv.conf "/etc/resolv.conf.pre:$dev"
	cat > /etc/resolv.conf <<END
# generated by /etc/openvpn/update-resolv-conf
$R
END
    ;;
  down)
	mv "/etc/resolv.conf.pre:$dev" /etc/resolv.conf
    ;;
esac

then update your Open VPN configs:

  • first copy your openvpn client configurations to /app/local/conf/vpnstart.{name}.ovpn

  • then chmod 600 the file

  • then add to the end of each named configuration

    cat >> vpnstart.{name}.ovpn <<END

    up /etc/openvpn/update-resolv-conf

    down /etc/openvpn/update-resolv-conf

    script-security 2

    END

Startup OpenVPN with:

vpnstart name