:

# This uses the public/private keys on a Yubikey, and uses a PIN
# stored in a file.

[ "$#" -ne 1 ] && echo "cluster_passphrase_command usage: $0 \"%d\"" 1>&2 && exit 1
# No need for %R or -R since we are not prompting for a PIN

DIR="$1"

# File that stores the PIN to unlock the Yubikey
PIN_FILE='/u/postgres/tmp/piv.pin'

# PIV slot 3 is the "Key Management" slot
PIV_SLOT='0:3'

# File containing the passphrased encrypted with the PIV_SLOT's public key
KEY_FILE="$DIR/yubipass.key"


# Create a passphrased encrypted with the PIV_SLOT's public key?
if [ ! -e "$KEY_FILE" ]
then	# The 'postgres' operating system user must have permission to
	# access the Yubikey device.

	openssl rand -hex 32 |
	xxd -plain -cols 999 |
	openssl rsautl -engine pkcs11 -keyform engine -encrypt \
		-inkey "$PIV_SLOT" -passin file:"$PIN_FILE" -out "$KEY_FILE"

	# Warn the user to save the passphrase in a safe place
	cat 1>&2 <<END

WARNING:  The Yubikey can be locked and require a reset if too many PIN
attempts fail.  It is recommended to run this command manually and save
the passphrase in a secure location for possible recovery.
END

fi

# Decrypt the passphrased encrypted with the PIV_SLOT's public key
openssl rsautl -engine pkcs11 -keyform engine -decrypt \
		-inkey "$PIV_SLOT" -passin file:"$PIN_FILE" -in "$KEY_FILE"

exit 0
