#!/bin/sh
# The offline half of the step-ca recipe with an offline root
# (https://ydentifi.io/docs/step-ca-recipes#recipe-2), run with the step CLI, of the version the CA's
# image carries (0.30), on a machine that is not networked and holds the
# root's key:
#
#   offline.sh root <name> <dir>
#       Makes a root, <dir>/root_ca.crt, and its key, <dir>/root_ca_key,
#       encrypted as PKCS#8 under PBKDF2 with a password step asks for 3
#       times: to make the key, then to read it and write it again. step
#       writes a key in the older PEM encryption, whose key is MD5 of the
#       password and a salt, without iterations, to <dir>/root_ca_key.pem,
#       which it names, and which is removed. Prints the root's fingerprint,
#       which intermediate.sh install takes, and its pin, the SHA-256 of its
#       public key as phones pin it and the server logs it for a backup root.
#       The backup root is made by a second run, with another name and directory.
#
#   offline.sh pin <certificate>
#       Prints the pin of the root in <certificate>, as root prints it: for a
#       root made before, or elsewhere, as another CA's backup root.
#
#   offline.sh sign <dir> <request.csr> <intermediate.pem> <key fingerprint> [lifetime]
#       Signs the intermediate the CA asked for (intermediate.sh request)
#       with the root in <dir>, once the file, one PEM block that is a
#       certificate request, is over the key with the fingerprint the CA
#       printed for it, and writes the intermediate only when it is over
#       that key: a request swapped or added to on its way is refused. The
#       intermediate lives 3 years (26280h) when no lifetime is given: it is
#       replaced every year, and outlives every certificate issued under it,
#       the longest of which, a relying party's, lives 2. A client checks the
#       dates of each certificate in the chain, so a certificate that
#       outlived its intermediate would fail with it. For the same reason an
#       intermediate that would outlive the root is not signed, as one of 3
#       years would in the root's last 3 years: a root lives 10 years, and is
#       replaced before its 8th year begins. A shorter lifetime, a duration
#       such as 8760h that ends before the root does, may be given as the last
#       argument. The file written holds the intermediate, then the root.
#
# YDFI_ROOT_PASSWORD_FILE, when set, names a file holding the root key's
# password, in place of the prompts. A root whose key is not written
# encrypted, as with an empty file, is removed, and the command fails.
set -eu

usage() {
	echo "usage: offline.sh root <name> <dir> | pin <certificate> | sign <dir> <request.csr> <intermediate.pem> <key fingerprint> [lifetime]" >&2
	exit 2
}

# pin prints the pin of the root in the file $1: the SHA-256 of its public
# key, base64url without padding, as phones pin it and the server logs it.
pin() {
	spki=$(step crypto key fingerprint --pkix --format base64-url-raw "$1")
	echo "offline.sh: the root's pin is ${spki#SHA256:}"
}

[ $# -ge 1 ] || usage
case "$1" in
root)
	[ $# -eq 3 ] || usage
	name=$2 dir=$3
	if [ -e "$dir/root_ca.crt" ] || [ -e "$dir/root_ca_key" ] || [ -e "$dir/root_ca_key.pem" ]; then
		echo "offline.sh: $dir already holds a root, or a key of one; a second root is made in another directory" >&2
		exit 1
	fi
	mkdir -p "$dir"
	# None of the 3 files was there, so a root not made whole is removed,
	# also when a signal ends the script: some shells run no EXIT trap then.
	trap 'rm -f "$dir/root_ca.crt" "$dir/root_ca_key" "$dir/root_ca_key.pem"' EXIT
	trap 'exit 1' HUP INT TERM
	step certificate create "$name" "$dir/root_ca.crt" "$dir/root_ca_key.pem" \
		--profile root-ca --kty EC --crv P-256 --not-after 87600h \
		${YDFI_ROOT_PASSWORD_FILE:+"--password-file=$YDFI_ROOT_PASSWORD_FILE"}
	step crypto key format "$dir/root_ca_key.pem" --pkcs8 --pem --out "$dir/root_ca_key" \
		${YDFI_ROOT_PASSWORD_FILE:+"--password-file=$YDFI_ROOT_PASSWORD_FILE"}
	rm -f "$dir/root_ca_key.pem"
	case "$(head -n 1 "$dir/root_ca_key")" in
	*"BEGIN ENCRYPTED PRIVATE KEY"*) ;;
	*)
		echo "offline.sh: the root's key was not written encrypted, as with an empty password; no root is made" >&2
		exit 1
		;;
	esac
	trap - EXIT HUP INT TERM
	echo "offline.sh: the root is $dir/root_ca.crt; its key, $dir/root_ca_key, stays on this machine"
	echo "offline.sh: the root's fingerprint is $(step certificate fingerprint "$dir/root_ca.crt")"
	pin "$dir/root_ca.crt"
	;;
pin)
	[ $# -eq 2 ] || usage
	pin "$2"
	;;
sign)
	[ $# -eq 5 ] || [ $# -eq 6 ] || usage
	dir=$2 request=$3 out=$4 fingerprint=$5 lifetime=${6:-26280h}
	work=$(mktemp -d)
	trap 'rm -rf "$work"' EXIT
	# The request is one certificate request and nothing else. step reads a
	# key from the first certificate, request or public key in a file, and
	# signs the first request in it, so a file holding more than one block
	# could pass the fingerprint's check with one key and be signed over
	# another.
	if [ "$(grep -c -- '-----BEGIN ' "$request")" != 1 ] || ! grep -qx -- '-----BEGIN CERTIFICATE REQUEST-----' "$request"; then
		echo "offline.sh: $request is not one certificate request alone; it is not signed" >&2
		exit 1
	fi
	step certificate key "$request" >"$work/request.pub"
	got=$(step crypto key fingerprint "$work/request.pub")
	if [ "$got" != "$fingerprint" ]; then
		echo "offline.sh: the request's key is $got, not the $fingerprint the CA printed; it is not signed" >&2
		exit 1
	fi
	# needs-renewal exits 0 when the root ends within the lifetime, 1 when it
	# outlives it, and otherwise when the lifetime cannot be read.
	ends=0
	step certificate needs-renewal "$dir/root_ca.crt" --expires-in "$lifetime" >/dev/null 2>&1 || ends=$?
	case "$ends" in
	0)
		echo "offline.sh: the root ends within $lifetime, before the intermediate would; it is not signed: the root is replaced before its 8th year begins, or a shorter lifetime is given" >&2
		exit 1
		;;
	1) ;;
	*)
		echo "offline.sh: the root's end could not be measured against the lifetime $lifetime; it is not signed" >&2
		exit 1
		;;
	esac
	step certificate sign "$request" "$dir/root_ca.crt" "$dir/root_ca_key" \
		--profile intermediate-ca --not-after "$lifetime" \
		${YDFI_ROOT_PASSWORD_FILE:+"--password-file=$YDFI_ROOT_PASSWORD_FILE"} >"$work/intermediate.crt"
	# A second line of defence, should the checks above miss a file step
	# reads otherwise: the intermediate signed is over the key checked, or
	# nothing is written.
	step certificate key "$work/intermediate.crt" >"$work/signed.pub"
	signed=$(step crypto key fingerprint "$work/signed.pub")
	if [ "$signed" != "$fingerprint" ]; then
		echo "offline.sh: the intermediate signed is over the key $signed, not $fingerprint; nothing is written" >&2
		exit 1
	fi
	cat "$work/intermediate.crt" "$dir/root_ca.crt" >"$out"
	echo "offline.sh: $out holds the intermediate, then the root; intermediate.sh install puts it on the CA"
	;;
*)
	usage
	;;
esac
