Last active
April 27, 2021 03:20
-
-
Save variadico/44fadb0d1eb6b319d47b24811e2ff9c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -euo pipefail | |
create_ca() { | |
domain="myca.private" | |
cakey="${domain}-ca-key.pem" | |
cacrt="${domain}-ca-cert.pem" | |
echo "Creating CA for domain: ${domain}" | |
echo "Certificate: ${cacrt}" | |
echo "Private Key: ${cakey}" | |
set -x | |
openssl req -x509 -nodes -days 90 -newkey rsa:4096 -keyout "$cakey" \ | |
-subj "/C=US/ST=California/L=San Francisco/O=My CA/OU=IT/CN=${domain}" \ | |
-out "${cacrt}" | |
set +x | |
} | |
issue_cert() { | |
domain="$1" | |
ca_domain="myca.private" | |
cacrt="$2" | |
cakey="$3" | |
key="${domain}-key.pem" | |
csr="${domain}-csr.pem" | |
crt="${domain}-cert.pem" | |
echo "Issuing certificate for domain: ${domain}" | |
echo "Certificate: ${crt}" | |
echo "Private Key: ${key}" | |
set -x | |
openssl req -nodes -newkey rsa:4096 -keyout "${key}" \ | |
-subj "/C=US/ST=California/L=San Francisco/O=Acme Corp/OU=IT/CN=${domain}" \ | |
-out "${csr}" | |
openssl x509 -req -days 90 -in "${csr}" -CA "${cacrt}" -CAkey "${cakey}" -CAcreateserial \ | |
-extfile <(echo " | |
basicConstraints = CA:FALSE | |
subjectKeyIdentifier = hash | |
authorityKeyIdentifier = keyid,issuer | |
subjectAltName = DNS:${domain} | |
") \ | |
-out "${crt}" | |
rm "${ca_domain}-ca-cert.srl" | |
set +x | |
} | |
! getopt --test > /dev/null | |
if [[ ${PIPESTATUS[0]} -ne 4 ]]; then | |
echo 'install GNU getopt and try again' | |
exit 1 | |
fi | |
OPTIONS='' | |
LONGOPTS=create-ca,issue-cert:,ca-cert:,ca-key: | |
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@") | |
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then | |
exit 2 | |
fi | |
eval set -- "$PARSED" | |
create_ca_domain="" | |
issue_cert_domain="" | |
ca_cert="" | |
ca_key="" | |
while true; do | |
case "$1" in | |
--create-ca) | |
create_ca_domain="yes" | |
shift 1 | |
;; | |
--issue-cert) | |
issue_cert_domain="$2" | |
shift 2 | |
;; | |
--ca-cert) | |
ca_cert="$2" | |
shift 2 | |
;; | |
--ca-key) | |
ca_key="$2" | |
shift 2 | |
;; | |
--) | |
shift | |
break | |
;; | |
*) | |
echo "error" | |
exit 3 | |
;; | |
esac | |
done | |
if [[ -n "$create_ca_domain" ]]; then | |
create_ca "$create_ca_domain" | |
fi | |
if [[ -n "$issue_cert_domain" ]] && [[ -n "$ca_cert" ]] && [[ -n "$ca_key" ]]; then | |
issue_cert "$issue_cert_domain" "$ca_cert" "$ca_key" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment