#!/bin/bash # Copyright (C) 2016 Ian Kelling # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -eE -o pipefail trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR [[ $EUID == 0 ]] || exec sudo -E "$BASH_SOURCE" "$@" case $1 in -h|--help|*) cat <<'EOF' usage: ${0##*/} Sets up a vpn server which pushes gateway route and dns server so all traffic goes through the vpn. requires systemd, and might have some debian specific paths. EOF ;; esac apt-get update # suggests get's us openssl & easy rsa apt-get install --install-suggests -y openvpn apt-get install -y uuid-runtime mkdir -p /etc/openvpn/easy-rsa/keys cd /etc/openvpn/easy-rsa cp -r /usr/share/easy-rsa/* . source vars # dun care about setting cert cn etc from the non-example values ./clean-all # accept default prompts echo -e '\n\n\n\n\n\n\n\n' | ./build-ca # This builds the server's key/cert. argument is the name of the file, # but it also is the default common name of the cert. # 'server' is the default name in our conf file for the name of the file # and I've seen no reason to change it. # Note, this is not idempotent. { echo -e '\n\n\n\n\n\n\n\n\n\n'; sleep 1; echo -e 'y\ny\n'; } | ./build-key-server server ./build-dh cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/ cp /etc/openvpn/easy-rsa/keys/{ca.crt,server.{crt,key},dh2048.pem} /etc/openvpn gzip -df /etc/openvpn/server.conf.gz sed -i --follow-symlinks 's/^dh dh1024.pem/dh dh2048.pem/' /etc/openvpn/server.conf teeu() { while read -r line; do grep -xFq "$line" "$1" || echo "$line" | tee -a "$1" done } # Be the default gateway for clients. teeu /etc/openvpn/server.conf <<'EOF' push "redirect-gateway def1" EOF # Be the dns server for clients teeu /etc/openvpn/server.conf <<'EOF' push "dhcp-option DNS 10.8.0.1" EOF echo "1" > /proc/sys/net/ipv4/ip_forward sed -i --follow-symlinks '/^ *net\.ipv4\.ip_forward=.*/d' /etc/sysctl.conf teeu /etc/sysctl.conf <<'EOF' net.ipv4.ip_forward=1 EOF gw=$(ip route | sed -rn 's/^default via .* dev (\S+).*/\1/p') sudo dd of=/etc/systemd/system/mynat.service <