Skip to content

Instantly share code, notes, and snippets.

@ntrrgc
Created August 4, 2015 22:19
Show Gist options
  • Save ntrrgc/7b5f604c55b4aa67ca42 to your computer and use it in GitHub Desktop.
Save ntrrgc/7b5f604c55b4aa67ca42 to your computer and use it in GitHub Desktop.
Script to request and install new SSL certificates without moving files by hand
#!/bin/bash
set -eu
if [ "$#" -ne 1 ]; then
echo "Usage: $0 domain.example.com"
echo
echo "Generates a private key and a default CSR which you can send to" \
"your CA. It prompts later for the certificate and stores it in a" \
"reasonable place."
echo "Tested only with StartSSL."
exit 1
fi
DOMAIN="$1"
KEY_FILE="/etc/ssl/private/${DOMAIN}.key"
CERT_FILE="/etc/ssl/certs/${DOMAIN}.pem"
CHAIN_FILE="/etc/ssl/certs/${DOMAIN}.chain.pem"
CHAIN_CAS=("/etc/ssl/certs/sub.class1.server.ca.pem")
safe_backup() {
# Backup a private key or cert without risk of the backup being overwritten
# by the command being ran twice.
FILE=$1
if [ -f "${FILE}" ]; then
YEAR=$(date '+%Y')
HASH=$(sha1sum "$1" | cut -c 1-10)
FILE_BACKUP="${FILE}.${YEAR}.${HASH}.bak"
cp "${FILE}" "${FILE_BACKUP}"
echo "Backup created: ${FILE_BACKUP}"
else
echo "Backup skipped (file does not exist): ${FILE}"
fi
}
# Backup everything (never run twice!)
safe_backup "${KEY_FILE}"
safe_backup "${CERT_FILE}"
openssl genrsa -out "${KEY_FILE}" 4096
echo "Paste the following CSR to your CA:"
echo
openssl req -new -batch -key "${KEY_FILE}"
echo
echo "Once you receive the certificate, paste it here:"
echo "(End input with new line plus Ctrl+D)"
cat > "${CERT_FILE}"
cat "${CERT_FILE}" "${CHAIN_CAS[@]}" > "${CHAIN_FILE}"
echo "Certificate stored successfully!"
echo "Private key: ${KEY_FILE}"
echo "Certificate file: ${CERT_FILE}"
echo "Certificate with chain: ${CHAIN_FILE}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment