working, tested version
[vpn-setup] / vpn-mk-client-cert
1 #!/bin/bash
2 # Copyright (C) 2016 Ian Kelling
3
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 # usage: $0 SERVER_HOST [DEST_HOST]
17 # ssh to SERVER_HOST, create a cert & client config, put it on
18 # DEST_HOST, or localhost by default. Assumes server was setup
19 # by the other script in this dir.
20
21 set -eE -o pipefail
22 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
23
24 [[ $EUID == 0 ]] || exec sudo -E "$BASH_SOURCE" "$@"
25
26 usage() {
27 cat <<'EOF'
28 usage: ${0##*/} VPN_SERVER_HOST [CLIENT_HOST]
29
30 Generate a client cert and config and install it on locally or on
31 CLIENT_HOST if given. Uses default config options, and expects be able
32 to ssh to VPN_SERVER_HOST and CLIENT_HOST.
33 EOF
34 exit ${1:-0}
35 }
36
37 case $1 in
38 -h|--help|*) usage 0 ;;
39 esac
40
41 (($# <= 2)) || usage 1
42
43 host=$1
44 shell="bash -c"
45 if [[ $2 ]]; then
46 shell="ssh $2"
47 fi
48
49 # bash or else we get motd spam. note sleep 2, sleep 1 failed.
50 ssh $host bash <<EOF | $shell 'id -u | grep -xF 0 || s=sudo; $s tar xzv -C /etc/openvpn'
51 set -eE -o pipefail
52 cd /etc/openvpn/easy-rsa
53 source vars >/dev/null
54
55 # uuidgen because common name must be unique
56 { echo -e '\n\n\n\n\n'\$(uuidgen)'\n\n\n\n\n'; sleep 2; echo -e 'y\ny\n'; } | ./build-key client &>/dev/null
57
58 d=\$(mktemp -d)
59 cp /etc/openvpn/easy-rsa/keys/ca.crt \
60 /etc/openvpn/update-resolv-conf \
61 /usr/share/doc/openvpn/examples/sample-config-files/client.conf \$d
62 mv /etc/openvpn/easy-rsa/keys/client.{crt,key} \$d
63
64 sed -i --follow-symlinks "s/^remote .*/remote $host 1194/" \$d/client.conf
65
66 tar cz -C \$d .
67 rm -rf \$d
68 EOF