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