Skip to content

Add storecert example and improve tests for certificate storage #594

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ examples/listkeys
examples/listkeys_ext
examples/eckeygen
examples/rsakeygen
examples/storecert

test-driver
tests/openssl_version
Expand All @@ -75,14 +76,12 @@ tests/rsa-oaep
tests/rsa-pss-sign
tests/check-privkey
tests/dup-key
tests/store-cert
tests/check-privkey-prov
tests/dup-key-prov
tests/evp-sign-prov
tests/fork-change-slot-prov
tests/rsa-oaep-prov
tests/rsa-pss-sign-prov
tests/store-cert-prov
tests/rsa-keygen
tests/ec-keygen
tests/check-all-prov
Expand Down
2 changes: 1 addition & 1 deletion examples/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ AM_CPPFLAGS = -I$(srcdir) -I$(top_srcdir)/src \

EXTRA_DIST = README

noinst_PROGRAMS = auth decrypt getrandom listkeys listkeys_ext eckeygen rsakeygen
noinst_PROGRAMS = auth decrypt getrandom listkeys listkeys_ext eckeygen rsakeygen storecert

LDADD = ../src/libp11.la $(OPENSSL_LIBS)

Expand Down
210 changes: 210 additions & 0 deletions examples/storecert.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/*
* Copyright © 2025 Mobi - Com Polska Sp. z o.o.
* Author: Małgorzata Olszówka <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/

/* libp11 example code: storecert.c
*
* This example demonstrates how to connect to a PKCS#11-compatible
* smart card (token) and store an X.509 certificate on it.
*/

#include <libp11.h>
#include <string.h>
#include <openssl/pem.h>

#define CHECK_ERR(cond, txt, code) \
do { \
if (cond) { \
fprintf(stderr, "%s\n", (txt)); \
rc=(code); \
goto end; \
} \
} while (0)

static void error_queue(const char *name)
{
if (ERR_peek_last_error()) {
fprintf(stderr, "%s generated errors:\n", name);
ERR_print_errors_fp(stderr);
}
}

static int hex_to_bytes(const char *hex, unsigned char *out, size_t out_len)
{
size_t i;

for (i = 0; i < out_len; i++) {
if (sscanf(hex + (i * 2), "%2hhx", &out[i]) != 1) {
return -1;
}
}
return 0;
}

static int extract_url_fields(char *uri, char **out_token, char **out_label,
char **out_id, char **out_pin)
{
static const char DELIMITERS[] = ":;?&=";
char *str, *token;

if (strncmp(uri, "pkcs11:", strlen("pkcs11:")) != 0) {
printf("URL does not look valid: %s\n", uri);
return 0;
}
str = uri + strlen("pkcs11:");
while ((token = strtok(str, DELIMITERS))) {
char **out = NULL;

str = NULL;
if (!strcmp(token, "token")) {
out = out_token;
} else if (!strcmp(token, "object")) {
out = out_label;
} else if (!strcmp(token, "id") ) {
out = out_id;
} else if (!strcmp(token, "pin-value")) {
out = out_pin;
} else {
printf("Unrecognized token: %s\n", token);
return 0;
}
if (out) {
if (*out) {
printf("Repeated token: %s\n", token);
return 0;
} else if ((token = strtok(str, DELIMITERS))) {
*out = token;
}
}
}
if (!*out_token || !*out_label || !*out_pin) {
printf("URL incomplete\n");
return 0;
}
return 1;
}

int main(int argc, char *argv[])
{
PKCS11_CTX *ctx = NULL;
PKCS11_SLOT *slots = NULL, *slot;
unsigned int nslots;
char *token = NULL, *label = NULL, *id_str = NULL, *pin = NULL;
unsigned char *id = NULL;
size_t id_len = 0;
FILE *file;
X509 *cert = NULL;
int rc = 0;

if (argc < 4) {
fprintf(stderr, "usage: %s [source certificate file] [target certificate URI] [module]\n", argv[0]);
return 1;
}

/* load an X509 certificate from a PEM file */
file = fopen(argv[1], "rb");
CHECK_ERR(!file, "Failed to open source certificate file\n", 1);

cert = PEM_read_X509(file, NULL, NULL, NULL);
fclose(file);
CHECK_ERR(!cert, "Failed to load certificate\n", 2);

printf("Certificate found: %s\n", argv[1]);

/* parse the target PKCS#11 URI */
rc = extract_url_fields(argv[2], &token, &label, &id_str, &pin);
CHECK_ERR(rc < 0, "Invalid certificate URI", 3);

if (id_str) {
size_t len = strlen(id_str);

CHECK_ERR(len % 2 != 0, "Invalid key ID format: odd length", 4);
id_len = len / 2;
id = OPENSSL_malloc(id_len);
CHECK_ERR(!id, "Memory allocation failed", 5);
rc = hex_to_bytes(id_str, id, id_len);
CHECK_ERR(rc < 0, "Invalid hex ID format", 6);
} else {
id = (unsigned char*)label;
id_len = strlen(label);
}

ctx = PKCS11_CTX_new();
error_queue("PKCS11_CTX_new");
CHECK_ERR(!ctx, "Could not initialize libp11 context", 7);

/* load PKCS#11 module */
rc = PKCS11_CTX_load(ctx, argv[3]);
error_queue("PKCS11_CTX_load");
CHECK_ERR(rc < 0, "Failed to load PKCS#11 module", 8);

/* get information on all slots */
rc = PKCS11_enumerate_slots(ctx, &slots, &nslots);
error_queue("PKCS11_enumerate_slots");
CHECK_ERR(rc < 0, "no slots available", 9);

slot = PKCS11_find_token(ctx, slots, nslots);
error_queue("PKCS11_find_token");
while (slot) {
if (!strncmp(token, slot->token->label, strlen(token)))
break;
slot = PKCS11_find_next_token(ctx, slots, nslots, slot);
}
CHECK_ERR(!slot || !slot->token, "No token available", 10);

rc = PKCS11_open_session(slot, 1);
error_queue("PKCS11_open_session");
CHECK_ERR(rc < 0, "Failed to open session", 11);

/* log in with a provided PIN */
rc = PKCS11_login(slot, 0, pin);
error_queue("PKCS11_login ");
CHECK_ERR(rc < 0, "PKCS11_login failed", 12);

/* store the certificate using the specified label and ID */
rc = PKCS11_store_certificate(slot->token, cert, label, id, id_len, NULL);
error_queue("PKCS11_store_certificate");
CHECK_ERR(rc < 0, "PKCS11_store_certificate failed", 13);

end:
X509_free(cert);
if (id_str)
OPENSSL_free(id);
if (slots)
PKCS11_release_all_slots(ctx, slots, nslots);
if (ctx) {
PKCS11_CTX_unload(ctx);
PKCS11_CTX_free(ctx);
}

if (rc)
printf("Storing failed (error code %d).\n", rc);
else
printf("Certificate stored.\n");
return rc;
}

/* vim: set noexpandtab: */
1 change: 0 additions & 1 deletion src/provider.c
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
#endif /* _WIN32 */

#include "util.h"
#include "p11_pthread.h"

#include <ctype.h> /* isdigit() */

Expand Down
5 changes: 1 addition & 4 deletions tests/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ check_PROGRAMS = \
rsa-oaep-prov \
check-privkey \
check-privkey-prov \
store-cert \
store-cert-prov \
dup-key \
dup-key-prov \
check-all-prov \
Expand All @@ -39,6 +37,7 @@ dist_check_SCRIPTS = \
rsa-pss-sign.softhsm \
rsa-oaep.softhsm \
rsa-check-privkey.softhsm \
rsa-cert-store.softhsm \
rsa-keygen.softhsm \
ec-testfork.softhsm \
ec-evp-sign.softhsm \
Expand All @@ -58,7 +57,6 @@ dist_check_SCRIPTS = \
provider-ec-evp-sign.softhsm \
provider-ec-check-privkey.softhsm \
provider-ec-check-all.softhsm \
provider-ec-cert-store.softhsm \
provider-ec-copy.softhsm \
provider-fork-change-slot.softhsm \
provider-case-insensitive.softhsm \
Expand All @@ -74,7 +72,6 @@ dup_key_prov_SOURCES = dup-key-prov.c helpers_prov.c
check_privkey_prov_SOURCES = check-privkey-prov.c helpers_prov.c
rsa_pss_sign_prov_SOURCES = rsa-pss-sign-prov.c helpers_prov.c
rsa_oaep_prov_SOURCES = rsa-oaep-prov.c helpers_prov.c
store_cert_prov_SOURCES = store-cert-prov.c helpers_prov.c
check_all_prov_SOURCES = check-all-prov.c helpers_prov.c

TESTS = $(dist_check_SCRIPTS)
Expand Down
2 changes: 1 addition & 1 deletion tests/common.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

# Uncomment the following line to enable debugging with Valgrind
# WRAPPER="valgrind -s --track-origins=yes --leak-check=full --show-leak-kinds=all --tool=memcheck --show-reachable=yes --keep-debuginfo=yes"
# WRAPPER="libtool --mode=execute valgrind -s --track-origins=yes --leak-check=full --show-leak-kinds=all --tool=memcheck --show-reachable=yes --keep-debuginfo=yes"

echo "Current directory: $(pwd)"
echo "Source directory: ${srcdir}"
Expand Down
7 changes: 3 additions & 4 deletions tests/ec-cert-store.softhsm
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@

outdir="output.$$"

CERTIFICATE_URL="pkcs11:token=libp11-0;object=stored-cert;pin-value=1234"

# Load common test functions
. ${srcdir}/common.sh

Expand All @@ -38,9 +36,10 @@ TEMP_LD_LIBRARY_PATH=${LD_LIBRARY_PATH}
${OPENSSL} x509 -in ${srcdir}/ec-cert.der -inform DER -outform PEM \
-out ${outdir}/ec-cert.pem
CERTIFICATE="${outdir}/ec-cert.pem"
CERTIFICATE_URL="pkcs11:token=libp11-0;id=04030201;object=stored-cert;pin-value=1234"

# Run the test
${WRAPPER} ./store-cert ${CERTIFICATE} ${CERTIFICATE_URL} ${MODULE} "${outdir}/engines.cnf"
${WRAPPER} ../examples/storecert ${CERTIFICATE} ${CERTIFICATE_URL} ${MODULE}
if [[ $? -ne 0 ]]; then
echo "The certificate storing couldn't be performed"
exit 1
Expand All @@ -49,7 +48,7 @@ fi
# Restore settings
export LD_LIBRARY_PATH=${TEMP_LD_LIBRARY_PATH}

list_objects | grep -q stored-cert
list_objects && list_objects | grep -q stored-cert
if [[ $? -ne 0 ]]; then
echo "The certificate was not properly stored"
exit 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,35 +21,23 @@ outdir="output.$$"
# Load common test functions
. ${srcdir}/common.sh

CERTIFICATE_URL="pkcs11:token=libp11-0;object=stored-cert;pin-value=${PIN}"

if [[ "${OPENSSL_VERSION}" =~ ^[012].* ]]; then
echo "Skipping test with OpenSSL ${OPENSSL_VERSION}"
exit 77
fi

# Do the token initialization
init_token "ec" "1" "libp11" ${ID} "server-key" "privkey" "" "cert"

# Ensure the use of the locally built provider; applies after running 'pkcs11-tool'
unset OPENSSL_ENGINES
export OPENSSL_MODULES="../src/.libs/"
export PKCS11_MODULE_PATH=${MODULE}
echo "OPENSSL_MODULES=${OPENSSL_MODULES}"
echo "PKCS11_MODULE_PATH=${PKCS11_MODULE_PATH}"
init_token "rsa" "1" "libp11" ${ID} "server-key" "privkey" "" "cert"

# Load openssl settings
TEMP_LD_LIBRARY_PATH=${LD_LIBRARY_PATH}
. ${srcdir}/openssl-settings.sh

${OPENSSL} x509 -in ${srcdir}/ec-cert.der -inform DER -outform PEM \
-out ${outdir}/ec-cert.pem
CERTIFICATE="${outdir}/ec-cert.pem"
# RSA certificate to store
${OPENSSL} x509 -in ${srcdir}/rsa-cert.der -inform DER -outform PEM \
-out ${outdir}/rsa-cert.pem
CERTIFICATE="${outdir}/rsa-cert.pem"
CERTIFICATE_URL="pkcs11:token=libp11-0;id=04030201;object=stored-cert;pin-value=1234"

# Run the test
${WRAPPER} ./store-cert-prov ${CERTIFICATE} ${CERTIFICATE_URL} ${MODULE}
${WRAPPER} ../examples/storecert ${CERTIFICATE} ${CERTIFICATE_URL} ${MODULE}
if [[ $? -ne 0 ]]; then
echo "The certificate storing couldn't be performed"
echo "RSA certificate storing couldn't be performed"
exit 1
fi

Expand All @@ -58,7 +46,7 @@ export LD_LIBRARY_PATH=${TEMP_LD_LIBRARY_PATH}

list_objects && list_objects | grep -q stored-cert
if [[ $? -ne 0 ]]; then
echo "The certificate was not properly stored"
echo "The RSA certificate was not properly stored"
exit 1
fi

Expand Down
Loading
Loading