improve license notices
[vpn-setup] / client-cert-helper
1 #!/bin/bash
2 # I, Ian Kelling, follow the GNU license recommendations at
3 # https://www.gnu.org/licenses/license-recommendations.en.html. They
4 # recommend that small programs, < 300 lines, be licensed under the
5 # Apache License 2.0. This file contains or is part of one or more small
6 # programs. If a small program grows beyond 300 lines, I plan to switch
7 # its license to GPL.
8
9 # Copyright 2024 Ian Kelling
10
11 # Licensed under the Apache License, Version 2.0 (the "License");
12 # you may not use this file except in compliance with the License.
13 # You may obtain a copy of the License at
14
15 # http://www.apache.org/licenses/LICENSE-2.0
16
17 # Unless required by applicable law or agreed to in writing, software
18 # distributed under the License is distributed on an "AS IS" BASIS,
19 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 # See the License for the specific language governing permissions and
21 # limitations under the License.
22
23 set -eE -o pipefail
24
25 # Outputs the keyfiles to stdout as tar.gz
26
27 rm -f /tmp/vpn-mk-client-cert.log
28 exec 2>/tmp/vpn-mk-client-cert.log
29
30
31 if ! test "$BASH_VERSION"; then echo "error: shell is not bash" >&2; exit 1; fi
32 shopt -s inherit_errexit 2>/dev/null ||: # ignore fail in bash < 4.4
33 set -eE -o pipefail
34 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?. PIPESTATUS: ${PIPESTATUS[*]}" >&2' ERR
35
36 date >&2
37 set -x
38
39 name=$1
40 common_name=$2
41
42 server_dir=/etc/openvpn
43 if [[ -e /etc/openvpn/server ]]; then
44 server_dir=/etc/openvpn/server
45 fi
46
47 cafile=$server_dir/ca-$name.crt
48
49 ### begin section roughly copied from vpn-server-setup
50 rsadir=/etc/openvpn/easy-rsa-$name
51 new=true # newer easy-rsa version
52 keyfiles=(
53 $rsadir/pki/private/$common_name.key
54 $rsadir/pki/issued/$common_name.crt
55 )
56 if [[ -e /etc/openvpn/easy-rsa-$name/build-ca ]]; then
57 new=false
58 keyfiles=(
59 $rsadir/keys/$common_name.key
60 $rsadir/keys/$common_name.crt
61 )
62 fi
63 ### end section roughly copied from vpn-server-setup
64
65 if [[ ! -e $cafile ]]; then
66 echo error: no cafile found at $cafile >&2
67 exit 1
68 fi
69
70 exists=true
71 for x in ${keyfiles[@]}; do
72 if [[ ! -e $x ]]; then
73 exists=false
74 break
75 fi
76 done
77
78
79 if ! $exists; then
80 cd /etc/openvpn/easy-rsa-$name
81 if $new; then
82 ./easyrsa build-client-full $common_name nopass >/dev/null
83 else
84 source vars >/dev/null
85
86 { 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
87 fi
88 fi
89
90 d=$(mktemp -d)
91 cp $server_dir/ta-$name.key $cafile $d
92 for f in ${keyfiles[@]}; do
93 cp $f $d/$name.${f##*.}
94 done
95
96 tar cz -C $d .
97 rm -rf $d