Skip to content

Instantly share code, notes, and snippets.

@lennartvdd
Created August 18, 2017 07:31
Show Gist options
  • Save lennartvdd/f2f7334f6ab6633baffdb8d8a388a5e8 to your computer and use it in GitHub Desktop.
Save lennartvdd/f2f7334f6ab6633baffdb8d8a388a5e8 to your computer and use it in GitHub Desktop.
Easily create CA, Client and Server certifcates
#!/usr/bin/env bash
# Copyright: Lennart van den Dool <lennartvdd at gmail dot com>
# All rights reserved.
# License: FreeBSD
# Settings
# ----
read -p "Application DNS: " app_dns
app_ip=$(ping -n 1 ${app_dns} | gawk -F'[' '/Pinging/{print $2}' | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
if [ -z ${app_ip} ]; then
echo "Could not resolve host ${app_dns} to a valid IPv4 address. Halting execution"
exit 1
fi
echo "IP: $app_ip"
set -e
# Script Helper Methods
# ----
info() {
echo ""
echo " ---> $1 "
echo ""
}
certdir=certs/${app_dns}/
if [ -d ${certdir} ]; then
read -p "Directory ${certdir} already exists. Overwrite? [y/N]" answer
case ${answer:0:1} in
y|Y )
rm -rf ${certdir}
;;
* )
exit 0
;;
esac
fi
mkdir -p ${certdir} && cd ${certdir}
info "Creating certificates for ${app_dns} with IP ${app_ip} ... "
# Actual Script
# ----
info "Creating a Certificate Authority (CA)"
# Create CA Private Key: ca-key.pem. (NOTE: manually enter a password)
openssl genrsa -aes256 -out ca-key.pem 4096
# Create CA Public Key: ca.pem
openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem
echo "Done!"
info "Creating Server Certificates"
# Create Server Private Key: server-key.pem
openssl genrsa -out server-key.pem 4096
# Create Server Public Key CSR
openssl req -subj "/CN=${app_dns}" -sha256 -new -key server-key.pem -out server.csr
echo subjectAltName = DNS:${app_dns},IP:${app_ip},IP:127.0.0.1 > extfile.cnf
# Create & Sign Server Public Key
openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \
-CAcreateserial -out server.pem -extfile extfile.cnf
# Cleanup CSR
rm extfile.cnf
rm server.csr
echo "Done!"
info "Creating Client Certificates"
# Create Client Private Key
openssl genrsa -out client-key.pem 4096
# Create Client Public Key CSR
openssl req -subj '/CN=client' -new -key client-key.pem -out client.csr
echo extendedKeyUsage = clientAuth > extfile.cnf
# Create and Sign Client Public Key
openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \
-CAcreateserial -out client-cert.pem -extfile extfile.cnf
# CLeanup CSR
rm extfile.cnf
rm client.csr
echo "Done!"
echo "Your certificate bundle can be found under ${certdir}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment