Skip to content

Instantly share code, notes, and snippets.

@aduzsardi
Created March 27, 2018 06:51
Show Gist options
  • Save aduzsardi/3e795d50540014505d55a03a9eb7735a to your computer and use it in GitHub Desktop.
Save aduzsardi/3e795d50540014505d55a03a9eb7735a to your computer and use it in GitHub Desktop.
Create CA with openssl
#!/bin/bash
# Usage: `./ca-init test` - this will create a CA cert with CN = My TEST CA
# server,client certs will be generated with ansible, but i needed the CA to be manually generated for each environment.
PKI_BASE="$1"
PKI_HOME="${PKI_HOME:="/keybase/private/${USER}/pki"}"
PKI_PATH="${PKI_HOME}/${PKI_BASE}"
# validity days
PKI_CA_VALIDITY="7300"
# key settings
PKI_DEFAULT_DIGEST="sha256"
PKI_DEFAULT_KEY_SIZE="2048"
PKI_SUBJ="/C=HH/ST=Hawaii/L=Honolulu/O=Home/OU=HQ/CN=My ${1^^} CA"
PKI_CA_EXT=$(cat <<'EOT'
[ req ]
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
countryName = HH
stateOrProvinceName = Hawaii
localityName = Honolulu
0.organizationName = Home
organizationalUnitName = HQ
[ ca_ext ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign
EOT
)
confirm() {
local prompt="$1"
local value="$2"
local msg="$3"
local input=""
printf "\n\t%s\n\t%s" "$msg" "Type the word '$value' to continue, or any other input to abort."
printf "\n\n\t%s" "$prompt"
read input
[ "$input" = "$value" ] && return
printf "\n %s \n" "Aborting without confirmation."
exit 1
}
init_pki() {
if [ -e "$PKI_PATH" ]; then
confirm "Confirm removal: " "yes" "WARNING!!! You are about to remove the PKI at: $PKI_PATH and initialize a fresh PKI here."
rm -rf "$PKI_PATH" || echo "Could not remove $PKI_PATH"
fi
mkdir -p "$PKI_PATH" || die "Failed to create PKI file structure (permissions?)"
return 0
}
build_ca() {
local err="Unable to create necessary PKI files (permissions?)"
local out_file="$PKI_PATH/ca.crt"
local out_key="$PKI_PATH/ca.key"
echo
openssl req -config <(echo "$PKI_CA_EXT") -x509 -new -utf8 -newkey rsa:"$PKI_DEFAULT_KEY_SIZE" \
-rand /dev/urandom -days "$PKI_CA_VALIDITY" -${PKI_DEFAULT_DIGEST} \
-extensions ca_ext -keyout "$out_key" -out "$out_file" -subj "$PKI_SUBJ" -nodes -batch || \
echo "Failed to build the CA"
echo
echo "pki-init complete; Your newly created PKI dir is: $PKI_PATH"
echo
return 0
}
init_pki
build_ca
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment