9647ab
#!/bin/sh
9647ab
#
9647ab
# This script will initialise token storage of softhsm PKCS11 provider
9647ab
# in custom location. Is useful to store tokens in non-standard location.
9647ab
9647ab
SOFTHSM2_CONF="$1"
9647ab
TOKENPATH="$2"
9647ab
GROUPNAME="$3"
9647ab
# Do not use this script for real keys worth protection
9647ab
# This is intended for crypto accelerators using PKCS11 interface.
9647ab
# Uninitialized token would fail any crypto operation.
9647ab
PIN=1234
9647ab
9647ab
set -e
9647ab
9647ab
if [ -z "$SOFTHSM2_CONF" -o -z "$TOKENPATH" ]; then
9647ab
	echo "Usage: $0 <config file> <token directory> [group]" >&2
9647ab
	exit 1
9647ab
fi
9647ab
9647ab
if ! [ -f "$SOFTHSM2_CONF" ]; then
9647ab
cat  << SED > "$SOFTHSM2_CONF"
9647ab
# SoftHSM v2 configuration file
9647ab
9647ab
directories.tokendir = ${TOKENPATH}
9647ab
objectstore.backend = file
9647ab
9647ab
# ERROR, WARNING, INFO, DEBUG
9647ab
log.level = ERROR
9647ab
9647ab
# If CKF_REMOVABLE_DEVICE flag should be set
9647ab
slots.removable = false
9647ab
SED
9647ab
else
9647ab
	echo "Config file $SOFTHSM2_CONF already exists" >&2
9647ab
fi
9647ab
9647ab
[ -d "$TOKENPATH" ] || mkdir -p "$TOKENPATH"
9647ab
9647ab
export SOFTHSM2_CONF
9647ab
9647ab
if softhsm2-util --show-slots | grep 'Initialized:[[:space:]]*yes' > /dev/null
9647ab
then
9647ab
	echo "Token in ${TOKENPATH} is already initialized" >&2
9647ab
else
9647ab
	echo "Initializing tokens to ${TOKENPATH}..."
9647ab
	softhsm2-util --init-token --free --label rpm --pin $PIN --so-pin $PIN
9647ab
9647ab
	if [ -n "$GROUPNAME" ]; then
9647ab
		chgrp -R -- "$GROUPNAME" "$TOKENPATH"
9647ab
		chmod -R -- g=rX,o= "$TOKENPATH"
9647ab
	fi
9647ab
fi
9647ab
9647ab
echo "export SOFTHSM2_CONF=\"$SOFTHSM2_CONF\""