Skip to content

Instantly share code, notes, and snippets.

@rdev5
Last active April 3, 2018 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdev5/caa8918a876c7658c0aa8760c13d026f to your computer and use it in GitHub Desktop.
Save rdev5/caa8918a876c7658c0aa8760c13d026f to your computer and use it in GitHub Desktop.
#!/bin/bash
# Usage: ./generate-csr.sh ./names.dat "$(cat ./subject.dat)" 4096
#
# Notes:
# - This script prefers AES256 over 3DES for password protecting private keys (https://stackoverflow.com/a/3938726)
# - This script may be used to renew certificates if a copy of the private key is made locally available in the format name_domain_ext.key
FILENAME="$1"
SUBJ="$2"
KEYSIZE="$3"
OPENSSL_CNF=""
if [ -z "$OPENSSL_CNF" ]; then
if [ -f "/etc/pki/tls/openssl.cnf" ]; then
OPENSSL_CNF="/etc/pki/tls/openssl.cnf"
fi
if [ -f "/etc/ssl/openssl.cnf" ]; then
OPENSSL_CNF="/etc/ssl/openssl.cnf"
fi
if [ -z "$OPENSSL_CNF" ]; then
echo "Failed to determine path to openssl.cnf. Please ensure the file exists or set this variable manually (OPENSSL_CNF)."
exit 1
fi
fi
if [ -z "$FILENAME" ] || [ -z "$SUBJ" ]; then
echo "Usage: $0 <filename> <subject> [keysize]"
exit 1
fi
while IFS='' read -r line || [[ -n "$line" ]]; do
[ -z "$line" ] && continue
IFS=':' read -ra line <<< "$line"
CN="${line[0]}"
IFS=',' read -ra names <<< "${line[1]}"
DNS_LIST="DNS:${CN}"
i=2
for name in "${names[@]}"; do
[ "${name}" == "${CN}" ] && continue
DNS_LIST="${DNS_LIST},DNS:${name}"
((i++))
done
ALIAS=$(echo "${CN}" | tr . _)
SUBJECT="${SUBJ}/CN=${CN}"
KEYFILE="${ALIAS}.key"
CSRFILE="${ALIAS}.csr"
if [ ! -f "$KEYFILE" ]; then
if [ -z "$KEYSIZE" ] || [ "$KEYSIZE" -lt 2048 ]; then
echo "[WARN] Weak key size specified (increased to 2048-bit)"
KEYSIZE=2048
fi
openssl genrsa -aes256 -out "$KEYFILE" "$KEYSIZE"
chmod 0400 "$KEYFILE"
fi
echo "Generating CSR: ${CN} ($CSRFILE)"
openssl req -new -key "$KEYFILE" \
-subj "$SUBJECT" \
-reqexts SAN \
-config <(cat "$OPENSSL_CNF" <(printf "\n[SAN]\nsubjectAltName=${DNS_LIST}")) \
-out "$CSRFILE"
done < "$FILENAME"
#!/bin/bash
# TODO: Parameterize
#
# Order:
# 1. The Certificate for your domain
# 2. The intermediates in ascending order to the Root CA
# 3. A Root CA, if any (usually none)
# 4. Private Key
#
# Source: https://www.meshcloud.io/en/2017/04/18/pem-file-layout-for-haproxy/
for CN in "dns1.domain.tld" "dns2.domain.tld" "dns3.domain.tld" "dns4.domain.tld"; do
ALIAS="$(echo "$CN" | tr . _)"
(cat "${ALIAS}_cert.cer"; echo; cat "${ALIAS}_interm.cer"; echo; cat "${ALIAS}.key") > "${ALIAS}.pem"
chmod 0400 "${ALIAS}.pem"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment