Skip to content

Instantly share code, notes, and snippets.

@carlbennett
Last active May 27, 2020 03:05
Show Gist options
  • Save carlbennett/9c965d6d0b583d18c0df7d7c6e299bfe to your computer and use it in GitHub Desktop.
Save carlbennett/9c965d6d0b583d18c0df7d7c6e299bfe to your computer and use it in GitHub Desktop.
Place this file in its own directory and run it. It generates the certificate files in its current directory.
#!/usr/bin/env bash
# vim: set colorcolumn=:
set -e -o pipefail
[ -z "${TERM}" ] && echo 'Error: TERM not set, this script is exclusively interactive!' 1>&2 && exit 1
echo -e '\e[1;32mCertificate Generator\e[0m'
HOSTNAMES=()
while true; do
echo -en '\e[1;33mEnter hostname\e[0m \e[1;30m[leave blank to finish]:\e[0m '
read -r prompt
[ -z "$prompt" ] && break
HOSTNAMES+=("$prompt")
done
if [ "${#HOSTNAMES[@]}" -eq 0 ]; then
echo -e '\e[1;31mError:\e[0;31m A hostname must be specified to use this script.\e[0m' 1>&2
exit 1
fi
echo -en '\e[1;33mEnter fqdn\e[0m \e[1;30m[leave blank to use first entry]:\e[0m '
read -r prompt
[ -n "$prompt" ] && FQDN="${prompt}" || FQDN="${HOSTNAMES}"
echo "FQDN: ${FQDN}"
ALTNAMES=''
for host in "${HOSTNAMES[@]}"; do
ipcalc -cs "${host}" && identifier='IP' || identifier='DNS'
echo "Alt Name: ${identifier}:${host}"
ALTNAMES="${ALTNAMES},${identifier}:${host}"
done
ALTNAMES="${ALTNAMES:1}" # remove first comma
cat > certgen.config.csr <<EOF
[ req ]
default_bits = 4096
default_keyfile = privkey.pem
default_md = sha256
distinguished_name = dn
encrypt_key = no
prompt = no
req_extensions = v3_req
x509_extensions = v3_x509
[ dn ]
C = US
CN = ${FQDN}
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment
subjectAltName = ${ALTNAMES}
[ v3_x509 ]
extendedKeyUsage = serverAuth,clientAuth
subjectKeyIdentifier = hash
subjectAltName = ${ALTNAMES}
issuerAltName = issuer:copy
EOF
openssl req -config certgen.config.csr -new -x509 -days 3650 -out cert.pem
echo -e '\e[32mComplete\e[0m'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment