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