Blob


1 #!/bin/sh
2 #
3 # NAME
4 # gencert - generate certificates
5 #
6 # SYNOPSIS
7 # ./gencert [-fh] [-D days] [-d destdir] hostname
8 #
9 # DESCRIPTION
10 # A simple script to generate self-signed X.509 certificates for
11 # gmid.
12 #
13 # The option are as follows:
14 # -D Specify the number of days the certificate
15 # will be valid for. Use 365 (a year) by default.
16 # -d Save the certificates to the given directory.
17 # By default the current directory is used.
18 # -f Forcefully overwrite existing certificates
19 # without prompting.
20 # -h Display usage and exit.
21 #
22 # SEE ALSO
23 # openssl(1)
24 #
26 progname="$(basename -- "$0")"
28 usage() {
29 echo "usage: $progname [-fh] [-d destdir] [-D days] hostname" >&2
30 echo "Please read the comment at the top of $0 for the usage." >&2
31 exit $1
32 }
34 force=no
35 destdir=.
36 days=365
38 while getopts "D:d:fh" flag; do
39 case $flag in
40 D) days="$OPTARG" ;;
41 d) destdir="${OPTARG%/}" ;;
42 f) force=yes ;;
43 h) usage 0 ;;
44 ?) usage 1 ;;
45 esac
46 done
48 shift $(($OPTIND - 1))
50 if [ $# -ne 1 ]; then
51 usage 1
52 fi
54 if [ ! -d "${destdir}" ]; then
55 echo "${progname}: ${destdir} is not a directory." >&2
56 usage 1
57 fi
59 hostname="${1}"
60 pem="${destdir}/${hostname}.pem"
61 key="${destdir}/${hostname}.key"
63 if [ -f "$pem" -o -f "$key" ]; then
64 if [ $force = no ]; then
65 while :; do
66 printf "Overwrite existing certificate $pem? [y/n] "
67 if ! read -r reply; then
68 echo
69 exit 1
70 fi
71 case "$reply" in
72 [yY]) echo "overwriting"; break ;;
73 [nN]) echo "quitting"; exit 0 ;;
74 esac
75 done
76 fi
77 fi
79 openssl req -x509 \
80 -newkey rsa:4096 \
81 -out "${pem}" \
82 -keyout "${key}" \
83 -days "${days}" \
84 -nodes \
85 -subj "/CN=$hostname"
87 e=$?
88 if [ $e -ne 0 ]; then
89 exit $e
90 fi
92 echo
93 echo "Generated files:"
94 echo " $pem : certificate"
95 echo " $key : private key"