Running OpenVPN on an isolated network namespace

It may be convenient to run select processes over VPN instead of applying the VPN connection system-wide. vpnshift by GitHub user crasm lets you run commands in an isolated network namespace with OpenVPN. Updates were made to crasm’s original repository in this forked version with additional funtionalities and command line options.

Outline

Usage

Download this vpnshift bash script and follow the instructions below:

  1. Apply VPN to a single process(COMMAND).

     sudo bash ./vpnshift -c <OVPN FILE> -i <INTERFACE> -u <USER> [<COMMAND> [<ARG>...]]
    
  2. Establish a VPN network namespace with a dummy ping command.

     sudo bash ./vpnshift -c <OVPN FILE> -i <INTERFACE> -u <USER> ping google.com
    

    ..and attach multiple processes to it.

     sudo ip netns exec <NAMESPACE> sudo -u <USER> [<COMMAND> [<ARG>...]]
    

Example scripts

Bash script to run firefox on an existing network namespace:

firefox_vpnshift.sh

usage="usage: bash firefox_vpnshift.sh -n <netns>"

quick_die() {
	format="$1"; shift
	>&2 printf "${format}\n" "$@"
	exit 1
}

main() {
	while getopts "hn:" opt; do
		case "${opt}" in
			h) quick_die "${usage}" ;;
			n) netns="${OPTARG}" ;;
			*) quick_die "unknown option: %s" "${opt}" ;;
		esac
	done
	shift $(( OPTIND - 1 ))

	if [[ -z "${netns}" ]]; then
		quick_die "network namespace is required"
	fi

	sudo ip netns exec $netns sudo -u $USER firefox
}

main "$@"