1#!/bin/sh 2 3# Copyright (c) 2005-2010 OpenVPN Technologies, Inc. 4# Licensed under the GPL version 2 5 6# First version by Jesse Adelman 7# someone at boldandbusted dink com 8# http://www.boldandbusted.com/ 9 10# PURPOSE: This script automatically sets the proper /etc/resolv.conf entries 11# as pulled down from an OpenVPN server. 12 13# INSTALL NOTES: 14# Place this in /etc/openvpn/client.up 15# Then, add the following to your /etc/openvpn/<clientconfig>.conf: 16# client 17# up /etc/openvpn/client.up 18# Next, "chmod a+x /etc/openvpn/client.up" 19 20# USAGE NOTES: 21# Note that this script is best served with the companion "client.down" 22# script. 23 24# Tested under Debian lenny with OpenVPN 2.1_rc11 25# It should work with any UNIX with a POSIX sh, /etc/resolv.conf or resolvconf 26 27# This runs with the context of the OpenVPN UID/GID 28# at the time of execution. This generally means that 29# the client "up" script will run fine, but the "down" script 30# will require the use of the OpenVPN "down-root" plugin 31# which is in the plugins/ directory of the OpenVPN source tree 32 33# A horrid work around, from a security perspective, 34# is to run OpenVPN as root. THIS IS NOT RECOMMENDED. You have 35# been WARNED. 36PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin 37 38# init variables 39 40i=1 41domains= 42fopt= 43ndoms=0 44nns=0 45nl=' 46' 47 48# $foreign_option_<n> is something like 49# "dhcp-option DOMAIN example.com" (multiple allowed) 50# or 51# "dhcp-option DNS 10.10.10.10" (multiple allowed) 52 53# each DNS option becomes a "nameserver" option in resolv.con 54# if we get one DOMAIN, that becomes "domain" in resolv.conf 55# if we get multiple DOMAINS, those become "search" lines in resolv.conf 56 57while true; do 58 eval fopt=\$foreign_option_${i} 59 [ -z "${fopt}" ] && break 60 61 case ${fopt} in 62 dhcp-option\ DOMAIN\ *) 63 ndoms=$((ndoms + 1)) 64 domains="${domains} ${fopt#dhcp-option DOMAIN }" 65 ;; 66 dhcp-option\ DNS\ *) 67 nns=$((nns + 1)) 68 if [ $nns -le 3 ]; then 69 dns="${dns}${dns:+$nl}nameserver ${fopt#dhcp-option DNS }" 70 else 71 printf "%s\n" "Too many nameservers - ignoring after third" >&2 72 fi 73 ;; 74 *) 75 printf "%s\n" "Unknown option \"${fopt}\" - ignored" >&2 76 ;; 77 esac 78 i=$((i + 1)) 79done 80 81ds=domain 82if [ $ndoms -gt 1 ]; then 83 ds=search 84fi 85 86# This is the complete file - "$domains" has a leading space already 87out="# resolv.conf autogenerated by ${0} (${1})${nl}${dns}${nl}${ds}${domains}" 88 89# use resolvconf if it's available 90if type resolvconf >/dev/null 2>&1; then 91 printf "%s\n" "${out}" | resolvconf -p -a "${1}" 92else 93 # Preserve the existing resolv.conf 94 if [ -e /etc/resolv.conf ] ; then 95 cp /etc/resolv.conf /etc/resolv.conf.ovpnsave 96 fi 97 printf "%s\n" "${out}" > /etc/resolv.conf 98 chmod 644 /etc/resolv.conf 99fi 100 101exit 0 102