#!/bin/bash # # Run the OpenVPN server normally # if [ "$DEBUG" == "1" ]; then set -x fi set -e cd $OPENVPN # Build runtime arguments array based on environment USER_ARGS=("${@}") ARGS=() IPTABLES="iptables-nft" # Checks if ARGS already contains the given value function hasArg { local element for element in "${@:2}"; do [ "${element}" == "${1}" ] && return 0 done return 1 } # Adds the given argument if it's not already specified. function addArg { local arg="${1}" [ $# -ge 1 ] && local val="${2}" if ! hasArg "${arg}" "${USER_ARGS[@]}"; then ARGS+=("${arg}") [ $# -ge 1 ] && ARGS+=("${val}") fi } # set up iptables rules and routing # this allows rules/routing to be altered by supplying this function function setupIptablesAndRouting { $IPTABLES -t nat -C POSTROUTING -s $VPN_CIDR_RANGE -o $OVPN_NATDEVICE -j MASQUERADE 2>/dev/null || { $IPTABLES -t nat -A POSTROUTING -s $VPN_CIDR_RANGE -o $OVPN_NATDEVICE -j MASQUERADE } for i in "${OVPN_ROUTES[@]}"; do $IPTABLES -t nat -C POSTROUTING -s "$i" -o $OVPN_NATDEVICE -j MASQUERADE 2>/dev/null || { $IPTABLES -t nat -A POSTROUTING -s "$i" -o $OVPN_NATDEVICE -j MASQUERADE } done } addArg "--config" "$OPENVPN/openvpn.conf" VPN_CIDR_RANGE="172.16.10.0/24" # When using --net=host, use this to specify nat device. OVPN_NATDEVICE=eth0 mkdir -p /dev/net if [ ! -c /dev/net/tun ]; then mknod /dev/net/tun c 10 200 fi if [ -d "$OPENVPN/ccd" ]; then addArg "--client-config-dir" "$OPENVPN/ccd" fi # Setup NAT forwarding if requested setupIptablesAndRouting echo "Running 'openvpn ${ARGS[@]} ${USER_ARGS[@]}'" exec openvpn ${ARGS[@]} ${USER_ARGS[@]}