9961fc64be0ecf6b487e9c86b3c60c68d1d8e6f0
[vpn-setup] / client-cert-helper
1 #!/bin/bash
2 set -eE -o pipefail
3
4 # Outputs the keyfiles to stdout as tar.gz
5
6 rm -f /tmp/vpn-mk-client-cert.log
7 exec 2>/tmp/vpn-mk-client-cert.log
8
9
10 if ! test "$BASH_VERSION"; then echo "error: shell is not bash" >&2; exit 1; fi
11 shopt -s inherit_errexit 2>/dev/null ||: # ignore fail in bash < 4.4
12 set -eE -o pipefail
13 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?. PIPESTATUS: ${PIPESTATUS[*]}" >&2' ERR
14
15 date >&2
16 set -x
17
18 name=$1
19 common_name=$2
20
21 server_dir=/etc/openvpn
22 if [[ -e /etc/openvpn/server ]]; then
23 server_dir=/etc/openvpn/server
24 fi
25
26 cafile=$server_dir/ca-$name.crt
27
28 ### begin section roughly copied from vpn-server-setup
29 rsadir=/etc/openvpn/easy-rsa-$name
30 new=true # newer easy-rsa version
31 keyfiles=(
32 $rsadir/pki/private/$common_name.key
33 $rsadir/pki/issued/$common_name.crt
34 )
35 if [[ -e /etc/openvpn/easy-rsa-$name/build-ca ]]; then
36 new=false
37 keyfiles=(
38 $rsadir/keys/$common_name.key
39 $rsadir/keys/$common_name.crt
40 )
41 fi
42 ### end section roughly copied from vpn-server-setup
43
44 if [[ ! -e $cafile ]]; then
45 echo error: no cafile found at $cafile >&2
46 exit 1
47 fi
48
49 exists=true
50 for x in ${keyfiles[@]}; do
51 if [[ ! -e $x ]]; then
52 exists=false
53 break
54 fi
55 done
56
57
58 if ! $exists; then
59 cd /etc/openvpn/easy-rsa-$name
60 if $new; then
61 ./easyrsa build-client-full $common_name nopass >/dev/null
62 else
63 source vars >/dev/null
64
65 { echo -e '\n\n\n\n\n'$common_name'\n\n\n\n\n'; sleep 2; echo -e 'y\ny\n'; } | ./build-key $name >/dev/null
66 fi
67 fi
68
69 d=$(mktemp -d)
70 cp $server_dir/ta-$name.key $cafile $d
71 for f in ${keyfiles[@]}; do
72 cp $f $d/$name.${f##*.}
73 done
74
75 tar cz -C $d .
76 rm -rf $d