Blob


1 #!/bin/sh
2 #
3 # NAME
4 # gencert - generate certificates
5 #
6 # SYNOPSIS
7 # ./gencert [-efh] [-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 # -e Use an EC key instead of RSA.
19 # -f Forcefully overwrite existing certificates
20 # without prompting.
21 # -h Display usage and exit.
22 #
23 # SEE ALSO
24 # openssl(1)
25 #
27 progname="$(basename -- "$0")"
29 usage() {
30 echo "usage: $progname [-fhe] [-d destdir] [-D days] hostname" >&2
31 echo "Please read the comment at the top of $0 for the usage." >&2
32 exit $1
33 }
35 ec=no
36 force=no
37 destdir=.
38 days=365
40 while getopts "D:d:efh" flag; do
41 case $flag in
42 D) days="$OPTARG" ;;
43 d) destdir="${OPTARG%/}" ;;
44 e) ec=yes ;;
45 f) force=yes ;;
46 h) usage 0 ;;
47 ?) usage 1 ;;
48 esac
49 done
51 shift $(($OPTIND - 1))
53 if [ $# -ne 1 ]; then
54 usage 1
55 fi
57 if [ ! -d "${destdir}" ]; then
58 echo "${progname}: ${destdir} is not a directory." >&2
59 usage 1
60 fi
62 hostname="${1}"
63 pem="${destdir}/${hostname}.pem"
64 key="${destdir}/${hostname}.key"
66 if [ -f "$pem" -o -f "$key" ]; then
67 if [ $force = no ]; then
68 while :; do
69 printf "Overwrite existing certificate $pem? [y/n] "
70 if ! read -r reply; then
71 echo
72 exit 1
73 fi
74 case "$reply" in
75 [yY]) echo "overwriting"; break ;;
76 [nN]) echo "quitting"; exit 0 ;;
77 esac
78 done
79 fi
80 fi
82 if [ $ec = yes ]; then
83 openssl ecparam -name secp384r1 -genkey -noout -out "${key}" && \
84 openssl req -new -x509 -key "${key}" -out "${pem}" -days "${days}" \
85 -nodes -subj "/CN=$hostname"
86 else
87 openssl req -x509 \
88 -newkey rsa:4096 \
89 -out "${pem}" \
90 -keyout "${key}" \
91 -days "${days}" \
92 -nodes \
93 -subj "/CN=$hostname"
94 fi
96 e=$?
97 if [ $e -ne 0 ]; then
98 exit $e
99 fi
101 echo
102 echo "Generated files:"
103 echo " $pem : certificate"
104 echo " $key : private key"