1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#!/bin/sh
# This test generates a self-signed certificate using the openssl engine from
# libp11 and a software-based "smart card" (softhsm2). It's based on
# https://github.com/OpenSC/libp11/blob/master/README.md#using-p11tool-and-openssl-from-the-command-line
set -e
PIN="1234"
SO_PIN="12341234"
URI="pkcs11:model=SoftHSM%20v2"
SUBJECT="CN=libp11-DEP8"
workdir=$(mktemp -d)
ssl_cnf="${workdir}/ssl.cnf"
req_pem="${workdir}/req.pem"
cert_pem="${workdir}/cert.pem"
DEB_BUILD_MULTIARCH="$(dpkg-architecture -q DEB_BUILD_MULTIARCH)"
cleanup() {
if [ -n "${workdir}" -a -d "${workdir}" ]; then
rm -rf "${workdir}"
fi
rm -rf /var/lib/softhsm/tokens/*
}
trap cleanup EXIT
cat > ${ssl_cnf} <<EOF
HOME = .
openssl_conf = openssl_init
[openssl_init]
engines = engine_section
[engine_section]
pkcs11 = pkcs11_section
[pkcs11_section]
engine_id = pkcs11
dynamic_path = /usr/lib/${DEB_BUILD_MULTIARCH}/engines-3/pkcs11.so
MODULE_PATH = /usr/lib/${DEB_BUILD_MULTIARCH}/softhsm/libsofthsm2.so
init = 0
EOF
echo "Initializing softhsm2"
softhsm2-util --init-token --free --label test-token --pin ${PIN} --so-pin ${SO_PIN}
echo "Generating RSA key in the softhsm2 token"
p11tool \
--provider /usr/lib/${DEB_BUILD_MULTIARCH}/softhsm/libsofthsm2.so \
--login --generate-rsa --bits 1024 --label test-key --set-pin ${PIN} \
--outfile /dev/stdout "${URI}"
echo "Listing generated private key"
p11tool \
--provider /usr/lib/${DEB_BUILD_MULTIARCH}/softhsm/libsofthsm2.so \
--list-privkeys --login --set-pin ${PIN} "${URI}"
echo "With openssl engine, generate a certificate request with the RSA key in the softhsm2 token"
OPENSSL_CONF="${ssl_cnf}" openssl \
req -engine pkcs11 -new -key "${URI};object=test-key;pin-value=${PIN}" \
-keyform engine -out ${req_pem} -text -x509 -subj "/${SUBJECT}"
echo "Sign the request with the RSA key"
OPENSSL_CONF="${ssl_cnf}" openssl \
x509 -engine pkcs11 -signkey "${URI};object=test-key;pin-value=${PIN}" \
-keyform engine -in ${req_pem} -out ${cert_pem}
echo "Confirm the generated certificate is valid and has the subject we specified"
s=$(openssl x509 -in ${cert_pem} -noout -subject | sed -r 's,^subject=,,' | tr -d ' ')
test "${s}" = "${SUBJECT}"
|