From bdd6188e299405e16179906bc79f9fef2605176a Mon Sep 17 00:00:00 2001 From: Stef Walter Date: Fri, 27 May 2011 14:42:35 +0200 Subject: Change around installation of headers, pkg-config, and file names * Install headers to ${prefix}/include/p11-kit-1/p11-kit/ * This solves problems with other projects that have their own pkcs11.h files. * Change the pkg-config file name to p11-kit-1.pc * Change the source file names. --- p11-kit/Makefile.am | 18 +- p11-kit/debug.h | 4 +- p11-kit/messages.c | 242 ++++++++ p11-kit/modules.c | 1195 ++++++++++++++++++++++++++++++++++++++ p11-kit/p11-kit-1.pc.in | 17 + p11-kit/p11-kit-lib.c | 1195 -------------------------------------- p11-kit/p11-kit-messages.c | 242 -------- p11-kit/p11-kit-private.h | 52 -- p11-kit/p11-kit-proxy.c | 1382 -------------------------------------------- p11-kit/p11-kit-uri.c | 1337 ------------------------------------------ p11-kit/p11-kit-uri.h | 135 ----- p11-kit/p11-kit.h | 2 +- p11-kit/p11-kit.pc | 17 - p11-kit/p11-kit.pc.in | 17 - p11-kit/private.h | 52 ++ p11-kit/proxy.c | 1382 ++++++++++++++++++++++++++++++++++++++++++++ p11-kit/uri.c | 1337 ++++++++++++++++++++++++++++++++++++++++++ p11-kit/uri.h | 135 +++++ 18 files changed, 4372 insertions(+), 4389 deletions(-) create mode 100644 p11-kit/messages.c create mode 100644 p11-kit/modules.c create mode 100644 p11-kit/p11-kit-1.pc.in delete mode 100644 p11-kit/p11-kit-lib.c delete mode 100644 p11-kit/p11-kit-messages.c delete mode 100644 p11-kit/p11-kit-private.h delete mode 100644 p11-kit/p11-kit-proxy.c delete mode 100644 p11-kit/p11-kit-uri.c delete mode 100644 p11-kit/p11-kit-uri.h delete mode 100644 p11-kit/p11-kit.pc delete mode 100644 p11-kit/p11-kit.pc.in create mode 100644 p11-kit/private.h create mode 100644 p11-kit/proxy.c create mode 100644 p11-kit/uri.c create mode 100644 p11-kit/uri.h (limited to 'p11-kit') diff --git a/p11-kit/Makefile.am b/p11-kit/Makefile.am index 0b7e163..1f2de49 100644 --- a/p11-kit/Makefile.am +++ b/p11-kit/Makefile.am @@ -2,11 +2,11 @@ INCLUDES = \ -DP11_KIT_API_SUBJECT_TO_CHANGE -incdir = $(includedir)/p11-kit +incdir = $(includedir)/p11-kit-1/p11-kit inc_HEADERS = \ p11-kit.h \ - p11-kit-uri.h \ + uri.h \ pkcs11.h MODULE_SRCS = \ @@ -14,11 +14,11 @@ MODULE_SRCS = \ debug.c debug.h \ hash.c hash.h \ util.c util.h \ - p11-kit-lib.c \ - p11-kit-proxy.c \ - p11-kit-private.h \ - p11-kit-messages.c \ - p11-kit-uri.c \ + modules.c \ + proxy.c \ + private.h \ + messages.c \ + uri.c \ $(inc_HEADERS) lib_LTLIBRARIES = \ @@ -38,7 +38,7 @@ libp11_kit_testable_la_LDFLAGS = \ libp11_kit_testable_la_SOURCES = $(MODULE_SRCS) pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = p11-kit.pc +pkgconfig_DATA = p11-kit-1.pc EXTRA_DIST = \ - p11-kit.pc.in \ No newline at end of file + p11-kit-1.pc.in \ No newline at end of file diff --git a/p11-kit/debug.h b/p11-kit/debug.h index 47e5cc4..acc9ca6 100644 --- a/p11-kit/debug.h +++ b/p11-kit/debug.h @@ -55,13 +55,13 @@ void debug_message (int flag, * more than once. So you can do: * * #define DEBUG_FLAG DEBUG_ONE_THING - * #include "gkr-debug.h" + * #include "debug.h" * ... * DEBUG ("if we're debugging one thing"); * ... * #undef DEBUG_FLAG * #define DEBUG_FLAG DEBUG_OTHER_THING - * #include "gkr-debug.h" + * #include "debug.h" * ... * DEBUG ("if we're debugging the other thing"); * ... diff --git a/p11-kit/messages.c b/p11-kit/messages.c new file mode 100644 index 0000000..bfc637c --- /dev/null +++ b/p11-kit/messages.c @@ -0,0 +1,242 @@ +/* + * Copyright (C) 2011 Collabora Ltd. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * 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. + * * The names of contributors to this software may not be + * used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 + * COPYRIGHT OWNER 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. + * + * Author: Stef Walter + */ + +#include "config.h" + +#include "pkcs11.h" +#include "p11-kit.h" + +/** + * SECTION:p11-kit-util + * @title: Utilities + * @short_description: PKCS\#11 utilities + * + * Utility functions for working with PKCS\#11. + */ + +#ifdef ENABLE_NLS +#include +#define _(x) dgettext(PACKAGE_NAME, x) +#else +#define _(x) x +#endif + +/** + * p11_kit_strerror: + * @rv: The code to get a message for. + * + * Get a message for a PKCS\#11 return value or error code. Do not + * pass CKR_OK or other such non errors to this function. + * + * Returns: The user readable and localized message. + **/ +const char* +p11_kit_strerror (CK_RV rv) +{ + switch (rv) { + + /* These are not really errors, or not current */ + case CKR_OK: + case CKR_NO_EVENT: + case CKR_FUNCTION_NOT_PARALLEL: + case CKR_SESSION_PARALLEL_NOT_SUPPORTED: + return ""; + + case CKR_CANCEL: + case CKR_FUNCTION_CANCELED: + return _("The operation was cancelled"); + + case CKR_HOST_MEMORY: + return _("Insufficient memory available"); + case CKR_SLOT_ID_INVALID: + return _("The specified slot ID is not valid"); + case CKR_GENERAL_ERROR: + return _("Internal error"); + case CKR_FUNCTION_FAILED: + return _("The operation failed"); + case CKR_ARGUMENTS_BAD: + return _("Invalid arguments"); + case CKR_NEED_TO_CREATE_THREADS: + return _("The module cannot create needed threads"); + case CKR_CANT_LOCK: + return _("The module cannot lock data properly"); + case CKR_ATTRIBUTE_READ_ONLY: + return _("The field is read-only"); + case CKR_ATTRIBUTE_SENSITIVE: + return _("The field is sensitive and cannot be revealed"); + case CKR_ATTRIBUTE_TYPE_INVALID: + return _("The field is invalid or does not exist"); + case CKR_ATTRIBUTE_VALUE_INVALID: + return _("Invalid value for field"); + case CKR_DATA_INVALID: + return _("The data is not valid or unrecognized"); + case CKR_DATA_LEN_RANGE: + return _("The data is too long"); + case CKR_DEVICE_ERROR: + return _("An error occurred on the device"); + case CKR_DEVICE_MEMORY: + return _("Insufficient memory available on the device"); + case CKR_DEVICE_REMOVED: + return _("The device was removed or unplugged"); + case CKR_ENCRYPTED_DATA_INVALID: + return _("The encrypted data is not valid or unrecognized"); + case CKR_ENCRYPTED_DATA_LEN_RANGE: + return _("The encrypted data is too long"); + case CKR_FUNCTION_NOT_SUPPORTED: + return _("This operation is not supported"); + case CKR_KEY_HANDLE_INVALID: + return _("The key is missing or invalid"); + case CKR_KEY_SIZE_RANGE: + return _("The key is the wrong size"); + case CKR_KEY_TYPE_INCONSISTENT: + return _("The key is of the wrong type"); + case CKR_KEY_NOT_NEEDED: + return _("No key is needed"); + case CKR_KEY_CHANGED: + return _("The key is different than before"); + case CKR_KEY_NEEDED: + return _("A key is needed"); + case CKR_KEY_INDIGESTIBLE: + return _("Cannot include the key in the digest"); + case CKR_KEY_FUNCTION_NOT_PERMITTED: + return _("This operation cannot be done with this key"); + case CKR_KEY_NOT_WRAPPABLE: + return _("The key cannot be wrapped"); + case CKR_KEY_UNEXTRACTABLE: + return _("Cannot export this key"); + case CKR_MECHANISM_INVALID: + return _("The crypto mechanism is invalid or unrecognized"); + case CKR_MECHANISM_PARAM_INVALID: + return _("The crypto mechanism has an invalid argument"); + case CKR_OBJECT_HANDLE_INVALID: + return _("The object is missing or invalid"); + case CKR_OPERATION_ACTIVE: + return _("Another operation is already taking place"); + case CKR_OPERATION_NOT_INITIALIZED: + return _("No operation is taking place"); + case CKR_PIN_INCORRECT: + return _("The password or PIN is incorrect"); + case CKR_PIN_INVALID: + return _("The password or PIN is invalid"); + case CKR_PIN_LEN_RANGE: + return _("The password or PIN is of an invalid length"); + case CKR_PIN_EXPIRED: + return _("The password or PIN has expired"); + case CKR_PIN_LOCKED: + return _("The password or PIN is locked"); + case CKR_SESSION_CLOSED: + return _("The session is closed"); + case CKR_SESSION_COUNT: + return _("Too many sessions are active"); + case CKR_SESSION_HANDLE_INVALID: + return _("The session is invalid"); + case CKR_SESSION_READ_ONLY: + return _("The session is read-only"); + case CKR_SESSION_EXISTS: + return _("An open session exists"); + case CKR_SESSION_READ_ONLY_EXISTS: + return _("A read-only session exists"); + case CKR_SESSION_READ_WRITE_SO_EXISTS: + return _("An administrator session exists"); + case CKR_SIGNATURE_INVALID: + return _("The signature is bad or corrupted"); + case CKR_SIGNATURE_LEN_RANGE: + return _("The signature is unrecognized or corrupted"); + case CKR_TEMPLATE_INCOMPLETE: + return _("Certain required fields are missing"); + case CKR_TEMPLATE_INCONSISTENT: + return _("Certain fields have invalid values"); + case CKR_TOKEN_NOT_PRESENT: + return _("The device is not present or unplugged"); + case CKR_TOKEN_NOT_RECOGNIZED: + return _("The device is invalid or unrecognizable"); + case CKR_TOKEN_WRITE_PROTECTED: + return _("The device is write protected"); + case CKR_UNWRAPPING_KEY_HANDLE_INVALID: + return _("Cannot import because the key is invalid"); + case CKR_UNWRAPPING_KEY_SIZE_RANGE: + return _("Cannot import because the key is of the wrong size"); + case CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: + return _("Cannot import because the key is of the wrong type"); + case CKR_USER_ALREADY_LOGGED_IN: + return _("You are already logged in"); + case CKR_USER_NOT_LOGGED_IN: + return _("No user has logged in"); + case CKR_USER_PIN_NOT_INITIALIZED: + return _("The user's password or PIN is not set"); + case CKR_USER_TYPE_INVALID: + return _("The user is of an invalid type"); + case CKR_USER_ANOTHER_ALREADY_LOGGED_IN: + return _("Another user is already logged in"); + case CKR_USER_TOO_MANY_TYPES: + return _("Too many users of different types are logged in"); + case CKR_WRAPPED_KEY_INVALID: + return _("Cannot import an invalid key"); + case CKR_WRAPPED_KEY_LEN_RANGE: + return _("Cannot import a key of the wrong size"); + case CKR_WRAPPING_KEY_HANDLE_INVALID: + return _("Cannot export because the key is invalid"); + case CKR_WRAPPING_KEY_SIZE_RANGE: + return _("Cannot export because the key is of the wrong size"); + case CKR_WRAPPING_KEY_TYPE_INCONSISTENT: + return _("Cannot export because the key is of the wrong type"); + case CKR_RANDOM_SEED_NOT_SUPPORTED: + return _("Unable to initialize the random number generator"); + case CKR_RANDOM_NO_RNG: + return _("No random number generator available"); + case CKR_DOMAIN_PARAMS_INVALID: + return _("The crypto mechanism has an invalid parameter"); + case CKR_BUFFER_TOO_SMALL: + return _("Not enough space to store the result"); + case CKR_SAVED_STATE_INVALID: + return _("The saved state is invalid"); + case CKR_INFORMATION_SENSITIVE: + return _("The information is sensitive and cannot be revealed"); + case CKR_STATE_UNSAVEABLE: + return _("The state cannot be saved"); + case CKR_CRYPTOKI_NOT_INITIALIZED: + return _("The module has not been initialized"); + case CKR_CRYPTOKI_ALREADY_INITIALIZED: + return _("The module has already been initialized"); + case CKR_MUTEX_BAD: + return _("Cannot lock data"); + case CKR_MUTEX_NOT_LOCKED: + return _("The data cannot be locked"); + case CKR_FUNCTION_REJECTED: + return _("The signature request was rejected by the user"); + + default: + return _("Unknown error"); + } +} diff --git a/p11-kit/modules.c b/p11-kit/modules.c new file mode 100644 index 0000000..25fd204 --- /dev/null +++ b/p11-kit/modules.c @@ -0,0 +1,1195 @@ +/* + * Copyright (C) 2008 Stefan Walter + * Copyright (C) 2011 Collabora Ltd. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * 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. + * * The names of contributors to this software may not be + * used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 + * COPYRIGHT OWNER 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. + * + * Author: Stef Walter + */ + +#include "config.h" + +#include "conf.h" +#define DEBUG_FLAG DEBUG_LIB +#include "debug.h" +#include "hash.h" +#include "pkcs11.h" +#include "p11-kit.h" +#include "private.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * SECTION:p11-kit + * @title: Modules + * @short_description: Module loading and initializing + * + * PKCS\#11 modules are used by crypto libraries and applications to access + * crypto objects (like keys and certificates) and to perform crypto operations. + * + * In order for applications to behave consistently with regard to the user's + * installed PKCS\#11 modules, each module must be registered so that applications + * or libraries know that they should load it. + * + * The functions here provide support for initializing registered modules. The + * p11_kit_initialize_registered() function should be used to load and initialize + * the registered modules. When done, the p11_kit_finalize_registered() function + * should be used to release those modules and associated resources. + * + * In addition p11_kit_registered_option() can be used to access other parts + * of the module configuration. + * + * When multiple consumers of a module (such as libraries or applications) are + * in the same process, coordination of the initialization and finalization + * of PKCS\#11 modules is required. The functions here automatically provide + * initialization reference counting to make this work. + * + * If a consumer wishes to load an arbitrary PKCS\#11 module that's not + * registered, that module should be initialized with p11_kit_initialize_module() + * and finalized with p11_kit_finalize_module(). The module's own + * C_Initialize and C_Finalize methods should not + * be called directly. + * + * Modules are represented by a pointer to their CK_FUNCTION_LIST + * entry points. This means that callers can load modules elsewhere, using + * dlopen() for example, and then still use these methods on them. + */ + +typedef struct _Module { + char *name; + hash_t *config; + void *dl_module; + CK_FUNCTION_LIST_PTR funcs; + int ref_count; + int initialize_count; + CK_C_INITIALIZE_ARGS init_args; +} Module; + +/* + * This is the mutex that protects the global data of this library + * and the pkcs11 proxy module. Note that we *never* call into our + * underlying pkcs11 modules while holding this mutex. Therefore it + * doesn't have to be recursive and we can keep things simple. + */ +pthread_mutex_t _p11_mutex = PTHREAD_MUTEX_INITIALIZER; + +/* + * Shared data between threads, protected by the mutex, a structure so + * we can audit thread safety easier. + */ +static struct _Shared { + hash_t *modules; + hash_t *config; +} gl = { NULL, NULL }; + +/* ----------------------------------------------------------------------------- + * UTILITIES + */ + +static void +warning (const char* msg, ...) +{ + char buffer[512]; + va_list va; + + va_start (va, msg); + + vsnprintf(buffer, sizeof (buffer) - 1, msg, va); + buffer[sizeof (buffer) - 1] = 0; + fprintf (stderr, "p11-kit: %s\n", buffer); + + va_end (va); +} + +static void +conf_error (const char *buffer) +{ + /* called from conf.c */ + fprintf (stderr, "p11-kit: %s\n", buffer); +} + +static char* +strconcat (const char *first, ...) +{ + size_t length = 0; + const char *arg; + char *result, *at; + va_list va; + + va_start (va, first); + + for (arg = first; arg; arg = va_arg (va, const char*)) + length += strlen (arg); + + va_end (va); + + at = result = malloc (length); + if (!result) + return NULL; + + va_start (va, first); + + for (arg = first; arg; arg = va_arg (va, const char*)) { + length = strlen (arg); + memcpy (at, arg, length); + at += length; + } + + va_end (va); + + *at = 0; + return result; +} + +static int +strequal (const char *one, const char *two) +{ + return strcmp (one, two) == 0; +} + +/* ----------------------------------------------------------------------------- + * P11-KIT FUNCTIONALITY + */ + +static CK_RV +create_mutex (CK_VOID_PTR_PTR mut) +{ + pthread_mutex_t *pmutex; + int err; + + if (mut == NULL) + return CKR_ARGUMENTS_BAD; + + pmutex = malloc (sizeof (pthread_mutex_t)); + if (!pmutex) + return CKR_HOST_MEMORY; + err = pthread_mutex_init (pmutex, NULL); + if (err == ENOMEM) + return CKR_HOST_MEMORY; + else if (err != 0) + return CKR_GENERAL_ERROR; + *mut = pmutex; + return CKR_OK; +} + +static CK_RV +destroy_mutex (CK_VOID_PTR mut) +{ + pthread_mutex_t *pmutex = mut; + int err; + + if (mut == NULL) + return CKR_MUTEX_BAD; + + err = pthread_mutex_destroy (pmutex); + if (err == EINVAL) + return CKR_MUTEX_BAD; + else if (err != 0) + return CKR_GENERAL_ERROR; + free (pmutex); + return CKR_OK; +} + +static CK_RV +lock_mutex (CK_VOID_PTR mut) +{ + pthread_mutex_t *pmutex = mut; + int err; + + if (mut == NULL) + return CKR_MUTEX_BAD; + + err = pthread_mutex_lock (pmutex); + if (err == EINVAL) + return CKR_MUTEX_BAD; + else if (err != 0) + return CKR_GENERAL_ERROR; + return CKR_OK; +} + +static CK_RV +unlock_mutex (CK_VOID_PTR mut) +{ + pthread_mutex_t *pmutex = mut; + int err; + + if (mut == NULL) + return CKR_MUTEX_BAD; + + err = pthread_mutex_unlock (pmutex); + if (err == EINVAL) + return CKR_MUTEX_BAD; + else if (err == EPERM) + return CKR_MUTEX_NOT_LOCKED; + else if (err != 0) + return CKR_GENERAL_ERROR; + return CKR_OK; +} + +static void +free_module_unlocked (void *data) +{ + Module *module = data; + + assert (module); + + /* Module must be finalized */ + assert (module->initialize_count == 0); + + /* Module must have no outstanding references */ + assert (module->ref_count == 0); + + if (module->dl_module) + dlclose (module->dl_module); + hash_free (module->config); + free (module->name); + free (module); +} + +static Module* +alloc_module_unlocked (void) +{ + Module *module; + + module = calloc (1, sizeof (Module)); + if (!module) + return NULL; + + module->init_args.CreateMutex = create_mutex; + module->init_args.DestroyMutex = destroy_mutex; + module->init_args.LockMutex = lock_mutex; + module->init_args.UnlockMutex = unlock_mutex; + module->init_args.flags = CKF_OS_LOCKING_OK; + + return module; +} + +static CK_RV +load_module_from_config_unlocked (const char *configfile, const char *name) +{ + Module *module, *prev; + const char *path; + CK_C_GetFunctionList gfl; + CK_RV rv; + + assert (configfile); + + module = alloc_module_unlocked (); + if (!module) + return CKR_HOST_MEMORY; + + module->config = conf_parse_file (configfile, 0, conf_error); + if (!module->config) { + free_module_unlocked (module); + if (errno == ENOMEM) + return CKR_HOST_MEMORY; + return CKR_GENERAL_ERROR; + } + + module->name = strdup (name); + if (!module->name) { + free_module_unlocked (module); + return CKR_HOST_MEMORY; + } + + path = hash_get (module->config, "module"); + if (path == NULL) { + free_module_unlocked (module); + warning ("no module path specified in config: %s", configfile); + return CKR_GENERAL_ERROR; + } + + module->dl_module = dlopen (path, RTLD_LOCAL | RTLD_NOW); + if (module->dl_module == NULL) { + warning ("couldn't load module: %s: %s", path, dlerror ()); + free_module_unlocked (module); + return CKR_GENERAL_ERROR; + } + + gfl = dlsym (module->dl_module, "C_GetFunctionList"); + if (!gfl) { + warning ("couldn't find C_GetFunctionList entry point in module: %s: %s", + path, dlerror ()); + free_module_unlocked (module); + return CKR_GENERAL_ERROR; + } + + rv = gfl (&module->funcs); + if (rv != CKR_OK) { + warning ("call to C_GetFunctiontList failed in module: %s: %s", + path, p11_kit_strerror (rv)); + free_module_unlocked (module); + return rv; + } + + prev = hash_get (gl.modules, module->funcs); + + /* Replace previous module that was loaded explicitly? */ + if (prev && !prev->name) { + module->ref_count = prev->ref_count; + module->initialize_count = prev->initialize_count; + prev->ref_count = 0; + prev->initialize_count = 0; + prev = NULL; /* freed by hash_set below */ + } + + /* Refuse to load duplicate module */ + if (prev) { + warning ("duplicate configured module: %s: %s", module->name, path); + free_module_unlocked (module); + return CKR_GENERAL_ERROR; + } + + /* + * We support setting of CK_C_INITIALIZE_ARGS.pReserved from + * 'x-init-reserved' setting in the config. This only works with specific + * PKCS#11 modules, and is non-standard use of that field. + */ + module->init_args.pReserved = hash_get (module->config, "x-init-reserved"); + + if (!hash_set (gl.modules, module->funcs, module)) { + free_module_unlocked (module); + return CKR_HOST_MEMORY; + } + + return CKR_OK; +} + +static CK_RV +load_modules_from_config_unlocked (const char *directory) +{ + struct dirent *dp; + struct stat st; + CK_RV rv = CKR_OK; + DIR *dir; + int is_dir; + char *path; + + debug ("loading module configs in: %s", directory); + + /* First we load all the modules */ + dir = opendir (directory); + if (!dir) { + if (errno == ENOENT || errno == ENOTDIR) + warning ("couldn't list directory: %s", directory); + return CKR_GENERAL_ERROR; + } + + /* We're within a global mutex, so readdir is safe */ + while ((dp = readdir(dir)) != NULL) { + path = strconcat (directory, "/", dp->d_name, NULL); + if (!path) { + rv = CKR_HOST_MEMORY; + break; + } + + is_dir = 0; +#ifdef HAVE_STRUCT_DIRENT_D_TYPE + if(dp->d_type != DT_UNKNOWN) { + is_dir = (dp->d_type == DT_DIR); + } else +#endif + { + if (stat (path, &st) < 0) { + warning ("couldn't stat path: %s", path); + free (path); + rv = CKR_GENERAL_ERROR; + break; + } + is_dir = S_ISDIR (st.st_mode); + } + + if (is_dir) + rv = CKR_OK; + else + rv = load_module_from_config_unlocked (path, dp->d_name); + + free (path); + + if (rv != CKR_OK) + break; + } + + closedir (dir); + + return rv; +} + +static char* +expand_user_path (const char *path) +{ + const char *env; + struct passwd *pwd; + + if (path[0] == '~' && path[1] == '/') { + env = getenv ("HOME"); + if (env && env[0]) { + return strconcat (env, path + 1, NULL); + } else { + pwd = getpwuid (getuid ()); + if (!pwd) + return NULL; + return strconcat (pwd->pw_dir, path + 1, NULL); + } + } + + return strdup (path); +} + +enum { + USER_CONFIG_INVALID = 0, + USER_CONFIG_NONE = 1, + USER_CONFIG_MERGE, + USER_CONFIG_OVERRIDE +}; + +static int +user_config_mode (hash_t *config, int defmode) +{ + const char *mode; + + /* Whether we should use or override from user directory */ + mode = hash_get (config, "user-config"); + if (mode == NULL) { + return defmode; + } else if (strequal (mode, "none")) { + return USER_CONFIG_NONE; + } else if (strequal (mode, "merge")) { + return USER_CONFIG_MERGE; + } else if (strequal (mode, "override")) { + return USER_CONFIG_OVERRIDE; + } else { + warning ("invalid mode for 'user-config': %s", mode); + return USER_CONFIG_INVALID; + } +} + +static CK_RV +load_config_files_unlocked (int *user_mode) +{ + hash_t *config = NULL; + hash_t *uconfig = NULL; + void *key = NULL; + void *value = NULL; + char *path; + int mode; + CK_RV rv = CKR_GENERAL_ERROR; + hash_iter_t hi; + + /* Should only be called after everything has been unloaded */ + assert (!gl.config); + + /* Load the main configuration */ + config = conf_parse_file (P11_SYSTEM_CONF, CONF_IGNORE_MISSING, conf_error); + if (!config) { + rv = (errno == ENOMEM) ? CKR_HOST_MEMORY : CKR_GENERAL_ERROR; + goto finished; + } + + /* Whether we should use or override from user directory */ + mode = user_config_mode (config, USER_CONFIG_NONE); + if (mode == USER_CONFIG_INVALID) + goto finished; + + if (mode != USER_CONFIG_NONE) { + path = expand_user_path (P11_USER_CONF); + if (!path) + goto finished; + + /* Load up the user configuration */ + uconfig = conf_parse_file (path, CONF_IGNORE_MISSING, conf_error); + free (path); + + if (!uconfig) { + rv = (errno == ENOMEM) ? CKR_HOST_MEMORY : CKR_GENERAL_ERROR; + goto finished; + } + + /* Figure out what the user mode is */ + mode = user_config_mode (uconfig, mode); + if (mode == USER_CONFIG_INVALID) + goto finished; + + /* Merge everything into the system config */ + if (mode == USER_CONFIG_MERGE) { + hash_iterate (uconfig, &hi); + while (hash_next (&hi, &key, &value)) { + key = strdup (key); + if (key == NULL) + goto finished; + value = strdup (value); + if (value == NULL) + goto finished; + if (!hash_set (config, key, value)) + goto finished; + key = NULL; + value = NULL; + } + + /* Override the system config */ + } else if (mode == USER_CONFIG_OVERRIDE) { + hash_free (config); + config = uconfig; + uconfig = NULL; + } + } + + gl.config = config; + config = NULL; + rv = CKR_OK; + + if (user_mode) + *user_mode = mode; + +finished: + hash_free (config); + hash_free (uconfig); + free (key); + free (value); + return rv; +} + +static CK_RV +load_registered_modules_unlocked (void) +{ + char *path; + int mode; + CK_RV rv; + + rv = load_config_files_unlocked (&mode); + if (rv != CKR_OK) + return rv; + + assert (gl.config); + assert (mode != USER_CONFIG_INVALID); + + /* Load each module from the main list */ + if (mode != USER_CONFIG_OVERRIDE) { + rv = load_modules_from_config_unlocked (P11_SYSTEM_MODULES); + if (rv != CKR_OK); + return rv; + } + + /* Load each module from the user list */ + if (mode != USER_CONFIG_NONE) { + path = expand_user_path (P11_USER_MODULES); + if (!path) + rv = CKR_GENERAL_ERROR; + else + rv = load_modules_from_config_unlocked (path); + free (path); + if (rv != CKR_OK); + return rv; + } + + return CKR_OK; +} + +static CK_RV +initialize_module_unlocked_reentrant (Module *module) +{ + CK_RV rv = CKR_OK; + + assert (module); + + /* + * Initialize first, so module doesn't get freed out from + * underneath us when the mutex is unlocked below. + */ + ++module->ref_count; + + if (!module->initialize_count) { + + _p11_unlock (); + + assert (module->funcs); + rv = module->funcs->C_Initialize (&module->init_args); + + _p11_lock (); + + /* + * Because we have the mutex unlocked above, two initializes could + * race. Therefore we need to take CKR_CRYPTOKI_ALREADY_INITIALIZED + * into account. + * + * We also need to take into account where in a race both calls return + * CKR_OK (which is not according to the spec but may happen, I mean we + * do it in this module, so it's not unimaginable). + */ + + if (rv == CKR_OK) + ++module->initialize_count; + else if (rv == CKR_CRYPTOKI_ALREADY_INITIALIZED) + rv = CKR_OK; + else + --module->ref_count; + } + + return rv; +} + +static void +reinitialize_after_fork (void) +{ + hash_iter_t it; + Module *module; + + /* WARNING: This function must be reentrant */ + debug ("forked"); + + _p11_lock (); + + if (gl.modules) { + hash_iterate (gl.modules, &it); + while (hash_next (&it, NULL, (void**)&module)) { + module->initialize_count = 0; + + /* WARNING: Reentrancy can occur here */ + initialize_module_unlocked_reentrant (module); + } + } + + _p11_unlock (); + + _p11_kit_proxy_after_fork (); +} + +static CK_RV +init_globals_unlocked (void) +{ + static int once = 0; + + if (!gl.modules) + gl.modules = hash_create (hash_direct_hash, hash_direct_equal, + NULL, free_module_unlocked); + if (!gl.modules) + return CKR_HOST_MEMORY; + + if (once) + return CKR_OK; + + pthread_atfork (NULL, NULL, reinitialize_after_fork); + once = 1; + + return CKR_OK; +} + +static void +free_modules_when_no_refs_unlocked (void) +{ + Module *module; + hash_iter_t it; + + /* Check if any modules have a ref count */ + hash_iterate (gl.modules, &it); + while (hash_next (&it, NULL, (void**)&module)) { + if (module->ref_count) + return; + } + + hash_free (gl.modules); + gl.modules = NULL; + hash_free (gl.config); + gl.config = NULL; +} + +static CK_RV +finalize_module_unlocked_reentrant (Module *module) +{ + assert (module); + + /* + * We leave module info around until all are finalized + * so we can encounter these zombie Module structures. + */ + if (module->ref_count == 0) + return CKR_ARGUMENTS_BAD; + + if (--module->ref_count > 0) + return CKR_OK; + + /* + * Becuase of the mutex unlock below, we temporarily increase + * the ref count. This prevents module from being freed out + * from ounder us. + */ + ++module->ref_count; + + while (module->initialize_count > 0) { + + _p11_unlock (); + + assert (module->funcs); + module->funcs->C_Finalize (NULL); + + _p11_lock (); + + if (module->initialize_count > 0) + --module->initialize_count; + } + + /* Match the increment above */ + --module->ref_count; + + free_modules_when_no_refs_unlocked (); + return CKR_OK; +} + +static Module* +find_module_for_name_unlocked (const char *name) +{ + Module *module; + hash_iter_t it; + + assert (name); + + hash_iterate (gl.modules, &it); + while (hash_next (&it, NULL, (void**)&module)) + if (module->ref_count && module->name && strcmp (name, module->name) == 0) + return module; + return NULL; +} + +CK_RV +_p11_kit_initialize_registered_unlocked_reentrant (void) +{ + Module *module; + hash_iter_t it; + CK_RV rv; + + rv = init_globals_unlocked (); + if (rv == CKR_OK) + rv = load_registered_modules_unlocked (); + if (rv == CKR_OK) { + hash_iterate (gl.modules, &it); + while (hash_next (&it, NULL, (void**)&module)) { + + /* Skip all modules that aren't registered */ + if (!module->name) + continue; + + rv = initialize_module_unlocked_reentrant (module); + + if (rv != CKR_OK) { + debug ("failed to initialize module: %s: %s", + module->name, p11_kit_strerror (rv)); + break; + } + } + } + + return rv; +} + +/** + * p11_kit_initialize_registered: + * + * Initialize all the registered PKCS\#11 modules. + * + * If this is the first time this function is called multiple times + * consecutively within a single process, then it merely increments an + * initialization reference count for each of these modules. + * + * Use p11_kit_finalize_registered() to finalize these registered modules once + * the caller is done with them. + * + * Returns: CKR_OK if the initialization succeeded, or an error code. + */ +CK_RV +p11_kit_initialize_registered (void) +{ + CK_RV rv; + + /* WARNING: This function must be reentrant */ + debug ("in"); + + _p11_lock (); + + /* WARNING: Reentrancy can occur here */ + rv = _p11_kit_initialize_registered_unlocked_reentrant (); + + _p11_unlock (); + + /* Cleanup any partial initialization */ + if (rv != CKR_OK) + p11_kit_finalize_registered (); + + debug ("out: %lu"); + return rv; +} + +CK_RV +_p11_kit_finalize_registered_unlocked_reentrant (void) +{ + Module *module; + hash_iter_t it; + Module **to_finalize; + int i, count; + + if (!gl.modules) + return CKR_CRYPTOKI_NOT_INITIALIZED; + + /* WARNING: This function must be reentrant */ + + to_finalize = calloc (hash_count (gl.modules), sizeof (Module*)); + if (!to_finalize) + return CKR_HOST_MEMORY; + + count = 0; + hash_iterate (gl.modules, &it); + while (hash_next (&it, NULL, (void**)&module)) { + + /* Skip all modules that aren't registered */ + if (module->name) + to_finalize[count++] = module; + } + + debug ("finalizing %d modules", count); + + for (i = 0; i < count; ++i) { + /* WARNING: Reentrant calls can occur here */ + finalize_module_unlocked_reentrant (to_finalize[i]); + } + + free (to_finalize); + return CKR_OK; +} + +/** + * p11_kit_finalize_registered: + * + * Finalize all the registered PKCS\#11 modules. These should have been + * initialized with p11_kit_initialize_registered(). + * + * If p11_kit_initialize_registered() has been called more than once in this + * process, then this function must be called the same number of times before + * actual finalization will occur. + * + * Returns: CKR_OK if the finalization succeeded, or an error code. + */ + +CK_RV +p11_kit_finalize_registered (void) +{ + CK_RV rv; + + /* WARNING: This function must be reentrant */ + debug ("in"); + + _p11_lock (); + + /* WARNING: Reentrant calls can occur here */ + rv = _p11_kit_finalize_registered_unlocked_reentrant (); + + _p11_unlock (); + + debug ("out: %lu", rv); + return rv; +} + +CK_FUNCTION_LIST_PTR_PTR +_p11_kit_registered_modules_unlocked (void) +{ + CK_FUNCTION_LIST_PTR_PTR result; + Module *module; + hash_iter_t it; + int i = 0; + + result = calloc (hash_count (gl.modules) + 1, sizeof (CK_FUNCTION_LIST_PTR)); + if (result) { + hash_iterate (gl.modules, &it); + while (hash_next (&it, NULL, (void**)&module)) { + if (module->ref_count && module->name) + result[i++] = module->funcs; + } + } + + return result; +} + +/** + * p11_kit_registered_modules: + * + * Get a list of all the registered PKCS\#11 modules. This list will be valid + * once the p11_kit_initialize_registered() function has been called. + * + * The returned value is a NULL terminated array of + * CK_FUNCTION_LIST_PTR pointers. + * + * Returns: A list of all the registered modules. Use the free() function to + * free the list. + */ +CK_FUNCTION_LIST_PTR_PTR +p11_kit_registered_modules (void) +{ + CK_FUNCTION_LIST_PTR_PTR result; + + _p11_lock (); + + result = _p11_kit_registered_modules_unlocked (); + + _p11_unlock (); + + return result; +} + +/** + * p11_kit_registered_module_to_name: + * @funcs: pointer to a registered module + * + * Get the name of a registered PKCS\#11 module. + * + * You can use p11_kit_registered_modules() to get a list of all the registered + * modules. This name is specified by the registered module configuration. + * + * Returns: A newly allocated string containing the module name, or + * NULL if no such registered module exists. Use free() to + * free this string. + */ +char* +p11_kit_registered_module_to_name (CK_FUNCTION_LIST_PTR funcs) +{ + Module *module; + char *name = NULL; + + if (!funcs) + return NULL; + + _p11_lock (); + + module = gl.modules ? hash_get (gl.modules, funcs) : NULL; + if (module && module->name) + name = strdup (module->name); + + _p11_unlock (); + + return name; +} + +/** + * p11_kit_registered_name_to_module: + * @name: name of a registered module + * + * Lookup a registered PKCS\#11 module by its name. This name is specified by + * the registered module configuration. + * + * Returns: a pointer to a PKCS\#11 module, or NULL if this name was + * not found. + */ +CK_FUNCTION_LIST_PTR +p11_kit_registered_name_to_module (const char *name) +{ + CK_FUNCTION_LIST_PTR funcs = NULL; + Module *module; + + _p11_lock (); + + if (gl.modules) { + module = find_module_for_name_unlocked (name); + if (module) + funcs = module->funcs; + } + + _p11_unlock (); + + return funcs; +} + +/** + * p11_kit_registered_option: + * @funcs: a pointer to a registered module + * @field: the name of the option to lookup. + * + * Lookup a configured option for a registered PKCS\#11 module. If a + * NULL funcs argument is specified, then this will lookup + * the configuration option in the global config file. + * + * Returns: A newly allocated string containing the option value, or + * NULL if the registered module or the option were not found. + * Use free() to free the returned string. + */ +char* +p11_kit_registered_option (CK_FUNCTION_LIST_PTR funcs, const char *field) +{ + Module *module = NULL; + char *option = NULL; + hash_t *config = NULL; + + if (!field) + return NULL; + + _p11_lock (); + + if (funcs == NULL) { + config = gl.config; + + } else { + module = gl.modules ? hash_get (gl.modules, funcs) : NULL; + if (module) + config = module->config; + } + + if (config) { + option = hash_get (config, field); + if (option) + option = strdup (option); + } + + _p11_unlock (); + + return option; +} + +/** + * p11_kit_initialize_module: + * @funcs: loaded module to initialize. + * + * Initialize an arbitrary PKCS\#11 module. Normally using the + * p11_kit_initialize_registered() is preferred. + * + * Using this function to initialize modules allows coordination between + * multiple users of the same module in a single process. It should be called + * on modules that have been loaded (with dlopen() for example) but not yet + * initialized. The caller should not yet have called the module's + * C_Initialize method. This function will call + * C_Initialize as necessary. + * + * Subsequent calls to this function for the same module will result in an + * initialization count being incremented for the module. It is safe (although + * usually unnecessary) to use this function on registered modules. + * + * The module must be finalized with p11_kit_finalize_module() instead of + * calling its C_Finalize method directly. + * + * This function does not accept a CK_C_INITIALIZE_ARGS argument. + * Custom initialization arguments cannot be supported when multiple consumers + * load the same module. + * + * Returns: CKR_OK if the initialization was successful. + */ +CK_RV +p11_kit_initialize_module (CK_FUNCTION_LIST_PTR funcs) +{ + Module *module; + Module *allocated = NULL; + CK_RV rv = CKR_OK; + + /* WARNING: This function must be reentrant for the same arguments */ + debug ("in"); + + _p11_lock (); + + rv = init_globals_unlocked (); + if (rv == CKR_OK) { + + module = hash_get (gl.modules, funcs); + if (module == NULL) { + debug ("allocating new module"); + allocated = module = alloc_module_unlocked (); + module->funcs = funcs; + } + + /* WARNING: Reentrancy can occur here */ + rv = initialize_module_unlocked_reentrant (module); + + /* If this was newly allocated, add it to the list */ + if (rv == CKR_OK && allocated) { + hash_set (gl.modules, allocated->funcs, allocated); + allocated = NULL; + } + + free (allocated); + } + + _p11_unlock (); + + debug ("out: %lu", rv); + return rv; +} + +/** + * p11_kit_finalize_module: + * @funcs: loaded module to finalize. + * + * Finalize an arbitrary PKCS\#11 module. The module must have been initialized + * using p11_kit_initialize_module(). In most cases callers will want to use + * p11_kit_finalize_registered() instead of this function. + * + * Using this function to finalize modules allows coordination between + * multiple users of the same module in a single process. The caller should + * call the module's C_Finalize method. This function will call + * C_Finalize as necessary. + * + * If the module was initialized more than once, then this function will + * decrement an initialization count for the module. When the count reaches zero + * the module will be truly finalized. It is safe (although usually unnecessary) + * to use this function on registered modules if (and only if) they were + * initialized using p11_kit_initialize_module() for some reason. + * + * Returns: CKR_OK if the finalization was successful. + */ +CK_RV +p11_kit_finalize_module (CK_FUNCTION_LIST_PTR funcs) +{ + Module *module; + CK_RV rv = CKR_OK; + + /* WARNING: This function must be reentrant for the same arguments */ + debug ("in"); + + _p11_lock (); + + module = gl.modules ? hash_get (gl.modules, funcs) : NULL; + if (module == NULL) { + debug ("module not found"); + rv = CKR_ARGUMENTS_BAD; + } else { + /* WARNING: Rentrancy can occur here */ + rv = finalize_module_unlocked_reentrant (module); + } + + _p11_unlock (); + + debug ("out: %lu", rv); + return rv; +} diff --git a/p11-kit/p11-kit-1.pc.in b/p11-kit/p11-kit-1.pc.in new file mode 100644 index 0000000..c5bcdbd --- /dev/null +++ b/p11-kit/p11-kit-1.pc.in @@ -0,0 +1,17 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ +datarootdir=@datarootdir@ +datadir=@datadir@ +sysconfdir=@sysconfdir@ +p11_system_conf=@p11_system_conf@ +p11_system_modules=@p11_system_modules@ +p11_user_conf=@p11_user_conf@ +p11_user_modules=@p11_user_modules@ + +Name: p11-kit +Description: Library and proxy module for properly loading and sharing PKCS#11 modules. +Version: @VERSION@ +Libs: -L${libdir} -lp11-kit +Cflags: -I${includedir}/p11-kit-1 diff --git a/p11-kit/p11-kit-lib.c b/p11-kit/p11-kit-lib.c deleted file mode 100644 index abc58f8..0000000 --- a/p11-kit/p11-kit-lib.c +++ /dev/null @@ -1,1195 +0,0 @@ -/* - * Copyright (C) 2008 Stefan Walter - * Copyright (C) 2011 Collabora Ltd. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * 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. - * * The names of contributors to this software may not be - * used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 - * COPYRIGHT OWNER 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. - * - * Author: Stef Walter - */ - -#include "config.h" - -#include "conf.h" -#define DEBUG_FLAG DEBUG_LIB -#include "debug.h" -#include "hash.h" -#include "pkcs11.h" -#include "p11-kit.h" -#include "p11-kit-private.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/** - * SECTION:p11-kit - * @title: Modules - * @short_description: Module loading and initializing - * - * PKCS\#11 modules are used by crypto libraries and applications to access - * crypto objects (like keys and certificates) and to perform crypto operations. - * - * In order for applications to behave consistently with regard to the user's - * installed PKCS\#11 modules, each module must be registered so that applications - * or libraries know that they should load it. - * - * The functions here provide support for initializing registered modules. The - * p11_kit_initialize_registered() function should be used to load and initialize - * the registered modules. When done, the p11_kit_finalize_registered() function - * should be used to release those modules and associated resources. - * - * In addition p11_kit_registered_option() can be used to access other parts - * of the module configuration. - * - * When multiple consumers of a module (such as libraries or applications) are - * in the same process, coordination of the initialization and finalization - * of PKCS\#11 modules is required. The functions here automatically provide - * initialization reference counting to make this work. - * - * If a consumer wishes to load an arbitrary PKCS\#11 module that's not - * registered, that module should be initialized with p11_kit_initialize_module() - * and finalized with p11_kit_finalize_module(). The module's own - * C_Initialize and C_Finalize methods should not - * be called directly. - * - * Modules are represented by a pointer to their CK_FUNCTION_LIST - * entry points. This means that callers can load modules elsewhere, using - * dlopen() for example, and then still use these methods on them. - */ - -typedef struct _Module { - char *name; - hash_t *config; - void *dl_module; - CK_FUNCTION_LIST_PTR funcs; - int ref_count; - int initialize_count; - CK_C_INITIALIZE_ARGS init_args; -} Module; - -/* - * This is the mutex that protects the global data of this library - * and the pkcs11 proxy module. Note that we *never* call into our - * underlying pkcs11 modules while holding this mutex. Therefore it - * doesn't have to be recursive and we can keep things simple. - */ -pthread_mutex_t _p11_mutex = PTHREAD_MUTEX_INITIALIZER; - -/* - * Shared data between threads, protected by the mutex, a structure so - * we can audit thread safety easier. - */ -static struct _Shared { - hash_t *modules; - hash_t *config; -} gl = { NULL, NULL }; - -/* ----------------------------------------------------------------------------- - * UTILITIES - */ - -static void -warning (const char* msg, ...) -{ - char buffer[512]; - va_list va; - - va_start (va, msg); - - vsnprintf(buffer, sizeof (buffer) - 1, msg, va); - buffer[sizeof (buffer) - 1] = 0; - fprintf (stderr, "p11-kit: %s\n", buffer); - - va_end (va); -} - -static void -conf_error (const char *buffer) -{ - /* called from conf.c */ - fprintf (stderr, "p11-kit: %s\n", buffer); -} - -static char* -strconcat (const char *first, ...) -{ - size_t length = 0; - const char *arg; - char *result, *at; - va_list va; - - va_start (va, first); - - for (arg = first; arg; arg = va_arg (va, const char*)) - length += strlen (arg); - - va_end (va); - - at = result = malloc (length); - if (!result) - return NULL; - - va_start (va, first); - - for (arg = first; arg; arg = va_arg (va, const char*)) { - length = strlen (arg); - memcpy (at, arg, length); - at += length; - } - - va_end (va); - - *at = 0; - return result; -} - -static int -strequal (const char *one, const char *two) -{ - return strcmp (one, two) == 0; -} - -/* ----------------------------------------------------------------------------- - * P11-KIT FUNCTIONALITY - */ - -static CK_RV -create_mutex (CK_VOID_PTR_PTR mut) -{ - pthread_mutex_t *pmutex; - int err; - - if (mut == NULL) - return CKR_ARGUMENTS_BAD; - - pmutex = malloc (sizeof (pthread_mutex_t)); - if (!pmutex) - return CKR_HOST_MEMORY; - err = pthread_mutex_init (pmutex, NULL); - if (err == ENOMEM) - return CKR_HOST_MEMORY; - else if (err != 0) - return CKR_GENERAL_ERROR; - *mut = pmutex; - return CKR_OK; -} - -static CK_RV -destroy_mutex (CK_VOID_PTR mut) -{ - pthread_mutex_t *pmutex = mut; - int err; - - if (mut == NULL) - return CKR_MUTEX_BAD; - - err = pthread_mutex_destroy (pmutex); - if (err == EINVAL) - return CKR_MUTEX_BAD; - else if (err != 0) - return CKR_GENERAL_ERROR; - free (pmutex); - return CKR_OK; -} - -static CK_RV -lock_mutex (CK_VOID_PTR mut) -{ - pthread_mutex_t *pmutex = mut; - int err; - - if (mut == NULL) - return CKR_MUTEX_BAD; - - err = pthread_mutex_lock (pmutex); - if (err == EINVAL) - return CKR_MUTEX_BAD; - else if (err != 0) - return CKR_GENERAL_ERROR; - return CKR_OK; -} - -static CK_RV -unlock_mutex (CK_VOID_PTR mut) -{ - pthread_mutex_t *pmutex = mut; - int err; - - if (mut == NULL) - return CKR_MUTEX_BAD; - - err = pthread_mutex_unlock (pmutex); - if (err == EINVAL) - return CKR_MUTEX_BAD; - else if (err == EPERM) - return CKR_MUTEX_NOT_LOCKED; - else if (err != 0) - return CKR_GENERAL_ERROR; - return CKR_OK; -} - -static void -free_module_unlocked (void *data) -{ - Module *module = data; - - assert (module); - - /* Module must be finalized */ - assert (module->initialize_count == 0); - - /* Module must have no outstanding references */ - assert (module->ref_count == 0); - - if (module->dl_module) - dlclose (module->dl_module); - hash_free (module->config); - free (module->name); - free (module); -} - -static Module* -alloc_module_unlocked (void) -{ - Module *module; - - module = calloc (1, sizeof (Module)); - if (!module) - return NULL; - - module->init_args.CreateMutex = create_mutex; - module->init_args.DestroyMutex = destroy_mutex; - module->init_args.LockMutex = lock_mutex; - module->init_args.UnlockMutex = unlock_mutex; - module->init_args.flags = CKF_OS_LOCKING_OK; - - return module; -} - -static CK_RV -load_module_from_config_unlocked (const char *configfile, const char *name) -{ - Module *module, *prev; - const char *path; - CK_C_GetFunctionList gfl; - CK_RV rv; - - assert (configfile); - - module = alloc_module_unlocked (); - if (!module) - return CKR_HOST_MEMORY; - - module->config = conf_parse_file (configfile, 0, conf_error); - if (!module->config) { - free_module_unlocked (module); - if (errno == ENOMEM) - return CKR_HOST_MEMORY; - return CKR_GENERAL_ERROR; - } - - module->name = strdup (name); - if (!module->name) { - free_module_unlocked (module); - return CKR_HOST_MEMORY; - } - - path = hash_get (module->config, "module"); - if (path == NULL) { - free_module_unlocked (module); - warning ("no module path specified in config: %s", configfile); - return CKR_GENERAL_ERROR; - } - - module->dl_module = dlopen (path, RTLD_LOCAL | RTLD_NOW); - if (module->dl_module == NULL) { - warning ("couldn't load module: %s: %s", path, dlerror ()); - free_module_unlocked (module); - return CKR_GENERAL_ERROR; - } - - gfl = dlsym (module->dl_module, "C_GetFunctionList"); - if (!gfl) { - warning ("couldn't find C_GetFunctionList entry point in module: %s: %s", - path, dlerror ()); - free_module_unlocked (module); - return CKR_GENERAL_ERROR; - } - - rv = gfl (&module->funcs); - if (rv != CKR_OK) { - warning ("call to C_GetFunctiontList failed in module: %s: %s", - path, p11_kit_strerror (rv)); - free_module_unlocked (module); - return rv; - } - - prev = hash_get (gl.modules, module->funcs); - - /* Replace previous module that was loaded explicitly? */ - if (prev && !prev->name) { - module->ref_count = prev->ref_count; - module->initialize_count = prev->initialize_count; - prev->ref_count = 0; - prev->initialize_count = 0; - prev = NULL; /* freed by hash_set below */ - } - - /* Refuse to load duplicate module */ - if (prev) { - warning ("duplicate configured module: %s: %s", module->name, path); - free_module_unlocked (module); - return CKR_GENERAL_ERROR; - } - - /* - * We support setting of CK_C_INITIALIZE_ARGS.pReserved from - * 'x-init-reserved' setting in the config. This only works with specific - * PKCS#11 modules, and is non-standard use of that field. - */ - module->init_args.pReserved = hash_get (module->config, "x-init-reserved"); - - if (!hash_set (gl.modules, module->funcs, module)) { - free_module_unlocked (module); - return CKR_HOST_MEMORY; - } - - return CKR_OK; -} - -static CK_RV -load_modules_from_config_unlocked (const char *directory) -{ - struct dirent *dp; - struct stat st; - CK_RV rv = CKR_OK; - DIR *dir; - int is_dir; - char *path; - - debug ("loading module configs in: %s", directory); - - /* First we load all the modules */ - dir = opendir (directory); - if (!dir) { - if (errno == ENOENT || errno == ENOTDIR) - warning ("couldn't list directory: %s", directory); - return CKR_GENERAL_ERROR; - } - - /* We're within a global mutex, so readdir is safe */ - while ((dp = readdir(dir)) != NULL) { - path = strconcat (directory, "/", dp->d_name, NULL); - if (!path) { - rv = CKR_HOST_MEMORY; - break; - } - - is_dir = 0; -#ifdef HAVE_STRUCT_DIRENT_D_TYPE - if(dp->d_type != DT_UNKNOWN) { - is_dir = (dp->d_type == DT_DIR); - } else -#endif - { - if (stat (path, &st) < 0) { - warning ("couldn't stat path: %s", path); - free (path); - rv = CKR_GENERAL_ERROR; - break; - } - is_dir = S_ISDIR (st.st_mode); - } - - if (is_dir) - rv = CKR_OK; - else - rv = load_module_from_config_unlocked (path, dp->d_name); - - free (path); - - if (rv != CKR_OK) - break; - } - - closedir (dir); - - return rv; -} - -static char* -expand_user_path (const char *path) -{ - const char *env; - struct passwd *pwd; - - if (path[0] == '~' && path[1] == '/') { - env = getenv ("HOME"); - if (env && env[0]) { - return strconcat (env, path + 1, NULL); - } else { - pwd = getpwuid (getuid ()); - if (!pwd) - return NULL; - return strconcat (pwd->pw_dir, path + 1, NULL); - } - } - - return strdup (path); -} - -enum { - USER_CONFIG_INVALID = 0, - USER_CONFIG_NONE = 1, - USER_CONFIG_MERGE, - USER_CONFIG_OVERRIDE -}; - -static int -user_config_mode (hash_t *config, int defmode) -{ - const char *mode; - - /* Whether we should use or override from user directory */ - mode = hash_get (config, "user-config"); - if (mode == NULL) { - return defmode; - } else if (strequal (mode, "none")) { - return USER_CONFIG_NONE; - } else if (strequal (mode, "merge")) { - return USER_CONFIG_MERGE; - } else if (strequal (mode, "override")) { - return USER_CONFIG_OVERRIDE; - } else { - warning ("invalid mode for 'user-config': %s", mode); - return USER_CONFIG_INVALID; - } -} - -static CK_RV -load_config_files_unlocked (int *user_mode) -{ - hash_t *config = NULL; - hash_t *uconfig = NULL; - void *key = NULL; - void *value = NULL; - char *path; - int mode; - CK_RV rv = CKR_GENERAL_ERROR; - hash_iter_t hi; - - /* Should only be called after everything has been unloaded */ - assert (!gl.config); - - /* Load the main configuration */ - config = conf_parse_file (P11_SYSTEM_CONF, CONF_IGNORE_MISSING, conf_error); - if (!config) { - rv = (errno == ENOMEM) ? CKR_HOST_MEMORY : CKR_GENERAL_ERROR; - goto finished; - } - - /* Whether we should use or override from user directory */ - mode = user_config_mode (config, USER_CONFIG_NONE); - if (mode == USER_CONFIG_INVALID) - goto finished; - - if (mode != USER_CONFIG_NONE) { - path = expand_user_path (P11_USER_CONF); - if (!path) - goto finished; - - /* Load up the user configuration */ - uconfig = conf_parse_file (path, CONF_IGNORE_MISSING, conf_error); - free (path); - - if (!uconfig) { - rv = (errno == ENOMEM) ? CKR_HOST_MEMORY : CKR_GENERAL_ERROR; - goto finished; - } - - /* Figure out what the user mode is */ - mode = user_config_mode (uconfig, mode); - if (mode == USER_CONFIG_INVALID) - goto finished; - - /* Merge everything into the system config */ - if (mode == USER_CONFIG_MERGE) { - hash_iterate (uconfig, &hi); - while (hash_next (&hi, &key, &value)) { - key = strdup (key); - if (key == NULL) - goto finished; - value = strdup (value); - if (value == NULL) - goto finished; - if (!hash_set (config, key, value)) - goto finished; - key = NULL; - value = NULL; - } - - /* Override the system config */ - } else if (mode == USER_CONFIG_OVERRIDE) { - hash_free (config); - config = uconfig; - uconfig = NULL; - } - } - - gl.config = config; - config = NULL; - rv = CKR_OK; - - if (user_mode) - *user_mode = mode; - -finished: - hash_free (config); - hash_free (uconfig); - free (key); - free (value); - return rv; -} - -static CK_RV -load_registered_modules_unlocked (void) -{ - char *path; - int mode; - CK_RV rv; - - rv = load_config_files_unlocked (&mode); - if (rv != CKR_OK) - return rv; - - assert (gl.config); - assert (mode != USER_CONFIG_INVALID); - - /* Load each module from the main list */ - if (mode != USER_CONFIG_OVERRIDE) { - rv = load_modules_from_config_unlocked (P11_SYSTEM_MODULES); - if (rv != CKR_OK); - return rv; - } - - /* Load each module from the user list */ - if (mode != USER_CONFIG_NONE) { - path = expand_user_path (P11_USER_MODULES); - if (!path) - rv = CKR_GENERAL_ERROR; - else - rv = load_modules_from_config_unlocked (path); - free (path); - if (rv != CKR_OK); - return rv; - } - - return CKR_OK; -} - -static CK_RV -initialize_module_unlocked_reentrant (Module *module) -{ - CK_RV rv = CKR_OK; - - assert (module); - - /* - * Initialize first, so module doesn't get freed out from - * underneath us when the mutex is unlocked below. - */ - ++module->ref_count; - - if (!module->initialize_count) { - - _p11_unlock (); - - assert (module->funcs); - rv = module->funcs->C_Initialize (&module->init_args); - - _p11_lock (); - - /* - * Because we have the mutex unlocked above, two initializes could - * race. Therefore we need to take CKR_CRYPTOKI_ALREADY_INITIALIZED - * into account. - * - * We also need to take into account where in a race both calls return - * CKR_OK (which is not according to the spec but may happen, I mean we - * do it in this module, so it's not unimaginable). - */ - - if (rv == CKR_OK) - ++module->initialize_count; - else if (rv == CKR_CRYPTOKI_ALREADY_INITIALIZED) - rv = CKR_OK; - else - --module->ref_count; - } - - return rv; -} - -static void -reinitialize_after_fork (void) -{ - hash_iter_t it; - Module *module; - - /* WARNING: This function must be reentrant */ - debug ("forked"); - - _p11_lock (); - - if (gl.modules) { - hash_iterate (gl.modules, &it); - while (hash_next (&it, NULL, (void**)&module)) { - module->initialize_count = 0; - - /* WARNING: Reentrancy can occur here */ - initialize_module_unlocked_reentrant (module); - } - } - - _p11_unlock (); - - _p11_kit_proxy_after_fork (); -} - -static CK_RV -init_globals_unlocked (void) -{ - static int once = 0; - - if (!gl.modules) - gl.modules = hash_create (hash_direct_hash, hash_direct_equal, - NULL, free_module_unlocked); - if (!gl.modules) - return CKR_HOST_MEMORY; - - if (once) - return CKR_OK; - - pthread_atfork (NULL, NULL, reinitialize_after_fork); - once = 1; - - return CKR_OK; -} - -static void -free_modules_when_no_refs_unlocked (void) -{ - Module *module; - hash_iter_t it; - - /* Check if any modules have a ref count */ - hash_iterate (gl.modules, &it); - while (hash_next (&it, NULL, (void**)&module)) { - if (module->ref_count) - return; - } - - hash_free (gl.modules); - gl.modules = NULL; - hash_free (gl.config); - gl.config = NULL; -} - -static CK_RV -finalize_module_unlocked_reentrant (Module *module) -{ - assert (module); - - /* - * We leave module info around until all are finalized - * so we can encounter these zombie Module structures. - */ - if (module->ref_count == 0) - return CKR_ARGUMENTS_BAD; - - if (--module->ref_count > 0) - return CKR_OK; - - /* - * Becuase of the mutex unlock below, we temporarily increase - * the ref count. This prevents module from being freed out - * from ounder us. - */ - ++module->ref_count; - - while (module->initialize_count > 0) { - - _p11_unlock (); - - assert (module->funcs); - module->funcs->C_Finalize (NULL); - - _p11_lock (); - - if (module->initialize_count > 0) - --module->initialize_count; - } - - /* Match the increment above */ - --module->ref_count; - - free_modules_when_no_refs_unlocked (); - return CKR_OK; -} - -static Module* -find_module_for_name_unlocked (const char *name) -{ - Module *module; - hash_iter_t it; - - assert (name); - - hash_iterate (gl.modules, &it); - while (hash_next (&it, NULL, (void**)&module)) - if (module->ref_count && module->name && strcmp (name, module->name) == 0) - return module; - return NULL; -} - -CK_RV -_p11_kit_initialize_registered_unlocked_reentrant (void) -{ - Module *module; - hash_iter_t it; - CK_RV rv; - - rv = init_globals_unlocked (); - if (rv == CKR_OK) - rv = load_registered_modules_unlocked (); - if (rv == CKR_OK) { - hash_iterate (gl.modules, &it); - while (hash_next (&it, NULL, (void**)&module)) { - - /* Skip all modules that aren't registered */ - if (!module->name) - continue; - - rv = initialize_module_unlocked_reentrant (module); - - if (rv != CKR_OK) { - debug ("failed to initialize module: %s: %s", - module->name, p11_kit_strerror (rv)); - break; - } - } - } - - return rv; -} - -/** - * p11_kit_initialize_registered: - * - * Initialize all the registered PKCS\#11 modules. - * - * If this is the first time this function is called multiple times - * consecutively within a single process, then it merely increments an - * initialization reference count for each of these modules. - * - * Use p11_kit_finalize_registered() to finalize these registered modules once - * the caller is done with them. - * - * Returns: CKR_OK if the initialization succeeded, or an error code. - */ -CK_RV -p11_kit_initialize_registered (void) -{ - CK_RV rv; - - /* WARNING: This function must be reentrant */ - debug ("in"); - - _p11_lock (); - - /* WARNING: Reentrancy can occur here */ - rv = _p11_kit_initialize_registered_unlocked_reentrant (); - - _p11_unlock (); - - /* Cleanup any partial initialization */ - if (rv != CKR_OK) - p11_kit_finalize_registered (); - - debug ("out: %lu"); - return rv; -} - -CK_RV -_p11_kit_finalize_registered_unlocked_reentrant (void) -{ - Module *module; - hash_iter_t it; - Module **to_finalize; - int i, count; - - if (!gl.modules) - return CKR_CRYPTOKI_NOT_INITIALIZED; - - /* WARNING: This function must be reentrant */ - - to_finalize = calloc (hash_count (gl.modules), sizeof (Module*)); - if (!to_finalize) - return CKR_HOST_MEMORY; - - count = 0; - hash_iterate (gl.modules, &it); - while (hash_next (&it, NULL, (void**)&module)) { - - /* Skip all modules that aren't registered */ - if (module->name) - to_finalize[count++] = module; - } - - debug ("finalizing %d modules", count); - - for (i = 0; i < count; ++i) { - /* WARNING: Reentrant calls can occur here */ - finalize_module_unlocked_reentrant (to_finalize[i]); - } - - free (to_finalize); - return CKR_OK; -} - -/** - * p11_kit_finalize_registered: - * - * Finalize all the registered PKCS\#11 modules. These should have been - * initialized with p11_kit_initialize_registered(). - * - * If p11_kit_initialize_registered() has been called more than once in this - * process, then this function must be called the same number of times before - * actual finalization will occur. - * - * Returns: CKR_OK if the finalization succeeded, or an error code. - */ - -CK_RV -p11_kit_finalize_registered (void) -{ - CK_RV rv; - - /* WARNING: This function must be reentrant */ - debug ("in"); - - _p11_lock (); - - /* WARNING: Reentrant calls can occur here */ - rv = _p11_kit_finalize_registered_unlocked_reentrant (); - - _p11_unlock (); - - debug ("out: %lu", rv); - return rv; -} - -CK_FUNCTION_LIST_PTR_PTR -_p11_kit_registered_modules_unlocked (void) -{ - CK_FUNCTION_LIST_PTR_PTR result; - Module *module; - hash_iter_t it; - int i = 0; - - result = calloc (hash_count (gl.modules) + 1, sizeof (CK_FUNCTION_LIST_PTR)); - if (result) { - hash_iterate (gl.modules, &it); - while (hash_next (&it, NULL, (void**)&module)) { - if (module->ref_count && module->name) - result[i++] = module->funcs; - } - } - - return result; -} - -/** - * p11_kit_registered_modules: - * - * Get a list of all the registered PKCS\#11 modules. This list will be valid - * once the p11_kit_initialize_registered() function has been called. - * - * The returned value is a NULL terminated array of - * CK_FUNCTION_LIST_PTR pointers. - * - * Returns: A list of all the registered modules. Use the free() function to - * free the list. - */ -CK_FUNCTION_LIST_PTR_PTR -p11_kit_registered_modules (void) -{ - CK_FUNCTION_LIST_PTR_PTR result; - - _p11_lock (); - - result = _p11_kit_registered_modules_unlocked (); - - _p11_unlock (); - - return result; -} - -/** - * p11_kit_registered_module_to_name: - * @funcs: pointer to a registered module - * - * Get the name of a registered PKCS\#11 module. - * - * You can use p11_kit_registered_modules() to get a list of all the registered - * modules. This name is specified by the registered module configuration. - * - * Returns: A newly allocated string containing the module name, or - * NULL if no such registered module exists. Use free() to - * free this string. - */ -char* -p11_kit_registered_module_to_name (CK_FUNCTION_LIST_PTR funcs) -{ - Module *module; - char *name = NULL; - - if (!funcs) - return NULL; - - _p11_lock (); - - module = gl.modules ? hash_get (gl.modules, funcs) : NULL; - if (module && module->name) - name = strdup (module->name); - - _p11_unlock (); - - return name; -} - -/** - * p11_kit_registered_name_to_module: - * @name: name of a registered module - * - * Lookup a registered PKCS\#11 module by its name. This name is specified by - * the registered module configuration. - * - * Returns: a pointer to a PKCS\#11 module, or NULL if this name was - * not found. - */ -CK_FUNCTION_LIST_PTR -p11_kit_registered_name_to_module (const char *name) -{ - CK_FUNCTION_LIST_PTR funcs = NULL; - Module *module; - - _p11_lock (); - - if (gl.modules) { - module = find_module_for_name_unlocked (name); - if (module) - funcs = module->funcs; - } - - _p11_unlock (); - - return funcs; -} - -/** - * p11_kit_registered_option: - * @funcs: a pointer to a registered module - * @field: the name of the option to lookup. - * - * Lookup a configured option for a registered PKCS\#11 module. If a - * NULL funcs argument is specified, then this will lookup - * the configuration option in the global config file. - * - * Returns: A newly allocated string containing the option value, or - * NULL if the registered module or the option were not found. - * Use free() to free the returned string. - */ -char* -p11_kit_registered_option (CK_FUNCTION_LIST_PTR funcs, const char *field) -{ - Module *module = NULL; - char *option = NULL; - hash_t *config = NULL; - - if (!field) - return NULL; - - _p11_lock (); - - if (funcs == NULL) { - config = gl.config; - - } else { - module = gl.modules ? hash_get (gl.modules, funcs) : NULL; - if (module) - config = module->config; - } - - if (config) { - option = hash_get (config, field); - if (option) - option = strdup (option); - } - - _p11_unlock (); - - return option; -} - -/** - * p11_kit_initialize_module: - * @funcs: loaded module to initialize. - * - * Initialize an arbitrary PKCS\#11 module. Normally using the - * p11_kit_initialize_registered() is preferred. - * - * Using this function to initialize modules allows coordination between - * multiple users of the same module in a single process. It should be called - * on modules that have been loaded (with dlopen() for example) but not yet - * initialized. The caller should not yet have called the module's - * C_Initialize method. This function will call - * C_Initialize as necessary. - * - * Subsequent calls to this function for the same module will result in an - * initialization count being incremented for the module. It is safe (although - * usually unnecessary) to use this function on registered modules. - * - * The module must be finalized with p11_kit_finalize_module() instead of - * calling its C_Finalize method directly. - * - * This function does not accept a CK_C_INITIALIZE_ARGS argument. - * Custom initialization arguments cannot be supported when multiple consumers - * load the same module. - * - * Returns: CKR_OK if the initialization was successful. - */ -CK_RV -p11_kit_initialize_module (CK_FUNCTION_LIST_PTR funcs) -{ - Module *module; - Module *allocated = NULL; - CK_RV rv = CKR_OK; - - /* WARNING: This function must be reentrant for the same arguments */ - debug ("in"); - - _p11_lock (); - - rv = init_globals_unlocked (); - if (rv == CKR_OK) { - - module = hash_get (gl.modules, funcs); - if (module == NULL) { - debug ("allocating new module"); - allocated = module = alloc_module_unlocked (); - module->funcs = funcs; - } - - /* WARNING: Reentrancy can occur here */ - rv = initialize_module_unlocked_reentrant (module); - - /* If this was newly allocated, add it to the list */ - if (rv == CKR_OK && allocated) { - hash_set (gl.modules, allocated->funcs, allocated); - allocated = NULL; - } - - free (allocated); - } - - _p11_unlock (); - - debug ("out: %lu", rv); - return rv; -} - -/** - * p11_kit_finalize_module: - * @funcs: loaded module to finalize. - * - * Finalize an arbitrary PKCS\#11 module. The module must have been initialized - * using p11_kit_initialize_module(). In most cases callers will want to use - * p11_kit_finalize_registered() instead of this function. - * - * Using this function to finalize modules allows coordination between - * multiple users of the same module in a single process. The caller should - * call the module's C_Finalize method. This function will call - * C_Finalize as necessary. - * - * If the module was initialized more than once, then this function will - * decrement an initialization count for the module. When the count reaches zero - * the module will be truly finalized. It is safe (although usually unnecessary) - * to use this function on registered modules if (and only if) they were - * initialized using p11_kit_initialize_module() for some reason. - * - * Returns: CKR_OK if the finalization was successful. - */ -CK_RV -p11_kit_finalize_module (CK_FUNCTION_LIST_PTR funcs) -{ - Module *module; - CK_RV rv = CKR_OK; - - /* WARNING: This function must be reentrant for the same arguments */ - debug ("in"); - - _p11_lock (); - - module = gl.modules ? hash_get (gl.modules, funcs) : NULL; - if (module == NULL) { - debug ("module not found"); - rv = CKR_ARGUMENTS_BAD; - } else { - /* WARNING: Rentrancy can occur here */ - rv = finalize_module_unlocked_reentrant (module); - } - - _p11_unlock (); - - debug ("out: %lu", rv); - return rv; -} diff --git a/p11-kit/p11-kit-messages.c b/p11-kit/p11-kit-messages.c deleted file mode 100644 index bfc637c..0000000 --- a/p11-kit/p11-kit-messages.c +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (C) 2011 Collabora Ltd. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * 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. - * * The names of contributors to this software may not be - * used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 - * COPYRIGHT OWNER 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. - * - * Author: Stef Walter - */ - -#include "config.h" - -#include "pkcs11.h" -#include "p11-kit.h" - -/** - * SECTION:p11-kit-util - * @title: Utilities - * @short_description: PKCS\#11 utilities - * - * Utility functions for working with PKCS\#11. - */ - -#ifdef ENABLE_NLS -#include -#define _(x) dgettext(PACKAGE_NAME, x) -#else -#define _(x) x -#endif - -/** - * p11_kit_strerror: - * @rv: The code to get a message for. - * - * Get a message for a PKCS\#11 return value or error code. Do not - * pass CKR_OK or other such non errors to this function. - * - * Returns: The user readable and localized message. - **/ -const char* -p11_kit_strerror (CK_RV rv) -{ - switch (rv) { - - /* These are not really errors, or not current */ - case CKR_OK: - case CKR_NO_EVENT: - case CKR_FUNCTION_NOT_PARALLEL: - case CKR_SESSION_PARALLEL_NOT_SUPPORTED: - return ""; - - case CKR_CANCEL: - case CKR_FUNCTION_CANCELED: - return _("The operation was cancelled"); - - case CKR_HOST_MEMORY: - return _("Insufficient memory available"); - case CKR_SLOT_ID_INVALID: - return _("The specified slot ID is not valid"); - case CKR_GENERAL_ERROR: - return _("Internal error"); - case CKR_FUNCTION_FAILED: - return _("The operation failed"); - case CKR_ARGUMENTS_BAD: - return _("Invalid arguments"); - case CKR_NEED_TO_CREATE_THREADS: - return _("The module cannot create needed threads"); - case CKR_CANT_LOCK: - return _("The module cannot lock data properly"); - case CKR_ATTRIBUTE_READ_ONLY: - return _("The field is read-only"); - case CKR_ATTRIBUTE_SENSITIVE: - return _("The field is sensitive and cannot be revealed"); - case CKR_ATTRIBUTE_TYPE_INVALID: - return _("The field is invalid or does not exist"); - case CKR_ATTRIBUTE_VALUE_INVALID: - return _("Invalid value for field"); - case CKR_DATA_INVALID: - return _("The data is not valid or unrecognized"); - case CKR_DATA_LEN_RANGE: - return _("The data is too long"); - case CKR_DEVICE_ERROR: - return _("An error occurred on the device"); - case CKR_DEVICE_MEMORY: - return _("Insufficient memory available on the device"); - case CKR_DEVICE_REMOVED: - return _("The device was removed or unplugged"); - case CKR_ENCRYPTED_DATA_INVALID: - return _("The encrypted data is not valid or unrecognized"); - case CKR_ENCRYPTED_DATA_LEN_RANGE: - return _("The encrypted data is too long"); - case CKR_FUNCTION_NOT_SUPPORTED: - return _("This operation is not supported"); - case CKR_KEY_HANDLE_INVALID: - return _("The key is missing or invalid"); - case CKR_KEY_SIZE_RANGE: - return _("The key is the wrong size"); - case CKR_KEY_TYPE_INCONSISTENT: - return _("The key is of the wrong type"); - case CKR_KEY_NOT_NEEDED: - return _("No key is needed"); - case CKR_KEY_CHANGED: - return _("The key is different than before"); - case CKR_KEY_NEEDED: - return _("A key is needed"); - case CKR_KEY_INDIGESTIBLE: - return _("Cannot include the key in the digest"); - case CKR_KEY_FUNCTION_NOT_PERMITTED: - return _("This operation cannot be done with this key"); - case CKR_KEY_NOT_WRAPPABLE: - return _("The key cannot be wrapped"); - case CKR_KEY_UNEXTRACTABLE: - return _("Cannot export this key"); - case CKR_MECHANISM_INVALID: - return _("The crypto mechanism is invalid or unrecognized"); - case CKR_MECHANISM_PARAM_INVALID: - return _("The crypto mechanism has an invalid argument"); - case CKR_OBJECT_HANDLE_INVALID: - return _("The object is missing or invalid"); - case CKR_OPERATION_ACTIVE: - return _("Another operation is already taking place"); - case CKR_OPERATION_NOT_INITIALIZED: - return _("No operation is taking place"); - case CKR_PIN_INCORRECT: - return _("The password or PIN is incorrect"); - case CKR_PIN_INVALID: - return _("The password or PIN is invalid"); - case CKR_PIN_LEN_RANGE: - return _("The password or PIN is of an invalid length"); - case CKR_PIN_EXPIRED: - return _("The password or PIN has expired"); - case CKR_PIN_LOCKED: - return _("The password or PIN is locked"); - case CKR_SESSION_CLOSED: - return _("The session is closed"); - case CKR_SESSION_COUNT: - return _("Too many sessions are active"); - case CKR_SESSION_HANDLE_INVALID: - return _("The session is invalid"); - case CKR_SESSION_READ_ONLY: - return _("The session is read-only"); - case CKR_SESSION_EXISTS: - return _("An open session exists"); - case CKR_SESSION_READ_ONLY_EXISTS: - return _("A read-only session exists"); - case CKR_SESSION_READ_WRITE_SO_EXISTS: - return _("An administrator session exists"); - case CKR_SIGNATURE_INVALID: - return _("The signature is bad or corrupted"); - case CKR_SIGNATURE_LEN_RANGE: - return _("The signature is unrecognized or corrupted"); - case CKR_TEMPLATE_INCOMPLETE: - return _("Certain required fields are missing"); - case CKR_TEMPLATE_INCONSISTENT: - return _("Certain fields have invalid values"); - case CKR_TOKEN_NOT_PRESENT: - return _("The device is not present or unplugged"); - case CKR_TOKEN_NOT_RECOGNIZED: - return _("The device is invalid or unrecognizable"); - case CKR_TOKEN_WRITE_PROTECTED: - return _("The device is write protected"); - case CKR_UNWRAPPING_KEY_HANDLE_INVALID: - return _("Cannot import because the key is invalid"); - case CKR_UNWRAPPING_KEY_SIZE_RANGE: - return _("Cannot import because the key is of the wrong size"); - case CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: - return _("Cannot import because the key is of the wrong type"); - case CKR_USER_ALREADY_LOGGED_IN: - return _("You are already logged in"); - case CKR_USER_NOT_LOGGED_IN: - return _("No user has logged in"); - case CKR_USER_PIN_NOT_INITIALIZED: - return _("The user's password or PIN is not set"); - case CKR_USER_TYPE_INVALID: - return _("The user is of an invalid type"); - case CKR_USER_ANOTHER_ALREADY_LOGGED_IN: - return _("Another user is already logged in"); - case CKR_USER_TOO_MANY_TYPES: - return _("Too many users of different types are logged in"); - case CKR_WRAPPED_KEY_INVALID: - return _("Cannot import an invalid key"); - case CKR_WRAPPED_KEY_LEN_RANGE: - return _("Cannot import a key of the wrong size"); - case CKR_WRAPPING_KEY_HANDLE_INVALID: - return _("Cannot export because the key is invalid"); - case CKR_WRAPPING_KEY_SIZE_RANGE: - return _("Cannot export because the key is of the wrong size"); - case CKR_WRAPPING_KEY_TYPE_INCONSISTENT: - return _("Cannot export because the key is of the wrong type"); - case CKR_RANDOM_SEED_NOT_SUPPORTED: - return _("Unable to initialize the random number generator"); - case CKR_RANDOM_NO_RNG: - return _("No random number generator available"); - case CKR_DOMAIN_PARAMS_INVALID: - return _("The crypto mechanism has an invalid parameter"); - case CKR_BUFFER_TOO_SMALL: - return _("Not enough space to store the result"); - case CKR_SAVED_STATE_INVALID: - return _("The saved state is invalid"); - case CKR_INFORMATION_SENSITIVE: - return _("The information is sensitive and cannot be revealed"); - case CKR_STATE_UNSAVEABLE: - return _("The state cannot be saved"); - case CKR_CRYPTOKI_NOT_INITIALIZED: - return _("The module has not been initialized"); - case CKR_CRYPTOKI_ALREADY_INITIALIZED: - return _("The module has already been initialized"); - case CKR_MUTEX_BAD: - return _("Cannot lock data"); - case CKR_MUTEX_NOT_LOCKED: - return _("The data cannot be locked"); - case CKR_FUNCTION_REJECTED: - return _("The signature request was rejected by the user"); - - default: - return _("Unknown error"); - } -} diff --git a/p11-kit/p11-kit-private.h b/p11-kit/p11-kit-private.h deleted file mode 100644 index 56d5394..0000000 --- a/p11-kit/p11-kit-private.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2011 Collabora Ltd. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * 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. - * * The names of contributors to this software may not be - * used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 - * COPYRIGHT OWNER 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. - * - * Author: Stef Walter - */ - -#ifndef __P11_KIT_PRIVATE_H__ -#define __P11_KIT_PRIVATE_H__ - -extern pthread_mutex_t _p11_mutex; - -#define _p11_lock() pthread_mutex_lock (&_p11_mutex); - -#define _p11_unlock() pthread_mutex_unlock (&_p11_mutex); - -CK_FUNCTION_LIST_PTR_PTR _p11_kit_registered_modules_unlocked (void); - -CK_RV _p11_kit_initialize_registered_unlocked_reentrant (void); - -CK_RV _p11_kit_finalize_registered_unlocked_reentrant (void); - -void _p11_kit_proxy_after_fork (void); - -#endif /* __P11_KIT_PRIVATE_H__ */ diff --git a/p11-kit/p11-kit-proxy.c b/p11-kit/p11-kit-proxy.c deleted file mode 100644 index e8c4015..0000000 --- a/p11-kit/p11-kit-proxy.c +++ /dev/null @@ -1,1382 +0,0 @@ -/* - * Copyright (C) 2008 Stefan Walter - * Copyright (C) 2011 Collabora Ltd. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * 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. - * * The names of contributors to this software may not be - * used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 - * COPYRIGHT OWNER 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. - * - * Author: Stef Walter - */ - -#include "config.h" - -#include "hash.h" -#include "pkcs11.h" -#include "p11-kit.h" -#include "p11-kit-private.h" -#include "util.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* Start wrap slots slightly higher for testing */ -#define MAPPING_OFFSET 0x10 -#define FIRST_HANDLE 0x10 - -typedef struct _Mapping { - CK_SLOT_ID wrap_slot; - CK_SLOT_ID real_slot; - CK_FUNCTION_LIST_PTR funcs; -} Mapping; - -typedef struct _Session { - CK_SESSION_HANDLE wrap_session; - CK_SESSION_HANDLE real_session; - CK_SLOT_ID wrap_slot; -} Session; - -/* Forward declaration */ -static CK_FUNCTION_LIST proxy_function_list; - -/* - * Shared data between threads, protected by the mutex, a structure so - * we can audit thread safety easier. - */ -static struct _Shared { - Mapping *mappings; - unsigned int n_mappings; - int mappings_refs; - hash_t *sessions; - CK_ULONG last_handle; -} gl = { NULL, 0, 0, NULL, FIRST_HANDLE }; - -#define MANUFACTURER_ID "PKCS#11 Kit " -#define LIBRARY_DESCRIPTION "PKCS#11 Kit Proxy Module " -#define LIBRARY_VERSION_MAJOR 1 -#define LIBRARY_VERSION_MINOR 1 - -/* ----------------------------------------------------------------------------- - * PKCS#11 PROXY MODULE - */ - -static CK_RV -map_slot_unlocked (CK_SLOT_ID slot, Mapping *mapping) -{ - assert (mapping); - - if (slot < MAPPING_OFFSET) - return CKR_SLOT_ID_INVALID; - slot -= MAPPING_OFFSET; - - if (slot > gl.n_mappings) { - return CKR_SLOT_ID_INVALID; - } else { - assert (gl.mappings); - memcpy (mapping, &gl.mappings[slot], sizeof (Mapping)); - return CKR_OK; - } -} - -static CK_RV -map_slot_to_real (CK_SLOT_ID_PTR slot, Mapping *mapping) -{ - CK_RV rv; - - assert (mapping); - - _p11_lock (); - - if (!gl.mappings) - rv = CKR_CRYPTOKI_NOT_INITIALIZED; - else - rv = map_slot_unlocked (*slot, mapping); - if (rv == CKR_OK) - *slot = mapping->real_slot; - - _p11_unlock (); - - return rv; -} - -static CK_RV -map_session_to_real (CK_SESSION_HANDLE_PTR handle, Mapping *mapping, Session *session) -{ - CK_RV rv = CKR_OK; - Session *sess; - - assert (handle); - assert (mapping); - - _p11_lock (); - - if (!gl.sessions) { - rv = CKR_CRYPTOKI_NOT_INITIALIZED; - } else { - assert (gl.sessions); - sess = hash_get (gl.sessions, &handle); - if (sess != NULL) { - *handle = sess->real_session; - rv = map_slot_unlocked (sess->wrap_slot, mapping); - if (session != NULL) - memcpy (session, sess, sizeof (Session)); - } else { - rv = CKR_SESSION_HANDLE_INVALID; - } - } - - _p11_unlock (); - - return rv; -} - -static void -finalize_mappings_unlocked (void) -{ - assert (gl.mappings_refs); - - if (--gl.mappings_refs) - return; - - /* No more mappings */ - free (gl.mappings); - gl.mappings = NULL; - gl.n_mappings = 0; - - /* no more sessions */ - hash_free (gl.sessions); - gl.sessions = NULL; -} - -void -_p11_kit_proxy_after_fork (void) -{ - /* - * After a fork the callers are supposed to call C_Initialize and all. - * In addition the underlying libraries may change their state so free - * up any mappings and all - */ - - _p11_lock (); - - gl.mappings_refs = 1; - finalize_mappings_unlocked (); - assert (!gl.mappings); - - _p11_unlock (); -} - -static CK_RV -proxy_C_Finalize (CK_VOID_PTR reserved) -{ - CK_RV rv; - - /* WARNING: This function must be reentrant */ - - if (reserved) - return CKR_ARGUMENTS_BAD; - - _p11_lock (); - - /* WARNING: Reentrancy can occur here */ - rv = _p11_kit_finalize_registered_unlocked_reentrant (); - - /* - * If modules are all gone, then this was the last - * finalize, so cleanup our mappings - */ - if (gl.mappings_refs) - finalize_mappings_unlocked (); - - _p11_unlock (); - - return rv; -} - -static CK_RV -initialize_mappings_unlocked_reentrant (void) -{ - CK_FUNCTION_LIST_PTR *funcss, *f; - CK_FUNCTION_LIST_PTR funcs; - Mapping *mappings = NULL; - int n_mappings = 0; - CK_SLOT_ID_PTR slots; - CK_ULONG i, count; - CK_RV rv; - - assert (!gl.mappings); - - funcss = _p11_kit_registered_modules_unlocked (); - for (f = funcss; *f; ++f) { - funcs = *f; - - assert (funcs); - slots = NULL; - - _p11_unlock (); - - /* Ask module for its slots */ - rv = (funcs->C_GetSlotList) (FALSE, NULL, &count); - if (rv == CKR_OK && count) { - slots = calloc (sizeof (CK_SLOT_ID), count); - if (!slots) - rv = CKR_HOST_MEMORY; - else - rv = (funcs->C_GetSlotList) (FALSE, slots, &count); - } - - _p11_lock (); - - if (rv != CKR_OK) { - free (slots); - break; - } - - mappings = xrealloc (mappings, sizeof (Mapping) * (n_mappings + count)); - if (!mappings) { - free (slots); - rv = CKR_HOST_MEMORY; - break; - } - - /* And now add a mapping for each of those slots */ - for (i = 0; i < count; ++i) { - mappings[n_mappings].funcs = funcs; - mappings[n_mappings].wrap_slot = n_mappings + MAPPING_OFFSET; - mappings[n_mappings].real_slot = slots[i]; - ++n_mappings; - } - - free (slots); - } - - /* Another thread raced us here due to above reentrancy */ - if (gl.mappings) { - free (mappings); - return CKR_OK; - } - - assert (!gl.sessions); - gl.sessions = hash_create (hash_ulongptr_hash, hash_ulongptr_equal, NULL, free); - ++gl.mappings_refs; - - /* Any cleanup necessary for failure will happen at caller */ - return rv; -} - -static CK_RV -proxy_C_Initialize (CK_VOID_PTR init_args) -{ - CK_RV rv; - - /* WARNING: This function must be reentrant */ - - _p11_lock (); - - /* WARNING: Reentrancy can occur here */ - rv = _p11_kit_initialize_registered_unlocked_reentrant (); - - /* WARNING: Reentrancy can occur here */ - if (rv == CKR_OK && !gl.mappings_refs == 0) - rv = initialize_mappings_unlocked_reentrant (); - - _p11_unlock (); - - if (rv != CKR_OK) - proxy_C_Finalize (NULL); - - return rv; -} - -static CK_RV -proxy_C_GetInfo (CK_INFO_PTR info) -{ - CK_RV rv = CKR_OK; - - if (info == NULL) - return CKR_ARGUMENTS_BAD; - - _p11_lock (); - - if (!gl.mappings) - rv = CKR_CRYPTOKI_NOT_INITIALIZED; - - _p11_unlock (); - - if (rv != CKR_OK) - return rv; - - info->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR; - info->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR; - info->libraryVersion.major = LIBRARY_VERSION_MAJOR; - info->libraryVersion.minor = LIBRARY_VERSION_MINOR; - info->flags = 0; - strncpy ((char*)info->manufacturerID, MANUFACTURER_ID, 32); - strncpy ((char*)info->libraryDescription, LIBRARY_DESCRIPTION, 32); - return CKR_OK; -} - -static CK_RV -proxy_C_GetFunctionList (CK_FUNCTION_LIST_PTR_PTR list) -{ - /* Can be called before C_Initialize */ - - if (!list) - return CKR_ARGUMENTS_BAD; - *list = &proxy_function_list; - return CKR_OK; -} - -static CK_RV -proxy_C_GetSlotList (CK_BBOOL token_present, CK_SLOT_ID_PTR slot_list, - CK_ULONG_PTR count) -{ - CK_SLOT_INFO info; - Mapping *mapping; - CK_ULONG index; - CK_RV rv = CKR_OK; - int i; - - if (!count) - return CKR_ARGUMENTS_BAD; - - _p11_lock (); - - if (!gl.mappings) { - rv = CKR_CRYPTOKI_NOT_INITIALIZED; - } else { - index = 0; - - /* Go through and build up a map */ - for (i = 0; i < gl.n_mappings; ++i) { - mapping = &gl.mappings[i]; - - /* Skip ones without a token if requested */ - if (token_present) { - rv = (mapping->funcs->C_GetSlotInfo) (mapping->real_slot, &info); - if (rv != CKR_OK) - break; - if (!(info.flags & CKF_TOKEN_PRESENT)) - continue; - } - - /* Fill in the slot if we can */ - if (slot_list && *count > index) - slot_list[index] = mapping->wrap_slot; - - ++index; - } - - if (slot_list && *count < index) - rv = CKR_BUFFER_TOO_SMALL; - - *count = index; - } - - _p11_unlock (); - - return rv; -} - -static CK_RV -proxy_C_GetSlotInfo (CK_SLOT_ID id, CK_SLOT_INFO_PTR info) -{ - Mapping map; - CK_RV rv; - - rv = map_slot_to_real (&id, &map); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GetSlotInfo) (id, info); -} - -static CK_RV -proxy_C_GetTokenInfo (CK_SLOT_ID id, CK_TOKEN_INFO_PTR info) -{ - Mapping map; - CK_RV rv; - - rv = map_slot_to_real (&id, &map); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GetTokenInfo) (id, info); -} - -static CK_RV -proxy_C_GetMechanismList (CK_SLOT_ID id, CK_MECHANISM_TYPE_PTR mechanism_list, - CK_ULONG_PTR count) -{ - Mapping map; - CK_RV rv; - - rv = map_slot_to_real (&id, &map); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GetMechanismList) (id, mechanism_list, count); -} - -static CK_RV -proxy_C_GetMechanismInfo (CK_SLOT_ID id, CK_MECHANISM_TYPE type, - CK_MECHANISM_INFO_PTR info) -{ - Mapping map; - CK_RV rv; - - rv = map_slot_to_real (&id, &map); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GetMechanismInfo) (id, type, info); -} - -static CK_RV -proxy_C_InitToken (CK_SLOT_ID id, CK_UTF8CHAR_PTR pin, CK_ULONG pin_len, CK_UTF8CHAR_PTR label) -{ - Mapping map; - CK_RV rv; - - rv = map_slot_to_real (&id, &map); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_InitToken) (id, pin, pin_len, label); -} - -static CK_RV -proxy_C_WaitForSlotEvent (CK_FLAGS flags, CK_SLOT_ID_PTR slot, CK_VOID_PTR reserved) -{ - return CKR_FUNCTION_NOT_SUPPORTED; -} - -static CK_RV -proxy_C_OpenSession (CK_SLOT_ID id, CK_FLAGS flags, CK_VOID_PTR user_data, - CK_NOTIFY callback, CK_SESSION_HANDLE_PTR handle) -{ - Session *sess; - Mapping map; - CK_RV rv; - - if (handle == NULL) - return CKR_ARGUMENTS_BAD; - - rv = map_slot_to_real (&id, &map); - if (rv != CKR_OK) - return rv; - - rv = (map.funcs->C_OpenSession) (id, flags, user_data, callback, handle); - - if (rv == CKR_OK) { - _p11_lock (); - - if (!gl.sessions) { - /* - * The underlying module should have returned an error, so this - * code should never be reached with properly behaving modules. - * That's why we don't cleanup and close the newly opened session here - * or anything like that. - */ - rv = CKR_CRYPTOKI_NOT_INITIALIZED; - - } else { - sess = calloc (1, sizeof (Session)); - sess->wrap_slot = map.wrap_slot; - sess->real_session = *handle; - sess->wrap_session = ++gl.last_handle; /* TODO: Handle wrapping, and then collisions */ - hash_set (gl.sessions, &sess->wrap_session, sess); - *handle = sess->wrap_session; - } - - _p11_unlock (); - } - - return rv; -} - -static CK_RV -proxy_C_CloseSession (CK_SESSION_HANDLE handle) -{ - CK_SESSION_HANDLE key; - Mapping map; - CK_RV rv; - - key = handle; - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - rv = (map.funcs->C_CloseSession) (handle); - - if (rv == CKR_OK) { - _p11_lock (); - - if (gl.sessions) - hash_remove (gl.sessions, &key); - - _p11_unlock (); - } - - return rv; -} - -static CK_RV -proxy_C_CloseAllSessions (CK_SLOT_ID id) -{ - CK_SESSION_HANDLE_PTR to_close; - CK_RV rv = CKR_OK; - Session *sess; - CK_ULONG i, count = 0; - hash_iter_t iter; - - _p11_lock (); - - if (!gl.sessions) { - rv = CKR_CRYPTOKI_NOT_INITIALIZED; - } else { - to_close = calloc (sizeof (CK_SESSION_HANDLE), hash_count (gl.sessions)); - if (!to_close) { - rv = CKR_HOST_MEMORY; - } else { - hash_iterate (gl.sessions, &iter); - count = 0; - while (hash_next (&iter, NULL, (void**)&sess)) { - if (sess->wrap_slot == id && to_close) - to_close[count++] = sess->wrap_session; - } - } - } - - _p11_unlock (); - - if (rv != CKR_OK) - return rv; - - for (i = 0; i < count; ++i) - proxy_C_CloseSession (to_close[i]); - - free (to_close); - return CKR_OK; -} - -static CK_RV -proxy_C_GetFunctionStatus (CK_SESSION_HANDLE handle) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GetFunctionStatus) (handle); -} - -static CK_RV -proxy_C_CancelFunction (CK_SESSION_HANDLE handle) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_CancelFunction) (handle); -} - -static CK_RV -proxy_C_GetSessionInfo (CK_SESSION_HANDLE handle, CK_SESSION_INFO_PTR info) -{ - Mapping map; - CK_RV rv; - - if (info == NULL) - return CKR_ARGUMENTS_BAD; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - - rv = (map.funcs->C_GetSessionInfo) (handle, info); - if (rv == CKR_OK) - info->slotID = map.wrap_slot; - - return rv; -} - -static CK_RV -proxy_C_InitPIN (CK_SESSION_HANDLE handle, CK_UTF8CHAR_PTR pin, CK_ULONG pin_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - - return (map.funcs->C_InitPIN) (handle, pin, pin_len); -} - -static CK_RV -proxy_C_SetPIN (CK_SESSION_HANDLE handle, CK_UTF8CHAR_PTR old_pin, CK_ULONG old_pin_len, - CK_UTF8CHAR_PTR new_pin, CK_ULONG new_pin_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - - return (map.funcs->C_SetPIN) (handle, old_pin, old_pin_len, new_pin, new_pin_len); -} - -static CK_RV -proxy_C_GetOperationState (CK_SESSION_HANDLE handle, CK_BYTE_PTR operation_state, CK_ULONG_PTR operation_state_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GetOperationState) (handle, operation_state, operation_state_len); -} - -static CK_RV -proxy_C_SetOperationState (CK_SESSION_HANDLE handle, CK_BYTE_PTR operation_state, - CK_ULONG operation_state_len, CK_OBJECT_HANDLE encryption_key, - CK_OBJECT_HANDLE authentication_key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_SetOperationState) (handle, operation_state, operation_state_len, encryption_key, authentication_key); -} - -static CK_RV -proxy_C_Login (CK_SESSION_HANDLE handle, CK_USER_TYPE user_type, - CK_UTF8CHAR_PTR pin, CK_ULONG pin_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - - return (map.funcs->C_Login) (handle, user_type, pin, pin_len); -} - -static CK_RV -proxy_C_Logout (CK_SESSION_HANDLE handle) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_Logout) (handle); -} - -static CK_RV -proxy_C_CreateObject (CK_SESSION_HANDLE handle, CK_ATTRIBUTE_PTR template, - CK_ULONG count, CK_OBJECT_HANDLE_PTR new_object) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - - return (map.funcs->C_CreateObject) (handle, template, count, new_object); -} - -static CK_RV -proxy_C_CopyObject (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object, - CK_ATTRIBUTE_PTR template, CK_ULONG count, - CK_OBJECT_HANDLE_PTR new_object) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_CopyObject) (handle, object, template, count, new_object); -} - -static CK_RV -proxy_C_DestroyObject (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DestroyObject) (handle, object); -} - -static CK_RV -proxy_C_GetObjectSize (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object, - CK_ULONG_PTR size) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GetObjectSize) (handle, object, size); -} - -static CK_RV -proxy_C_GetAttributeValue (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object, - CK_ATTRIBUTE_PTR template, CK_ULONG count) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GetAttributeValue) (handle, object, template, count); -} - -static CK_RV -proxy_C_SetAttributeValue (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object, - CK_ATTRIBUTE_PTR template, CK_ULONG count) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_SetAttributeValue) (handle, object, template, count); -} - -static CK_RV -proxy_C_FindObjectsInit (CK_SESSION_HANDLE handle, CK_ATTRIBUTE_PTR template, - CK_ULONG count) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_FindObjectsInit) (handle, template, count); -} - -static CK_RV -proxy_C_FindObjects (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE_PTR objects, - CK_ULONG max_count, CK_ULONG_PTR count) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_FindObjects) (handle, objects, max_count, count); -} - -static CK_RV -proxy_C_FindObjectsFinal (CK_SESSION_HANDLE handle) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_FindObjectsFinal) (handle); -} - -static CK_RV -proxy_C_EncryptInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_OBJECT_HANDLE key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_EncryptInit) (handle, mechanism, key); -} - -static CK_RV -proxy_C_Encrypt (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, - CK_BYTE_PTR encrypted_data, CK_ULONG_PTR encrypted_data_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_Encrypt) (handle, data, data_len, encrypted_data, encrypted_data_len); -} - -static CK_RV -proxy_C_EncryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, - CK_ULONG part_len, CK_BYTE_PTR encrypted_part, - CK_ULONG_PTR encrypted_part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_EncryptUpdate) (handle, part, part_len, encrypted_part, encrypted_part_len); -} - -static CK_RV -proxy_C_EncryptFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR last_part, - CK_ULONG_PTR last_part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_EncryptFinal) (handle, last_part, last_part_len); -} - -static CK_RV -proxy_C_DecryptInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_OBJECT_HANDLE key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DecryptInit) (handle, mechanism, key); -} - -static CK_RV -proxy_C_Decrypt (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_data, - CK_ULONG enc_data_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_Decrypt) (handle, enc_data, enc_data_len, data, data_len); -} - -static CK_RV -proxy_C_DecryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_part, - CK_ULONG enc_part_len, CK_BYTE_PTR part, CK_ULONG_PTR part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DecryptUpdate) (handle, enc_part, enc_part_len, part, part_len); -} - -static CK_RV -proxy_C_DecryptFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR last_part, - CK_ULONG_PTR last_part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DecryptFinal) (handle, last_part, last_part_len); -} - -static CK_RV -proxy_C_DigestInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DigestInit) (handle, mechanism); -} - -static CK_RV -proxy_C_Digest (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, - CK_BYTE_PTR digest, CK_ULONG_PTR digest_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_Digest) (handle, data, data_len, digest, digest_len); -} - -static CK_RV -proxy_C_DigestUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, CK_ULONG part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DigestUpdate) (handle, part, part_len); -} - -static CK_RV -proxy_C_DigestKey (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DigestKey) (handle, key); -} - -static CK_RV -proxy_C_DigestFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR digest, - CK_ULONG_PTR digest_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DigestFinal) (handle, digest, digest_len); -} - -static CK_RV -proxy_C_SignInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_OBJECT_HANDLE key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_SignInit) (handle, mechanism, key); -} - -static CK_RV -proxy_C_Sign (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, - CK_BYTE_PTR signature, CK_ULONG_PTR signature_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_Sign) (handle, data, data_len, signature, signature_len); -} - -static CK_RV -proxy_C_SignUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, CK_ULONG part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_SignUpdate) (handle, part, part_len); -} - -static CK_RV -proxy_C_SignFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR signature, - CK_ULONG_PTR signature_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_SignFinal) (handle, signature, signature_len); -} - -static CK_RV -proxy_C_SignRecoverInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_OBJECT_HANDLE key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_SignRecoverInit) (handle, mechanism, key); -} - -static CK_RV -proxy_C_SignRecover (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, - CK_BYTE_PTR signature, CK_ULONG_PTR signature_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_SignRecover) (handle, data, data_len, signature, signature_len); -} - -static CK_RV -proxy_C_VerifyInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_OBJECT_HANDLE key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_VerifyInit) (handle, mechanism, key); -} - -static CK_RV -proxy_C_Verify (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, - CK_BYTE_PTR signature, CK_ULONG signature_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_Verify) (handle, data, data_len, signature, signature_len); -} - -static CK_RV -proxy_C_VerifyUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, CK_ULONG part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_VerifyUpdate) (handle, part, part_len); -} - -static CK_RV -proxy_C_VerifyFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR signature, - CK_ULONG signature_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_VerifyFinal) (handle, signature, signature_len); -} - -static CK_RV -proxy_C_VerifyRecoverInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_OBJECT_HANDLE key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_VerifyRecoverInit) (handle, mechanism, key); -} - -static CK_RV -proxy_C_VerifyRecover (CK_SESSION_HANDLE handle, CK_BYTE_PTR signature, - CK_ULONG signature_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_VerifyRecover) (handle, signature, signature_len, data, data_len); -} - -static CK_RV -proxy_C_DigestEncryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, - CK_ULONG part_len, CK_BYTE_PTR enc_part, - CK_ULONG_PTR enc_part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DigestEncryptUpdate) (handle, part, part_len, enc_part, enc_part_len); -} - -static CK_RV -proxy_C_DecryptDigestUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_part, - CK_ULONG enc_part_len, CK_BYTE_PTR part, - CK_ULONG_PTR part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DecryptDigestUpdate) (handle, enc_part, enc_part_len, part, part_len); -} - -static CK_RV -proxy_C_SignEncryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, - CK_ULONG part_len, CK_BYTE_PTR enc_part, - CK_ULONG_PTR enc_part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_SignEncryptUpdate) (handle, part, part_len, enc_part, enc_part_len); -} - -static CK_RV -proxy_C_DecryptVerifyUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_part, - CK_ULONG enc_part_len, CK_BYTE_PTR part, - CK_ULONG_PTR part_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DecryptVerifyUpdate) (handle, enc_part, enc_part_len, part, part_len); -} - -static CK_RV -proxy_C_GenerateKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_ATTRIBUTE_PTR template, CK_ULONG count, - CK_OBJECT_HANDLE_PTR key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GenerateKey) (handle, mechanism, template, count, key); -} - -static CK_RV -proxy_C_GenerateKeyPair (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_ATTRIBUTE_PTR pub_template, CK_ULONG pub_count, - CK_ATTRIBUTE_PTR priv_template, CK_ULONG priv_count, - CK_OBJECT_HANDLE_PTR pub_key, CK_OBJECT_HANDLE_PTR priv_key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GenerateKeyPair) (handle, mechanism, pub_template, pub_count, priv_template, priv_count, pub_key, priv_key); -} - -static CK_RV -proxy_C_WrapKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_OBJECT_HANDLE wrapping_key, CK_OBJECT_HANDLE key, - CK_BYTE_PTR wrapped_key, CK_ULONG_PTR wrapped_key_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_WrapKey) (handle, mechanism, wrapping_key, key, wrapped_key, wrapped_key_len); -} - -static CK_RV -proxy_C_UnwrapKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_OBJECT_HANDLE unwrapping_key, CK_BYTE_PTR wrapped_key, - CK_ULONG wrapped_key_len, CK_ATTRIBUTE_PTR template, - CK_ULONG count, CK_OBJECT_HANDLE_PTR key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_UnwrapKey) (handle, mechanism, unwrapping_key, wrapped_key, wrapped_key_len, template, count, key); -} - -static CK_RV -proxy_C_DeriveKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, - CK_OBJECT_HANDLE base_key, CK_ATTRIBUTE_PTR template, - CK_ULONG count, CK_OBJECT_HANDLE_PTR key) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_DeriveKey) (handle, mechanism, base_key, template, count, key); -} - -static CK_RV -proxy_C_SeedRandom (CK_SESSION_HANDLE handle, CK_BYTE_PTR seed, CK_ULONG seed_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_SeedRandom) (handle, seed, seed_len); -} - -static CK_RV -proxy_C_GenerateRandom (CK_SESSION_HANDLE handle, CK_BYTE_PTR random_data, - CK_ULONG random_len) -{ - Mapping map; - CK_RV rv; - - rv = map_session_to_real (&handle, &map, NULL); - if (rv != CKR_OK) - return rv; - return (map.funcs->C_GenerateRandom) (handle, random_data, random_len); -} - -/* -------------------------------------------------------------------- - * MODULE ENTRY POINT - */ - -static CK_FUNCTION_LIST proxy_function_list = { - { CRYPTOKI_VERSION_MAJOR, CRYPTOKI_VERSION_MINOR }, /* version */ - proxy_C_Initialize, - proxy_C_Finalize, - proxy_C_GetInfo, - proxy_C_GetFunctionList, - proxy_C_GetSlotList, - proxy_C_GetSlotInfo, - proxy_C_GetTokenInfo, - proxy_C_GetMechanismList, - proxy_C_GetMechanismInfo, - proxy_C_InitToken, - proxy_C_InitPIN, - proxy_C_SetPIN, - proxy_C_OpenSession, - proxy_C_CloseSession, - proxy_C_CloseAllSessions, - proxy_C_GetSessionInfo, - proxy_C_GetOperationState, - proxy_C_SetOperationState, - proxy_C_Login, - proxy_C_Logout, - proxy_C_CreateObject, - proxy_C_CopyObject, - proxy_C_DestroyObject, - proxy_C_GetObjectSize, - proxy_C_GetAttributeValue, - proxy_C_SetAttributeValue, - proxy_C_FindObjectsInit, - proxy_C_FindObjects, - proxy_C_FindObjectsFinal, - proxy_C_EncryptInit, - proxy_C_Encrypt, - proxy_C_EncryptUpdate, - proxy_C_EncryptFinal, - proxy_C_DecryptInit, - proxy_C_Decrypt, - proxy_C_DecryptUpdate, - proxy_C_DecryptFinal, - proxy_C_DigestInit, - proxy_C_Digest, - proxy_C_DigestUpdate, - proxy_C_DigestKey, - proxy_C_DigestFinal, - proxy_C_SignInit, - proxy_C_Sign, - proxy_C_SignUpdate, - proxy_C_SignFinal, - proxy_C_SignRecoverInit, - proxy_C_SignRecover, - proxy_C_VerifyInit, - proxy_C_Verify, - proxy_C_VerifyUpdate, - proxy_C_VerifyFinal, - proxy_C_VerifyRecoverInit, - proxy_C_VerifyRecover, - proxy_C_DigestEncryptUpdate, - proxy_C_DecryptDigestUpdate, - proxy_C_SignEncryptUpdate, - proxy_C_DecryptVerifyUpdate, - proxy_C_GenerateKey, - proxy_C_GenerateKeyPair, - proxy_C_WrapKey, - proxy_C_UnwrapKey, - proxy_C_DeriveKey, - proxy_C_SeedRandom, - proxy_C_GenerateRandom, - proxy_C_GetFunctionStatus, - proxy_C_CancelFunction, - proxy_C_WaitForSlotEvent -}; - -CK_RV -C_GetFunctionList (CK_FUNCTION_LIST_PTR_PTR list) -{ - return proxy_C_GetFunctionList (list); -} diff --git a/p11-kit/p11-kit-uri.c b/p11-kit/p11-kit-uri.c deleted file mode 100644 index f2ac3ad..0000000 --- a/p11-kit/p11-kit-uri.c +++ /dev/null @@ -1,1337 +0,0 @@ -/* - * Copyright (C) 2011 Collabora Ltd. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * 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. - * * The names of contributors to this software may not be - * used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 - * COPYRIGHT OWNER 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. - * - * Author: Stef Walter - */ - -#include "config.h" - -#define DEBUG_FLAG DEBUG_URI -#include "debug.h" -#include "pkcs11.h" -#include "p11-kit-uri.h" -#include "util.h" - -#include -#include -#include -#include -#include - -/** - * SECTION:p11-kit-uri - * @title: URIs - * @short_description: Parsing and formatting PKCS\#11 URIs - * - * PKCS\#11 URIs can be used in configuration files or applications to represent - * PKCS\#11 modules, tokens or objects. An example of a URI might be: - * - * - * pkcs11:token=The\%20Software\%20PKCS\#11\%20softtoken; - * manufacturer=Snake\%20Oil,\%20Inc.;serial=;object=my-certificate; - * model=1.0;objecttype=cert;id=\%69\%95\%3e\%5c\%f4\%bd\%ec\%91 - * - * - * You can use p11_kit_uri_parse() to parse such a URI, and p11_kit_uri_format() - * to build one. URIs are represented by the #P11KitUri structure. You can match - * a parsed URI against PKCS\#11 tokens with p11_kit_uri_match_token_info() - * or attributes with p11_kit_uri_match_attributes(). - * - * Since URIs can represent different sorts of things, when parsing or formatting - * a URI a 'context' can be used to indicate which sort of URI is expected. - * - * URIs have an unrecognized flag. This flag is set during parsing - * if any parts of the URI are not recognized. This may be because the part is - * from a newer version of the PKCS\#11 spec or because that part was not valid - * inside of the desired context used when parsing. - */ - -/** - * P11KitUri: - * - * A structure representing a PKCS\#11 URI. There are no public fields - * visible in this structure. Use the various accessor functions. - */ - -/** - * P11KitUriType: - * @P11_KIT_URI_IS_MODULE: The URI represents one or more modules - * @P11_KIT_URI_IS_TOKEN: The URI represents one or more tokens - * @P11_KIT_URI_IS_OBJECT: The URI represents one or more objects - * @P11_KIT_URI_IS_ANY: The URI can represent anything - * - * A PKCS\#11 URI can represent different kinds of things. This flag is used by - * p11_kit_uri_parse() to denote in what context the URI will be used. - */ - -/** - * P11KitUriResult: - * @P11_KIT_URI_OK: Success - * @P11_KIT_URI_NO_MEMORY: Memory allocation failed - * @P11_KIT_URI_BAD_SCHEME: The URI had a bad scheme - * @P11_KIT_URI_BAD_ENCODING: The URI had a bad encoding - * @P11_KIT_URI_BAD_SYNTAX: The URI had a bad syntax - * @P11_KIT_URI_BAD_VERSION: The URI contained a bad version number - * @P11_KIT_URI_NOT_FOUND: A requested part of the URI was not found - * - * Error codes returned by various functions. The functions each clearly state - * which error codes they are capable of returning. - */ - -/** - * P11_KIT_URI_SCHEME: - * - * String of URI scheme for PKCS\#11 URIs. - */ - -/** - * P11_KIT_URI_SCHEME_LEN: - * - * Length of %P11_KIT_URI_SCHEME. - */ - -static const CK_ATTRIBUTE_TYPE SUPPORTED_ATTRIBUTE_TYPES[] = { - CKA_CLASS, - CKA_LABEL, - CKA_ID -}; - -#define NUM_ATTRIBUTE_TYPES \ - (sizeof (SUPPORTED_ATTRIBUTE_TYPES) / sizeof (SUPPORTED_ATTRIBUTE_TYPES[0])) - -struct _P11KitUri { - int unrecognized; - CK_INFO module; - CK_TOKEN_INFO token; - CK_ATTRIBUTE attributes[NUM_ATTRIBUTE_TYPES]; - CK_ULONG n_attributes; - char *pinfile; -}; - -const static char HEX_CHARS[] = "0123456789abcdef"; - -static int -url_decode (const char *value, const char *end, - unsigned char** output, size_t *length) -{ - char *a, *b; - unsigned char *result, *p; - - assert (output); - assert (value <= end); - - /* String can only get shorter */ - result = malloc ((end - value) + 1); - if (!result) - return P11_KIT_URI_NO_MEMORY; - - /* Now loop through looking for escapes */ - p = result; - while (value != end) { - /* - * A percent sign followed by two hex digits means - * that the digits represent an escaped character. - */ - if (*value == '%') { - value++; - if (value + 2 > end) { - free (result); - return P11_KIT_URI_BAD_ENCODING; - } - a = strchr (HEX_CHARS, tolower (value[0])); - b = strchr (HEX_CHARS, tolower (value[1])); - if (!a || !b) { - free (result); - return P11_KIT_URI_BAD_ENCODING; - } - *p = (a - HEX_CHARS) << 4; - *(p++) |= (b - HEX_CHARS); - value += 2; - } else { - *(p++) = *(value++); - } - } - - /* Null terminate string, in case its a string */ - *p = 0; - - if (length) - *length = p - result; - *output = result; - return P11_KIT_URI_OK; -} - -static char* -url_encode (const unsigned char *value, const unsigned char *end, size_t *length) -{ - char *p; - char *result; - - assert (value <= end); - - /* Just allocate for worst case */ - result = malloc (((end - value) * 3) + 1); - if (!result) - return NULL; - - /* Now loop through looking for escapes */ - p = result; - while (value != end) { - - /* These characters we let through verbatim */ - if (*value && (isalnum (*value) || strchr ("_-.", *value) != NULL)) { - *(p++) = *(value++); - - /* All others get encoded */ - } else { - *(p++) = '%'; - *(p++) = HEX_CHARS[((unsigned char)*value) >> 4]; - *(p++) = HEX_CHARS[((unsigned char)*value) & 0x0F]; - ++value; - } - } - - *p = 0; - if (length) - *length = p - result; - return result; -} - -static int -match_struct_string (const unsigned char *inuri, const unsigned char *real, - size_t length) -{ - assert (inuri); - assert (real); - assert (length > 0); - - /* NULL matches anything */ - if (inuri[0] == 0) - return 1; - - return memcmp (inuri, real, length) == 0 ? 1 : 0; -} - -static int -match_struct_version (CK_VERSION_PTR inuri, CK_VERSION_PTR real) -{ - /* This matches anything */ - if (inuri->major == (CK_BYTE)-1 && inuri->minor == (CK_BYTE)-1) - return 1; - - return memcmp (inuri, real, sizeof (CK_VERSION)); -} - -/** - * p11_kit_uri_get_module_info: - * @uri: the URI - * - * Get the CK_INFO structure associated with this URI. - * - * If this is a parsed URI, then the fields corresponding to library parts of - * the URI will be filled in. Any library URI parts that were missing will have - * their fields filled with zeros. - * - * If the caller wishes to setup information for building a URI, then relevant - * fields should be filled in. Fields that should not appear as parts in the - * resulting URI should be filled with zeros. - * - * Returns: A pointer to the CK_INFO structure. - */ -CK_INFO_PTR -p11_kit_uri_get_module_info (P11KitUri *uri) -{ - assert (uri); - return &uri->module; -} - -/** - * p11_kit_uri_match_module_info: - * @uri: the URI - * @info: the structure to match against the URI - * - * Match a CK_INFO structure against the library parts of this URI. - * - * Only the fields of the CK_INFO structure that are valid for use - * in a URI will be matched. A URI part that was not specified in the URI will - * match any value in the structure. If during the URI parsing any unrecognized - * parts were encountered then this match will fail. - * - * Returns: 1 if the URI matches, 0 if not. - */ -int -p11_kit_uri_match_module_info (P11KitUri *uri, CK_INFO_PTR info) -{ - assert (uri); - assert (info); - - if (uri->unrecognized) - return 0; - - return (match_struct_string (uri->module.libraryDescription, - info->libraryDescription, - sizeof (info->libraryDescription)) && - match_struct_string (uri->module.manufacturerID, - info->manufacturerID, - sizeof (info->manufacturerID)) && - match_struct_version (&uri->module.libraryVersion, - &info->libraryVersion)); -} - -/** - * p11_kit_uri_get_token_info: - * @uri: the URI - * - * Get the CK_TOKEN_INFO structure associated with this URI. - * - * If this is a parsed URI, then the fields corresponding to token parts of - * the URI will be filled in. Any token URI parts that were missing will have - * their fields filled with zeros. - * - * If the caller wishes to setup information for building a URI, then relevant - * fields should be filled in. Fields that should not appear as parts in the - * resulting URI should be filled with zeros. - * - * Returns: A pointer to the CK_INFO structure. - */ -CK_TOKEN_INFO_PTR -p11_kit_uri_get_token_info (P11KitUri *uri) -{ - assert (uri); - return &uri->token; -} - -/** - * p11_kit_uri_match_token_info: - * @uri: the URI - * @token_info: the structure to match against the URI - * - * Match a CK_TOKEN_INFO structure against the token parts of this - * URI. - * - * Only the fields of the CK_TOKEN_INFO structure that are valid - * for use in a URI will be matched. A URI part that was not specified in the - * URI will match any value in the structure. If during the URI parsing any - * unrecognized parts were encountered then this match will fail. - * - * Returns: 1 if the URI matches, 0 if not. - */ -int -p11_kit_uri_match_token_info (P11KitUri *uri, CK_TOKEN_INFO_PTR token_info) -{ - assert (uri); - assert (token_info); - - if (uri->unrecognized) - return 0; - - return (match_struct_string (uri->token.label, - token_info->label, - sizeof (token_info->label)) && - match_struct_string (uri->token.manufacturerID, - token_info->manufacturerID, - sizeof (token_info->manufacturerID)) && - match_struct_string (uri->token.model, - token_info->model, - sizeof (token_info->model)) && - match_struct_string (uri->token.serialNumber, - token_info->serialNumber, - sizeof (token_info->serialNumber))); -} - -/** - * p11_kit_uri_get_attribute: - * @uri: The URI - * @attr_type: The attribute type - * - * Get a pointer to an attribute present in this URI. - * - * Returns: A pointer to the attribute, or NULL if not present. - * The attribute is owned by the URI and should not be freed. - */ -CK_ATTRIBUTE_PTR -p11_kit_uri_get_attribute (P11KitUri *uri, CK_ATTRIBUTE_TYPE attr_type) -{ - CK_ULONG i; - - assert (uri); - - for (i = 0; i < uri->n_attributes; i++) { - if (uri->attributes[i].type == attr_type) - return &uri->attributes[i]; - } - - return NULL; -} - -static void -uri_take_attribute (P11KitUri *uri, CK_ATTRIBUTE_PTR attr) -{ - CK_ULONG i; - - assert (uri); - assert (attr); - - /* Replace an attribute already set */ - for (i = 0; i < uri->n_attributes; i++) { - if (uri->attributes[i].type == attr->type) { - free (uri->attributes[i].pValue); - memcpy (&uri->attributes[i], attr, sizeof (CK_ATTRIBUTE)); - memset (attr, 0, sizeof (CK_ATTRIBUTE)); - return; - } - } - - /* Add one at the end */ - assert (uri->n_attributes < NUM_ATTRIBUTE_TYPES); - memcpy (&uri->attributes[uri->n_attributes], attr, sizeof (CK_ATTRIBUTE)); - memset (attr, 0, sizeof (CK_ATTRIBUTE)); - uri->n_attributes++; -} - -/** - * p11_kit_uri_set_attribute: - * @uri: The URI - * @attr: The attribute to set - * - * Set an attribute on the URI. - * - * Only attributes that map to parts in a PKCS\#11 URI will be accepted. - * - * Returns: %P11_KIT_URI_OK if the attribute was successfully set. - * %P11_KIT_URI_NOT_FOUND if the attribute was not valid for a URI. - * %P11_KIT_URI_NO_MEMORY if allocation failed. - */ -int -p11_kit_uri_set_attribute (P11KitUri *uri, CK_ATTRIBUTE_PTR attr) -{ - CK_ATTRIBUTE copy; - CK_ULONG i; - - assert (uri); - assert (attr); - - /* Make sure the attribute type is valid */ - for (i = 0; i < NUM_ATTRIBUTE_TYPES; i++) { - if (SUPPORTED_ATTRIBUTE_TYPES[i] == attr->type) - break; - } - if (i == NUM_ATTRIBUTE_TYPES) - return P11_KIT_URI_NOT_FOUND; - - memcpy (©, attr, sizeof (CK_ATTRIBUTE)); - - /* Duplicate the value */ - if (attr->pValue && attr->ulValueLen && attr->ulValueLen != (CK_ULONG)-1) { - copy.pValue = malloc (attr->ulValueLen); - if (!copy.pValue) - return P11_KIT_URI_NO_MEMORY; - memcpy (copy.pValue, attr->pValue, attr->ulValueLen); - } - - uri_take_attribute (uri, ©); - return P11_KIT_URI_OK; -} - -/** - * p11_kit_uri_clear_attribute: - * @uri: The URI - * @attr_type: The type of the attribute to clear - * - * Clear an attribute on the URI. - * - * Only attributes that map to parts in a PKCS\#11 URI will be accepted. - * - * Returns: %P11_KIT_URI_OK if the attribute was successfully cleared. - * %P11_KIT_URI_NOT_FOUND if the attribute was not valid for a URI. - */ -int -p11_kit_uri_clear_attribute (P11KitUri *uri, CK_ATTRIBUTE_TYPE attr_type) -{ - CK_ATTRIBUTE_PTR clear = NULL; - CK_ATTRIBUTE_PTR last; - CK_ULONG i; - - assert (uri); - - /* Make sure the attribute type is valid */ - for (i = 0; i < NUM_ATTRIBUTE_TYPES; i++) { - if (SUPPORTED_ATTRIBUTE_TYPES[i] == attr_type) - break; - } - if (i == NUM_ATTRIBUTE_TYPES) - return P11_KIT_URI_NOT_FOUND; - - /* Cleanup the values in the attribute */ - for (i = 0; i < uri->n_attributes; i++) { - if (uri->attributes[i].type == attr_type) { - clear = &uri->attributes[i]; - free (uri->attributes[i].pValue); - break; - } - } - - /* A valid attribute, but not present */ - if (clear == NULL) - return P11_KIT_URI_OK; - - assert (uri->n_attributes > 0); - uri->n_attributes--; - - /* If not the last attribute, then make last take its place */ - last = &uri->attributes[uri->n_attributes]; - if (clear != last) { - memcpy (clear, last, sizeof (CK_ATTRIBUTE)); - clear = last; - } - - memset (clear, 0, sizeof (CK_ATTRIBUTE)); - return P11_KIT_URI_OK; -} - -/** - * p11_kit_uri_get_attribute_types: - * @uri: The URI - * @n_attrs: A location to store the number of attributes returned. - * - * Get the attributes present in this URI. The attributes and values are - * owned by the URI. If the URI is modified, then the attributes that were - * returned from this function will not remain consistent. - * - * Returns: The attributes for this URI. These are owned by the URI. - */ -CK_ATTRIBUTE_PTR -p11_kit_uri_get_attributes (P11KitUri *uri, CK_ULONG_PTR n_attrs) -{ - assert (uri); - assert (n_attrs); - - *n_attrs = uri->n_attributes; - return uri->attributes; -} - -int -p11_kit_uri_set_attributes (P11KitUri *uri, CK_ATTRIBUTE_PTR attrs, - CK_ULONG n_attrs) -{ - CK_ULONG i; - int ret; - - assert (uri); - - p11_kit_uri_clear_attributes (uri); - - for (i = 0; i < n_attrs; i++) { - ret = p11_kit_uri_set_attribute (uri, &attrs[i]); - if (ret != P11_KIT_URI_OK && ret != P11_KIT_URI_NOT_FOUND) - return ret; - } - - return P11_KIT_URI_OK; -} - -void -p11_kit_uri_clear_attributes (P11KitUri *uri) -{ - CK_ULONG i; - - assert (uri); - - for (i = 0; i < uri->n_attributes; i++) - free (uri->attributes[i].pValue); - uri->n_attributes = 0; -} - - -static int -match_attributes (CK_ATTRIBUTE_PTR one, CK_ATTRIBUTE_PTR two) -{ - assert (one); - assert (two); - - if (one->type != two->type) - return 0; - if (one->ulValueLen != two->ulValueLen) - return 0; - if (one->pValue == two->pValue) - return 1; - if (!one->pValue || !two->pValue) - return 0; - return memcmp (one->pValue, two->pValue, one->ulValueLen) == 0; -} - -/** - * p11_kit_uri_match_attributes: - * @uri: The URI - * @attrs: The attributes to match - * @n_attrs: The number of attributes - * - * Match a attributes against the object parts of this URI. - * - * Only the attributes that are valid for use in a URI will be matched. A URI - * part that was not specified in the URI will match any attribute value. If - * during the URI parsing any unrecognized parts were encountered then this - * match will fail. - * - * Returns: 1 if the URI matches, 0 if not. - */ -int -p11_kit_uri_match_attributes (P11KitUri *uri, CK_ATTRIBUTE_PTR attrs, - CK_ULONG n_attrs) -{ - CK_ULONG j; - CK_ULONG i; - - assert (uri); - assert (attrs || !n_attrs); - - if (uri->unrecognized) - return 0; - - for (i = 0; i < uri->n_attributes; i++) { - for (j = 0; j < n_attrs; ++j) { - if (uri->attributes[i].type == attrs[j].type) { - if (!match_attributes (&uri->attributes[i], &attrs[j])) - return 0; - break; - } - } - } - - return 1; -} - -/** - * p11_kit_uri_set_unrecognized: - * @uri: The URI - * @unrecognized: The new unregognized flag value - * - * Set the unrecognized flag on this URI. - * - * The unrecognized flag is automatically set to 1 when during parsing any part - * of the URI is unrecognized. If the unrecognized flag is set to 1, then - * matching against this URI will always fail. - */ -void -p11_kit_uri_set_unrecognized (P11KitUri *uri, int unrecognized) -{ - assert (uri); - uri->unrecognized = unrecognized; -} - -/** - * p11_kit_uri_any_unrecognized: - * @uri: The URI - * - * Get the unrecognized flag for this URI. - * - * The unrecognized flag is automatically set to 1 when during parsing any part - * of the URI is unrecognized. If the unrecognized flag is set to 1, then - * matching against this URI will always fail. - * - * Returns: 1 if unrecognized flag is set, 0 otherwise. - */ -int -p11_kit_uri_any_unrecognized (P11KitUri *uri) -{ - assert (uri); - return uri->unrecognized; -} - -/** - * p11_kit_uri_get_pinfile: - * @uri: The URI - * - * Get the 'pinfile' part of the URI. This is used by some applications to - * lookup a PIN for logging into a PKCS\#11 token. - * - * Returns: The pinfile or %NULL if not present. - */ -const char* -p11_kit_uri_get_pinfile (P11KitUri *uri) -{ - assert (uri); - return uri->pinfile; -} - -/** - * p11_kit_uri_set_pinfile: - * @uri: The URI - * @pinfile: The new pinfile - * - * Set the 'pinfile' part of the URI. This is used by some applications to - * lookup a PIN for logging into a PKCS\#11 token. - */ -void -p11_kit_uri_set_pinfile (P11KitUri *uri, const char *pinfile) -{ - assert (uri); - free (uri->pinfile); - uri->pinfile = strdup (pinfile); -} - -/** - * p11_kit_uri_new: - * - * Create a new blank PKCS\#11 URI. - * - * The new URI is in the right state to parse a string into. All relevant fields - * are zeroed out. Formatting this URI will produce a valid but empty URI. - * - * Returns: A newly allocated URI. This should be freed with p11_kit_uri_free(). - */ -P11KitUri* -p11_kit_uri_new (void) -{ - P11KitUri *uri; - - uri = calloc (1, sizeof (P11KitUri)); - if (!uri) - return NULL; - - /* So that it matches anything */ - uri->module.libraryVersion.major = (CK_BYTE)-1; - uri->module.libraryVersion.minor = (CK_BYTE)-1; - - return uri; -} - -static size_t -space_strlen (const unsigned char *string, size_t max_length) -{ - size_t i = max_length - 1; - - assert (string); - - while (i > 0 && string[i] == ' ') - --i; - return i + 1; -} - -static int -format_raw_string (char **string, size_t *length, int *is_first, - const char *name, const char *value) -{ - size_t namelen; - size_t vallen; - - /* Not set */ - if (!value) - return 1; - - namelen = strlen (name); - vallen = strlen (value); - - *string = xrealloc (*string, *length + namelen + vallen + 3); - if (!*string) - return 0; - - if (!*is_first) - (*string)[(*length)++] = ';'; - memcpy ((*string) + *length, name, namelen); - *length += namelen; - (*string)[(*length)++] = '='; - memcpy ((*string) + *length, value, vallen); - *length += vallen; - (*string)[*length] = 0; - *is_first = 0; - - return 1; -} - -static int -format_encode_string (char **string, size_t *length, int *is_first, - const char *name, const unsigned char *value, - size_t n_value) -{ - char *encoded; - int ret; - - encoded = url_encode (value, value + n_value, NULL); - if (!encoded) - return 0; - - ret = format_raw_string (string, length, is_first, name, encoded); - free (encoded); - return ret; -} - - -static int -format_struct_string (char **string, size_t *length, int *is_first, - const char *name, const unsigned char *value, - size_t value_max) -{ - size_t len; - - /* Not set */ - if (!value[0]) - return 1; - - len = space_strlen (value, value_max); - return format_encode_string (string, length, is_first, name, value, len); -} - -static int -format_attribute_string (char **string, size_t *length, int *is_first, - const char *name, CK_ATTRIBUTE_PTR attr) -{ - /* Not set */; - if (attr == NULL) - return 1; - - return format_encode_string (string, length, is_first, name, - attr->pValue, attr->ulValueLen); -} - -static int -format_attribute_class (char **string, size_t *length, int *is_first, - const char *name, CK_ATTRIBUTE_PTR attr) -{ - CK_OBJECT_CLASS klass; - const char *value; - - /* Not set */; - if (attr == NULL) - return 1; - - klass = *((CK_OBJECT_CLASS*)attr->pValue); - switch (klass) { - case CKO_DATA: - value = "data"; - break; - case CKO_SECRET_KEY: - value = "secretkey"; - break; - case CKO_CERTIFICATE: - value = "cert"; - break; - case CKO_PUBLIC_KEY: - value = "public"; - break; - case CKO_PRIVATE_KEY: - value = "private"; - break; - default: - return 1; - } - - return format_raw_string (string, length, is_first, name, value); -} - -static int -format_struct_version (char **string, size_t *length, int *is_first, - const char *name, CK_VERSION_PTR version) -{ - char buffer[64]; - - /* Not set */ - if (version->major == (CK_BYTE)-1 && version->minor == (CK_BYTE)-1) - return 1; - - snprintf (buffer, sizeof (buffer), "%d.%d", - (int)version->major, (int)version->minor); - return format_raw_string (string, length, is_first, name, buffer); -} - -/** - * p11_kit_uri_format: - * @uri: The URI. - * @uri_type: The type of URI that should be produced. - * @string: Location to store a newly allocated string. - * - * Format a PKCS\#11 URI into a string. - * - * Fields which are zeroed out will not be included in the resulting string. - * Attributes which are not present will also not be included. - * - * The uri_type of URI specified limits the different parts of the resulting - * URI. To format a URI containing all possible information use - * %P11_KIT_URI_IS_ANY - * - * The resulting string should be freed with free(). - * - * Returns: %P11_KIT_URI_OK if the URI was formatted successfully. - * %P11_KIT_URI_NO_MEMORY if memory allocation failed. - */ -int -p11_kit_uri_format (P11KitUri *uri, P11KitUriType uri_type, char **string) -{ - char *result = NULL; - size_t length = 0; - int is_first = 1; - - result = malloc (128); - if (!result) - return P11_KIT_URI_NO_MEMORY; - - length = P11_KIT_URI_SCHEME_LEN; - memcpy (result, P11_KIT_URI_SCHEME, length); - result[length] = 0; - - if (uri_type & P11_KIT_URI_IS_MODULE) { - if (!format_struct_string (&result, &length, &is_first, "library-description", - uri->module.libraryDescription, - sizeof (uri->module.libraryDescription)) || - !format_struct_version (&result, &length, &is_first, "library-version", - &uri->module.libraryVersion) || - !format_struct_string (&result, &length, &is_first, "library-manufacturer", - uri->module.manufacturerID, - sizeof (uri->module.manufacturerID))) { - free (result); - return P11_KIT_URI_NO_MEMORY; - } - } - - if (uri_type & P11_KIT_URI_IS_TOKEN) { - if (!format_struct_string (&result, &length, &is_first, "model", - uri->token.model, - sizeof (uri->token.model)) || - !format_struct_string (&result, &length, &is_first, "manufacturer", - uri->token.manufacturerID, - sizeof (uri->token.manufacturerID)) || - !format_struct_string (&result, &length, &is_first, "serial", - uri->token.serialNumber, - sizeof (uri->token.serialNumber)) || - !format_struct_string (&result, &length, &is_first, "token", - uri->token.label, - sizeof (uri->token.label))) { - free (result); - return P11_KIT_URI_NO_MEMORY; - } - } - - if (uri_type & P11_KIT_URI_IS_OBJECT) { - if (!format_attribute_string (&result, &length, &is_first, "id", - p11_kit_uri_get_attribute (uri, CKA_ID)) || - !format_attribute_string (&result, &length, &is_first, "object", - p11_kit_uri_get_attribute (uri, CKA_LABEL))) { - free (result); - return P11_KIT_URI_NO_MEMORY; - } - - if (!format_attribute_class (&result, &length, &is_first, "objecttype", - p11_kit_uri_get_attribute (uri, CKA_CLASS))) { - free (result); - return P11_KIT_URI_NO_MEMORY; - } - } - - if (uri->pinfile) { - format_encode_string (&result, &length, &is_first, "pinfile", - (const unsigned char*)uri->pinfile, - strlen (uri->pinfile)); - } - - *string = result; - return P11_KIT_URI_OK; -} - -static int -parse_string_attribute (const char *name, const char *start, const char *end, - P11KitUri *uri) -{ - unsigned char *value; - CK_ATTRIBUTE attr; - size_t length; - int ret; - - assert (start <= end); - - if (strcmp ("id", name) == 0) - attr.type = CKA_ID; - else if (strcmp ("object", name) == 0) - attr.type = CKA_LABEL; - else - return 0; - - ret = url_decode (start, end, &value, &length); - if (ret < 0) - return ret; - - attr.pValue = value; - attr.ulValueLen = length; - uri_take_attribute (uri, &attr); - return 1; -} - -static int -equals_segment (const char *start, const char *end, const char *match) -{ - size_t len = strlen (match); - assert (start <= end); - return (end - start == len) && memcmp (start, match, len) == 0; -} - -static int -parse_class_attribute (const char *name, const char *start, const char *end, - P11KitUri *uri) -{ - CK_OBJECT_CLASS klass = 0; - CK_ATTRIBUTE attr; - - assert (start <= end); - - if (strcmp ("objecttype", name) != 0) - return 0; - - if (equals_segment (start, end, "cert")) - klass = CKO_CERTIFICATE; - else if (equals_segment (start, end, "public")) - klass = CKO_PUBLIC_KEY; - else if (equals_segment (start, end, "private")) - klass = CKO_PRIVATE_KEY; - else if (equals_segment (start, end, "secretkey")) - klass = CKO_SECRET_KEY; - else if (equals_segment (start, end, "data")) - klass = CKO_DATA; - else { - uri->unrecognized = 1; - return 1; - } - - attr.pValue = malloc (sizeof (klass)); - if (attr.pValue == NULL) - return P11_KIT_URI_NO_MEMORY; - - memcpy (attr.pValue, &klass, sizeof (klass)); - attr.ulValueLen = sizeof (klass); - attr.type = CKA_CLASS; - - uri_take_attribute (uri, &attr); - return 1; -} - -static int -parse_struct_info (unsigned char *where, size_t length, const char *start, - const char *end, P11KitUri *uri) -{ - unsigned char *value; - size_t value_length; - int ret; - - assert (start <= end); - - ret = url_decode (start, end, &value, &value_length); - if (ret < 0) - return ret; - - /* Too long, shouldn't match anything */ - if (value_length > length) { - free (value); - uri->unrecognized = 1; - return 1; - } - - memset (where, ' ', length); - memcpy (where, value, value_length); - - free (value); - return 1; -} - -static int -parse_token_info (const char *name, const char *start, const char *end, - P11KitUri *uri) -{ - unsigned char *where; - size_t length; - - assert (start <= end); - - if (strcmp (name, "model") == 0) { - where = uri->token.model; - length = sizeof (uri->token.model); - } else if (strcmp (name, "manufacturer") == 0) { - where = uri->token.manufacturerID; - length = sizeof (uri->token.manufacturerID); - } else if (strcmp (name, "serial") == 0) { - where = uri->token.serialNumber; - length = sizeof (uri->token.serialNumber); - } else if (strcmp (name, "token") == 0) { - where = uri->token.label; - length = sizeof (uri->token.label); - } else { - return 0; - } - - return parse_struct_info (where, length, start, end, uri); -} - -static int -atoin (const char *start, const char *end) -{ - int ret = 0; - while (start != end) { - if (*start < '0' || *start > '9') - return -1; - ret *= 10; - ret += (*start - '0'); - ++start; - } - return ret; -} - -static int -parse_struct_version (const char *start, const char *end, CK_VERSION_PTR version) -{ - const char *dot; - int val; - - assert (start <= end); - - dot = memchr (start, '.', end - start); - if (!dot) - dot = end; - - if (dot == start) - return P11_KIT_URI_BAD_VERSION; - val = atoin (start, dot); - if (val < 0 || val >= 255) - return P11_KIT_URI_BAD_VERSION; - version->major = (CK_BYTE)val; - version->minor = 0; - - if (dot != end) { - if (dot + 1 == end) - return P11_KIT_URI_BAD_VERSION; - val = atoin (dot + 1, end); - if (val < 0 || val >= 255) - return P11_KIT_URI_BAD_VERSION; - version->minor = (CK_BYTE)val; - } - - return 1; -} - -static int -parse_module_info (const char *name, const char *start, const char *end, - P11KitUri *uri) -{ - unsigned char *where; - size_t length; - - assert (start <= end); - - if (strcmp (name, "library-description") == 0) { - where = uri->module.libraryDescription; - length = sizeof (uri->module.libraryDescription); - } else if (strcmp (name, "library-manufacturer") == 0) { - where = uri->module.manufacturerID; - length = sizeof (uri->module.manufacturerID); - } else if (strcmp (name, "library-version") == 0) { - return parse_struct_version (start, end, - &uri->module.libraryVersion); - } else { - return 0; - } - - return parse_struct_info (where, length, start, end, uri); -} - -static int -parse_extra_info (const char *name, const char *start, const char *end, - P11KitUri *uri) -{ - unsigned char *pinfile; - int ret; - - assert (start <= end); - - if (strcmp (name, "pinfile") == 0) { - ret = url_decode (start, end, &pinfile, NULL); - if (ret < 0) - return ret; - free (uri->pinfile); - uri->pinfile = (char*)pinfile; - return 1; - } - - return 0; -} - -/** - * p11_kit_uri_parse: - * @string: The string to parse - * @uri_type: The type of URI that is expected - * @uri: The blank URI to parse the values into - * - * Parse a PKCS\#11 URI string. - * - * PKCS\#11 URIs can represent tokens, objects or modules. The uri_type argument - * allows the caller to specify what type of URI is expected and the sorts of - * objects the URI should match. %P11_KIT_URI_IS_ANY can be used to parse a URI - * for any context. It's then up to the caller to make sense of the way that - * it is used. - * - * If the PKCS\#11 URI contains unrecognized URI parts or parts not applicable - * to the specified context, then the unrecognized flag will be set. This will - * prevent the URI from matching using the various match functions. - * - * Returns: %P11_KIT_URI_OK if the URI was parsed successfully. - * %P11_KIT_URI_BAD_SCHEME if this was not a PKCS\#11 URI. - * %P11_KIT_URI_BAD_SYNTAX if the URI syntax was bad. - * %P11_KIT_URI_NO_MEMORY if memory allocation failed. - * %P11_KIT_URI_BAD_VERSION if a version number was bad. - * %P11_KIT_URI_BAD_ENCODING if the URI encoding was invalid. - */ -int -p11_kit_uri_parse (const char *string, P11KitUriType uri_type, - P11KitUri *uri) -{ - const char *spos, *epos; - char *key = NULL; - int ret = -1; - int i; - - assert (string); - assert (uri); - - if (strncmp (string, P11_KIT_URI_SCHEME, P11_KIT_URI_SCHEME_LEN) != 0) - return P11_KIT_URI_BAD_SCHEME; - - string += P11_KIT_URI_SCHEME_LEN; - - /* Clear everything out */ - memset (&uri->module, 0, sizeof (uri->module)); - memset (&uri->token, 0, sizeof (uri->module)); - for (i = 0; i < uri->n_attributes; ++i) { - free (uri->attributes[i].pValue); - memset (&uri->attributes[i], 0, sizeof (CK_ATTRIBUTE)); - } - uri->n_attributes = 0; - uri->module.libraryVersion.major = (CK_BYTE)-1; - uri->module.libraryVersion.minor = (CK_BYTE)-1; - uri->unrecognized = 0; - free (uri->pinfile); - uri->pinfile = NULL; - - for (;;) { - spos = strchr (string, ';'); - if (spos == NULL) { - spos = string + strlen (string); - assert (*spos == '\0'); - if (spos == string) - break; - } - - epos = strchr (string, '='); - if (epos == NULL || spos == string || epos == string || epos >= spos) - return P11_KIT_URI_BAD_SYNTAX; - - key = malloc ((epos - string) + 1); - if (key == NULL) - return P11_KIT_URI_NO_MEMORY; - memcpy (key, string, epos - string); - key[epos - string] = 0; - epos++; - - ret = 0; - if (uri_type & P11_KIT_URI_IS_OBJECT) - ret = parse_string_attribute (key, epos, spos, uri); - if (ret == 0 && uri_type & P11_KIT_URI_IS_OBJECT) - ret = parse_class_attribute (key, epos, spos, uri); - if (ret == 0 && uri_type & P11_KIT_URI_IS_TOKEN) - ret = parse_token_info (key, epos, spos, uri); - if (ret == 0 && uri_type & P11_KIT_URI_IS_MODULE) - ret = parse_module_info (key, epos, spos, uri); - if (ret == 0) - ret = parse_extra_info (key, epos, spos, uri); - free (key); - - if (ret < 0) - return ret; - if (ret == 0) - uri->unrecognized = 1; - - if (*spos == '\0') - break; - string = spos + 1; - } - - return P11_KIT_URI_OK; -} - -/** - * p11_kit_uri_free: - * @uri: The URI - * - * Free a PKCS\#11 URI. - */ -void -p11_kit_uri_free (P11KitUri *uri) -{ - int i; - - if (!uri) - return; - - for (i = 0; i < uri->n_attributes; ++i) - free (uri->attributes[i].pValue); - - free (uri); -} - -/** - * p11_kit_uri_message: - * @code: The error code - * - * Lookup a message for the uri error code. These codes are the P11_KIT_URI_XXX - * error codes that can be returned from p11_kit_uri_parse() or - * p11_kit_uri_format(). As a special case %NULL, will be returned for - * %P11_KIT_URI_OK. - * - * Returns: The message for the error code. This string is owned by the p11-kit - * library. - */ -const char* -p11_kit_uri_message (int code) -{ - switch (code) { - case P11_KIT_URI_OK: - return NULL; - case P11_KIT_URI_NO_MEMORY: - return "Out of memory"; - case P11_KIT_URI_BAD_SCHEME: - return "URI scheme must be 'pkcs11:'"; - case P11_KIT_URI_BAD_ENCODING: - return "URI encoding invalid or corrupted"; - case P11_KIT_URI_BAD_SYNTAX: - return "URI syntax is invalid"; - case P11_KIT_URI_BAD_VERSION: - return "URI version component is invalid"; - case P11_KIT_URI_NOT_FOUND: - return "The URI component was not found"; - default: - debug ("unknown error code: %d", code); - return "Unknown error"; - } -} diff --git a/p11-kit/p11-kit-uri.h b/p11-kit/p11-kit-uri.h deleted file mode 100644 index a54f7a4..0000000 --- a/p11-kit/p11-kit-uri.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2011 Collabora Ltd. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * 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. - * * The names of contributors to this software may not be - * used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 - * COPYRIGHT OWNER 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. - * - * Author: Stef Walter - */ - -#ifndef P11_KIT_URI_H -#define P11_KIT_URI_H - -/* - * To use this API, you need to be prepared for changes to the API, - * and add the C flag: -DP11_KIT_API_SUBJECT_TO_CHANGE - */ - -#ifndef P11_KIT_API_SUBJECT_TO_CHANGE -#error "This API has not yet reached stability." -#endif - -#include "pkcs11.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define P11_KIT_URI_SCHEME "pkcs11:" -#define P11_KIT_URI_SCHEME_LEN 7 - -typedef enum { - P11_KIT_URI_OK = 0, - P11_KIT_URI_NO_MEMORY = -1, - P11_KIT_URI_BAD_SCHEME = -2, - P11_KIT_URI_BAD_ENCODING = -3, - P11_KIT_URI_BAD_SYNTAX = -4, - P11_KIT_URI_BAD_VERSION = -5, - P11_KIT_URI_NOT_FOUND = -6, -} P11KitUriResult; - -typedef enum { - P11_KIT_URI_IS_MODULE = (1 << 1), - P11_KIT_URI_IS_TOKEN = (1 << 2) | P11_KIT_URI_IS_MODULE, - P11_KIT_URI_IS_OBJECT = (1 << 3) | P11_KIT_URI_IS_TOKEN, - P11_KIT_URI_IS_ANY = 0x0000FFFF, -} P11KitUriType; - -typedef struct _P11KitUri P11KitUri; - -CK_INFO_PTR p11_kit_uri_get_module_info (P11KitUri *uri); - -int p11_kit_uri_match_module_info (P11KitUri *uri, - CK_INFO_PTR info); - -CK_TOKEN_INFO_PTR p11_kit_uri_get_token_info (P11KitUri *uri); - -int p11_kit_uri_match_token_info (P11KitUri *uri, - CK_TOKEN_INFO_PTR token_info); - -CK_ATTRIBUTE_PTR p11_kit_uri_get_attribute (P11KitUri *uri, - CK_ATTRIBUTE_TYPE attr_type); - -int p11_kit_uri_set_attribute (P11KitUri *uri, - CK_ATTRIBUTE_PTR attr); - -int p11_kit_uri_clear_attribute (P11KitUri *uri, - CK_ATTRIBUTE_TYPE attr_type); - -CK_ATTRIBUTE_PTR p11_kit_uri_get_attributes (P11KitUri *uri, - CK_ULONG *n_attrs); - -int p11_kit_uri_set_attributes (P11KitUri *uri, - CK_ATTRIBUTE_PTR attrs, - CK_ULONG n_attrs); - -void p11_kit_uri_clear_attributes (P11KitUri *uri); - -int p11_kit_uri_match_attributes (P11KitUri *uri, - CK_ATTRIBUTE_PTR attrs, - CK_ULONG n_attrs); - -const char* p11_kit_uri_get_pinfile (P11KitUri *uri); - -void p11_kit_uri_set_pinfile (P11KitUri *uri, - const char *pinfile); - -void p11_kit_uri_set_unrecognized (P11KitUri *uri, - int unrecognized); - -int p11_kit_uri_any_unrecognized (P11KitUri *uri); - -P11KitUri* p11_kit_uri_new (void); - -int p11_kit_uri_format (P11KitUri *uri, - P11KitUriType uri_type, - char **string); - -int p11_kit_uri_parse (const char *string, - P11KitUriType uri_type, - P11KitUri *uri); - -void p11_kit_uri_free (P11KitUri *uri); - -const char* p11_kit_uri_message (int code); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* P11_KIT_URI_H */ diff --git a/p11-kit/p11-kit.h b/p11-kit/p11-kit.h index 7dcfa4f..6d90a8d 100644 --- a/p11-kit/p11-kit.h +++ b/p11-kit/p11-kit.h @@ -44,7 +44,7 @@ #error "This API has not yet reached stability." #endif -#include "pkcs11.h" +#include "p11-kit/pkcs11.h" #ifdef __cplusplus extern "C" { diff --git a/p11-kit/p11-kit.pc b/p11-kit/p11-kit.pc deleted file mode 100644 index ce763cc..0000000 --- a/p11-kit/p11-kit.pc +++ /dev/null @@ -1,17 +0,0 @@ -prefix=/usr -exec_prefix=${prefix} -libdir=${exec_prefix}/lib -includedir=${prefix}/include -datarootdir=${prefix}/share -datadir=${datarootdir} -sysconfdir=/etc -p11_system_conf=/etc/pkcs11/pkcs11.conf -p11_system_modules=/etc/pkcs11/modules -p11_user_conf=~/.pkcs11/pkcs11.conf -p11_user_modules=~/.pkcs11/modules - -Name: p11-kit -Description: Library and proxy module for properly loading and sharing PKCS#11 modules. -Version: 0.1 -Libs: -L${libdir} -lp11-kit -Cflags: -I${includedir}/p11-kit diff --git a/p11-kit/p11-kit.pc.in b/p11-kit/p11-kit.pc.in deleted file mode 100644 index d80167e..0000000 --- a/p11-kit/p11-kit.pc.in +++ /dev/null @@ -1,17 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ -datarootdir=@datarootdir@ -datadir=@datadir@ -sysconfdir=@sysconfdir@ -p11_system_conf=@p11_system_conf@ -p11_system_modules=@p11_system_modules@ -p11_user_conf=@p11_user_conf@ -p11_user_modules=@p11_user_modules@ - -Name: p11-kit -Description: Library and proxy module for properly loading and sharing PKCS#11 modules. -Version: @VERSION@ -Libs: -L${libdir} -lp11-kit -Cflags: -I${includedir}/p11-kit diff --git a/p11-kit/private.h b/p11-kit/private.h new file mode 100644 index 0000000..56d5394 --- /dev/null +++ b/p11-kit/private.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Collabora Ltd. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * 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. + * * The names of contributors to this software may not be + * used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 + * COPYRIGHT OWNER 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. + * + * Author: Stef Walter + */ + +#ifndef __P11_KIT_PRIVATE_H__ +#define __P11_KIT_PRIVATE_H__ + +extern pthread_mutex_t _p11_mutex; + +#define _p11_lock() pthread_mutex_lock (&_p11_mutex); + +#define _p11_unlock() pthread_mutex_unlock (&_p11_mutex); + +CK_FUNCTION_LIST_PTR_PTR _p11_kit_registered_modules_unlocked (void); + +CK_RV _p11_kit_initialize_registered_unlocked_reentrant (void); + +CK_RV _p11_kit_finalize_registered_unlocked_reentrant (void); + +void _p11_kit_proxy_after_fork (void); + +#endif /* __P11_KIT_PRIVATE_H__ */ diff --git a/p11-kit/proxy.c b/p11-kit/proxy.c new file mode 100644 index 0000000..7160422 --- /dev/null +++ b/p11-kit/proxy.c @@ -0,0 +1,1382 @@ +/* + * Copyright (C) 2008 Stefan Walter + * Copyright (C) 2011 Collabora Ltd. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * 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. + * * The names of contributors to this software may not be + * used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 + * COPYRIGHT OWNER 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. + * + * Author: Stef Walter + */ + +#include "config.h" + +#include "hash.h" +#include "pkcs11.h" +#include "p11-kit.h" +#include "private.h" +#include "util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Start wrap slots slightly higher for testing */ +#define MAPPING_OFFSET 0x10 +#define FIRST_HANDLE 0x10 + +typedef struct _Mapping { + CK_SLOT_ID wrap_slot; + CK_SLOT_ID real_slot; + CK_FUNCTION_LIST_PTR funcs; +} Mapping; + +typedef struct _Session { + CK_SESSION_HANDLE wrap_session; + CK_SESSION_HANDLE real_session; + CK_SLOT_ID wrap_slot; +} Session; + +/* Forward declaration */ +static CK_FUNCTION_LIST proxy_function_list; + +/* + * Shared data between threads, protected by the mutex, a structure so + * we can audit thread safety easier. + */ +static struct _Shared { + Mapping *mappings; + unsigned int n_mappings; + int mappings_refs; + hash_t *sessions; + CK_ULONG last_handle; +} gl = { NULL, 0, 0, NULL, FIRST_HANDLE }; + +#define MANUFACTURER_ID "PKCS#11 Kit " +#define LIBRARY_DESCRIPTION "PKCS#11 Kit Proxy Module " +#define LIBRARY_VERSION_MAJOR 1 +#define LIBRARY_VERSION_MINOR 1 + +/* ----------------------------------------------------------------------------- + * PKCS#11 PROXY MODULE + */ + +static CK_RV +map_slot_unlocked (CK_SLOT_ID slot, Mapping *mapping) +{ + assert (mapping); + + if (slot < MAPPING_OFFSET) + return CKR_SLOT_ID_INVALID; + slot -= MAPPING_OFFSET; + + if (slot > gl.n_mappings) { + return CKR_SLOT_ID_INVALID; + } else { + assert (gl.mappings); + memcpy (mapping, &gl.mappings[slot], sizeof (Mapping)); + return CKR_OK; + } +} + +static CK_RV +map_slot_to_real (CK_SLOT_ID_PTR slot, Mapping *mapping) +{ + CK_RV rv; + + assert (mapping); + + _p11_lock (); + + if (!gl.mappings) + rv = CKR_CRYPTOKI_NOT_INITIALIZED; + else + rv = map_slot_unlocked (*slot, mapping); + if (rv == CKR_OK) + *slot = mapping->real_slot; + + _p11_unlock (); + + return rv; +} + +static CK_RV +map_session_to_real (CK_SESSION_HANDLE_PTR handle, Mapping *mapping, Session *session) +{ + CK_RV rv = CKR_OK; + Session *sess; + + assert (handle); + assert (mapping); + + _p11_lock (); + + if (!gl.sessions) { + rv = CKR_CRYPTOKI_NOT_INITIALIZED; + } else { + assert (gl.sessions); + sess = hash_get (gl.sessions, &handle); + if (sess != NULL) { + *handle = sess->real_session; + rv = map_slot_unlocked (sess->wrap_slot, mapping); + if (session != NULL) + memcpy (session, sess, sizeof (Session)); + } else { + rv = CKR_SESSION_HANDLE_INVALID; + } + } + + _p11_unlock (); + + return rv; +} + +static void +finalize_mappings_unlocked (void) +{ + assert (gl.mappings_refs); + + if (--gl.mappings_refs) + return; + + /* No more mappings */ + free (gl.mappings); + gl.mappings = NULL; + gl.n_mappings = 0; + + /* no more sessions */ + hash_free (gl.sessions); + gl.sessions = NULL; +} + +void +_p11_kit_proxy_after_fork (void) +{ + /* + * After a fork the callers are supposed to call C_Initialize and all. + * In addition the underlying libraries may change their state so free + * up any mappings and all + */ + + _p11_lock (); + + gl.mappings_refs = 1; + finalize_mappings_unlocked (); + assert (!gl.mappings); + + _p11_unlock (); +} + +static CK_RV +proxy_C_Finalize (CK_VOID_PTR reserved) +{ + CK_RV rv; + + /* WARNING: This function must be reentrant */ + + if (reserved) + return CKR_ARGUMENTS_BAD; + + _p11_lock (); + + /* WARNING: Reentrancy can occur here */ + rv = _p11_kit_finalize_registered_unlocked_reentrant (); + + /* + * If modules are all gone, then this was the last + * finalize, so cleanup our mappings + */ + if (gl.mappings_refs) + finalize_mappings_unlocked (); + + _p11_unlock (); + + return rv; +} + +static CK_RV +initialize_mappings_unlocked_reentrant (void) +{ + CK_FUNCTION_LIST_PTR *funcss, *f; + CK_FUNCTION_LIST_PTR funcs; + Mapping *mappings = NULL; + int n_mappings = 0; + CK_SLOT_ID_PTR slots; + CK_ULONG i, count; + CK_RV rv; + + assert (!gl.mappings); + + funcss = _p11_kit_registered_modules_unlocked (); + for (f = funcss; *f; ++f) { + funcs = *f; + + assert (funcs); + slots = NULL; + + _p11_unlock (); + + /* Ask module for its slots */ + rv = (funcs->C_GetSlotList) (FALSE, NULL, &count); + if (rv == CKR_OK && count) { + slots = calloc (sizeof (CK_SLOT_ID), count); + if (!slots) + rv = CKR_HOST_MEMORY; + else + rv = (funcs->C_GetSlotList) (FALSE, slots, &count); + } + + _p11_lock (); + + if (rv != CKR_OK) { + free (slots); + break; + } + + mappings = xrealloc (mappings, sizeof (Mapping) * (n_mappings + count)); + if (!mappings) { + free (slots); + rv = CKR_HOST_MEMORY; + break; + } + + /* And now add a mapping for each of those slots */ + for (i = 0; i < count; ++i) { + mappings[n_mappings].funcs = funcs; + mappings[n_mappings].wrap_slot = n_mappings + MAPPING_OFFSET; + mappings[n_mappings].real_slot = slots[i]; + ++n_mappings; + } + + free (slots); + } + + /* Another thread raced us here due to above reentrancy */ + if (gl.mappings) { + free (mappings); + return CKR_OK; + } + + assert (!gl.sessions); + gl.sessions = hash_create (hash_ulongptr_hash, hash_ulongptr_equal, NULL, free); + ++gl.mappings_refs; + + /* Any cleanup necessary for failure will happen at caller */ + return rv; +} + +static CK_RV +proxy_C_Initialize (CK_VOID_PTR init_args) +{ + CK_RV rv; + + /* WARNING: This function must be reentrant */ + + _p11_lock (); + + /* WARNING: Reentrancy can occur here */ + rv = _p11_kit_initialize_registered_unlocked_reentrant (); + + /* WARNING: Reentrancy can occur here */ + if (rv == CKR_OK && !gl.mappings_refs == 0) + rv = initialize_mappings_unlocked_reentrant (); + + _p11_unlock (); + + if (rv != CKR_OK) + proxy_C_Finalize (NULL); + + return rv; +} + +static CK_RV +proxy_C_GetInfo (CK_INFO_PTR info) +{ + CK_RV rv = CKR_OK; + + if (info == NULL) + return CKR_ARGUMENTS_BAD; + + _p11_lock (); + + if (!gl.mappings) + rv = CKR_CRYPTOKI_NOT_INITIALIZED; + + _p11_unlock (); + + if (rv != CKR_OK) + return rv; + + info->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR; + info->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR; + info->libraryVersion.major = LIBRARY_VERSION_MAJOR; + info->libraryVersion.minor = LIBRARY_VERSION_MINOR; + info->flags = 0; + strncpy ((char*)info->manufacturerID, MANUFACTURER_ID, 32); + strncpy ((char*)info->libraryDescription, LIBRARY_DESCRIPTION, 32); + return CKR_OK; +} + +static CK_RV +proxy_C_GetFunctionList (CK_FUNCTION_LIST_PTR_PTR list) +{ + /* Can be called before C_Initialize */ + + if (!list) + return CKR_ARGUMENTS_BAD; + *list = &proxy_function_list; + return CKR_OK; +} + +static CK_RV +proxy_C_GetSlotList (CK_BBOOL token_present, CK_SLOT_ID_PTR slot_list, + CK_ULONG_PTR count) +{ + CK_SLOT_INFO info; + Mapping *mapping; + CK_ULONG index; + CK_RV rv = CKR_OK; + int i; + + if (!count) + return CKR_ARGUMENTS_BAD; + + _p11_lock (); + + if (!gl.mappings) { + rv = CKR_CRYPTOKI_NOT_INITIALIZED; + } else { + index = 0; + + /* Go through and build up a map */ + for (i = 0; i < gl.n_mappings; ++i) { + mapping = &gl.mappings[i]; + + /* Skip ones without a token if requested */ + if (token_present) { + rv = (mapping->funcs->C_GetSlotInfo) (mapping->real_slot, &info); + if (rv != CKR_OK) + break; + if (!(info.flags & CKF_TOKEN_PRESENT)) + continue; + } + + /* Fill in the slot if we can */ + if (slot_list && *count > index) + slot_list[index] = mapping->wrap_slot; + + ++index; + } + + if (slot_list && *count < index) + rv = CKR_BUFFER_TOO_SMALL; + + *count = index; + } + + _p11_unlock (); + + return rv; +} + +static CK_RV +proxy_C_GetSlotInfo (CK_SLOT_ID id, CK_SLOT_INFO_PTR info) +{ + Mapping map; + CK_RV rv; + + rv = map_slot_to_real (&id, &map); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GetSlotInfo) (id, info); +} + +static CK_RV +proxy_C_GetTokenInfo (CK_SLOT_ID id, CK_TOKEN_INFO_PTR info) +{ + Mapping map; + CK_RV rv; + + rv = map_slot_to_real (&id, &map); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GetTokenInfo) (id, info); +} + +static CK_RV +proxy_C_GetMechanismList (CK_SLOT_ID id, CK_MECHANISM_TYPE_PTR mechanism_list, + CK_ULONG_PTR count) +{ + Mapping map; + CK_RV rv; + + rv = map_slot_to_real (&id, &map); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GetMechanismList) (id, mechanism_list, count); +} + +static CK_RV +proxy_C_GetMechanismInfo (CK_SLOT_ID id, CK_MECHANISM_TYPE type, + CK_MECHANISM_INFO_PTR info) +{ + Mapping map; + CK_RV rv; + + rv = map_slot_to_real (&id, &map); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GetMechanismInfo) (id, type, info); +} + +static CK_RV +proxy_C_InitToken (CK_SLOT_ID id, CK_UTF8CHAR_PTR pin, CK_ULONG pin_len, CK_UTF8CHAR_PTR label) +{ + Mapping map; + CK_RV rv; + + rv = map_slot_to_real (&id, &map); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_InitToken) (id, pin, pin_len, label); +} + +static CK_RV +proxy_C_WaitForSlotEvent (CK_FLAGS flags, CK_SLOT_ID_PTR slot, CK_VOID_PTR reserved) +{ + return CKR_FUNCTION_NOT_SUPPORTED; +} + +static CK_RV +proxy_C_OpenSession (CK_SLOT_ID id, CK_FLAGS flags, CK_VOID_PTR user_data, + CK_NOTIFY callback, CK_SESSION_HANDLE_PTR handle) +{ + Session *sess; + Mapping map; + CK_RV rv; + + if (handle == NULL) + return CKR_ARGUMENTS_BAD; + + rv = map_slot_to_real (&id, &map); + if (rv != CKR_OK) + return rv; + + rv = (map.funcs->C_OpenSession) (id, flags, user_data, callback, handle); + + if (rv == CKR_OK) { + _p11_lock (); + + if (!gl.sessions) { + /* + * The underlying module should have returned an error, so this + * code should never be reached with properly behaving modules. + * That's why we don't cleanup and close the newly opened session here + * or anything like that. + */ + rv = CKR_CRYPTOKI_NOT_INITIALIZED; + + } else { + sess = calloc (1, sizeof (Session)); + sess->wrap_slot = map.wrap_slot; + sess->real_session = *handle; + sess->wrap_session = ++gl.last_handle; /* TODO: Handle wrapping, and then collisions */ + hash_set (gl.sessions, &sess->wrap_session, sess); + *handle = sess->wrap_session; + } + + _p11_unlock (); + } + + return rv; +} + +static CK_RV +proxy_C_CloseSession (CK_SESSION_HANDLE handle) +{ + CK_SESSION_HANDLE key; + Mapping map; + CK_RV rv; + + key = handle; + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + rv = (map.funcs->C_CloseSession) (handle); + + if (rv == CKR_OK) { + _p11_lock (); + + if (gl.sessions) + hash_remove (gl.sessions, &key); + + _p11_unlock (); + } + + return rv; +} + +static CK_RV +proxy_C_CloseAllSessions (CK_SLOT_ID id) +{ + CK_SESSION_HANDLE_PTR to_close; + CK_RV rv = CKR_OK; + Session *sess; + CK_ULONG i, count = 0; + hash_iter_t iter; + + _p11_lock (); + + if (!gl.sessions) { + rv = CKR_CRYPTOKI_NOT_INITIALIZED; + } else { + to_close = calloc (sizeof (CK_SESSION_HANDLE), hash_count (gl.sessions)); + if (!to_close) { + rv = CKR_HOST_MEMORY; + } else { + hash_iterate (gl.sessions, &iter); + count = 0; + while (hash_next (&iter, NULL, (void**)&sess)) { + if (sess->wrap_slot == id && to_close) + to_close[count++] = sess->wrap_session; + } + } + } + + _p11_unlock (); + + if (rv != CKR_OK) + return rv; + + for (i = 0; i < count; ++i) + proxy_C_CloseSession (to_close[i]); + + free (to_close); + return CKR_OK; +} + +static CK_RV +proxy_C_GetFunctionStatus (CK_SESSION_HANDLE handle) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GetFunctionStatus) (handle); +} + +static CK_RV +proxy_C_CancelFunction (CK_SESSION_HANDLE handle) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_CancelFunction) (handle); +} + +static CK_RV +proxy_C_GetSessionInfo (CK_SESSION_HANDLE handle, CK_SESSION_INFO_PTR info) +{ + Mapping map; + CK_RV rv; + + if (info == NULL) + return CKR_ARGUMENTS_BAD; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + + rv = (map.funcs->C_GetSessionInfo) (handle, info); + if (rv == CKR_OK) + info->slotID = map.wrap_slot; + + return rv; +} + +static CK_RV +proxy_C_InitPIN (CK_SESSION_HANDLE handle, CK_UTF8CHAR_PTR pin, CK_ULONG pin_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + + return (map.funcs->C_InitPIN) (handle, pin, pin_len); +} + +static CK_RV +proxy_C_SetPIN (CK_SESSION_HANDLE handle, CK_UTF8CHAR_PTR old_pin, CK_ULONG old_pin_len, + CK_UTF8CHAR_PTR new_pin, CK_ULONG new_pin_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + + return (map.funcs->C_SetPIN) (handle, old_pin, old_pin_len, new_pin, new_pin_len); +} + +static CK_RV +proxy_C_GetOperationState (CK_SESSION_HANDLE handle, CK_BYTE_PTR operation_state, CK_ULONG_PTR operation_state_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GetOperationState) (handle, operation_state, operation_state_len); +} + +static CK_RV +proxy_C_SetOperationState (CK_SESSION_HANDLE handle, CK_BYTE_PTR operation_state, + CK_ULONG operation_state_len, CK_OBJECT_HANDLE encryption_key, + CK_OBJECT_HANDLE authentication_key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_SetOperationState) (handle, operation_state, operation_state_len, encryption_key, authentication_key); +} + +static CK_RV +proxy_C_Login (CK_SESSION_HANDLE handle, CK_USER_TYPE user_type, + CK_UTF8CHAR_PTR pin, CK_ULONG pin_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + + return (map.funcs->C_Login) (handle, user_type, pin, pin_len); +} + +static CK_RV +proxy_C_Logout (CK_SESSION_HANDLE handle) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_Logout) (handle); +} + +static CK_RV +proxy_C_CreateObject (CK_SESSION_HANDLE handle, CK_ATTRIBUTE_PTR template, + CK_ULONG count, CK_OBJECT_HANDLE_PTR new_object) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + + return (map.funcs->C_CreateObject) (handle, template, count, new_object); +} + +static CK_RV +proxy_C_CopyObject (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_PTR template, CK_ULONG count, + CK_OBJECT_HANDLE_PTR new_object) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_CopyObject) (handle, object, template, count, new_object); +} + +static CK_RV +proxy_C_DestroyObject (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DestroyObject) (handle, object); +} + +static CK_RV +proxy_C_GetObjectSize (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object, + CK_ULONG_PTR size) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GetObjectSize) (handle, object, size); +} + +static CK_RV +proxy_C_GetAttributeValue (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_PTR template, CK_ULONG count) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GetAttributeValue) (handle, object, template, count); +} + +static CK_RV +proxy_C_SetAttributeValue (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_PTR template, CK_ULONG count) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_SetAttributeValue) (handle, object, template, count); +} + +static CK_RV +proxy_C_FindObjectsInit (CK_SESSION_HANDLE handle, CK_ATTRIBUTE_PTR template, + CK_ULONG count) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_FindObjectsInit) (handle, template, count); +} + +static CK_RV +proxy_C_FindObjects (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE_PTR objects, + CK_ULONG max_count, CK_ULONG_PTR count) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_FindObjects) (handle, objects, max_count, count); +} + +static CK_RV +proxy_C_FindObjectsFinal (CK_SESSION_HANDLE handle) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_FindObjectsFinal) (handle); +} + +static CK_RV +proxy_C_EncryptInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_OBJECT_HANDLE key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_EncryptInit) (handle, mechanism, key); +} + +static CK_RV +proxy_C_Encrypt (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, + CK_BYTE_PTR encrypted_data, CK_ULONG_PTR encrypted_data_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_Encrypt) (handle, data, data_len, encrypted_data, encrypted_data_len); +} + +static CK_RV +proxy_C_EncryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, + CK_ULONG part_len, CK_BYTE_PTR encrypted_part, + CK_ULONG_PTR encrypted_part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_EncryptUpdate) (handle, part, part_len, encrypted_part, encrypted_part_len); +} + +static CK_RV +proxy_C_EncryptFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR last_part, + CK_ULONG_PTR last_part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_EncryptFinal) (handle, last_part, last_part_len); +} + +static CK_RV +proxy_C_DecryptInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_OBJECT_HANDLE key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DecryptInit) (handle, mechanism, key); +} + +static CK_RV +proxy_C_Decrypt (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_data, + CK_ULONG enc_data_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_Decrypt) (handle, enc_data, enc_data_len, data, data_len); +} + +static CK_RV +proxy_C_DecryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_part, + CK_ULONG enc_part_len, CK_BYTE_PTR part, CK_ULONG_PTR part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DecryptUpdate) (handle, enc_part, enc_part_len, part, part_len); +} + +static CK_RV +proxy_C_DecryptFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR last_part, + CK_ULONG_PTR last_part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DecryptFinal) (handle, last_part, last_part_len); +} + +static CK_RV +proxy_C_DigestInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DigestInit) (handle, mechanism); +} + +static CK_RV +proxy_C_Digest (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, + CK_BYTE_PTR digest, CK_ULONG_PTR digest_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_Digest) (handle, data, data_len, digest, digest_len); +} + +static CK_RV +proxy_C_DigestUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, CK_ULONG part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DigestUpdate) (handle, part, part_len); +} + +static CK_RV +proxy_C_DigestKey (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DigestKey) (handle, key); +} + +static CK_RV +proxy_C_DigestFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR digest, + CK_ULONG_PTR digest_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DigestFinal) (handle, digest, digest_len); +} + +static CK_RV +proxy_C_SignInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_OBJECT_HANDLE key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_SignInit) (handle, mechanism, key); +} + +static CK_RV +proxy_C_Sign (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, + CK_BYTE_PTR signature, CK_ULONG_PTR signature_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_Sign) (handle, data, data_len, signature, signature_len); +} + +static CK_RV +proxy_C_SignUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, CK_ULONG part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_SignUpdate) (handle, part, part_len); +} + +static CK_RV +proxy_C_SignFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR signature, + CK_ULONG_PTR signature_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_SignFinal) (handle, signature, signature_len); +} + +static CK_RV +proxy_C_SignRecoverInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_OBJECT_HANDLE key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_SignRecoverInit) (handle, mechanism, key); +} + +static CK_RV +proxy_C_SignRecover (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, + CK_BYTE_PTR signature, CK_ULONG_PTR signature_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_SignRecover) (handle, data, data_len, signature, signature_len); +} + +static CK_RV +proxy_C_VerifyInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_OBJECT_HANDLE key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_VerifyInit) (handle, mechanism, key); +} + +static CK_RV +proxy_C_Verify (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len, + CK_BYTE_PTR signature, CK_ULONG signature_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_Verify) (handle, data, data_len, signature, signature_len); +} + +static CK_RV +proxy_C_VerifyUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, CK_ULONG part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_VerifyUpdate) (handle, part, part_len); +} + +static CK_RV +proxy_C_VerifyFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR signature, + CK_ULONG signature_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_VerifyFinal) (handle, signature, signature_len); +} + +static CK_RV +proxy_C_VerifyRecoverInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_OBJECT_HANDLE key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_VerifyRecoverInit) (handle, mechanism, key); +} + +static CK_RV +proxy_C_VerifyRecover (CK_SESSION_HANDLE handle, CK_BYTE_PTR signature, + CK_ULONG signature_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_VerifyRecover) (handle, signature, signature_len, data, data_len); +} + +static CK_RV +proxy_C_DigestEncryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, + CK_ULONG part_len, CK_BYTE_PTR enc_part, + CK_ULONG_PTR enc_part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DigestEncryptUpdate) (handle, part, part_len, enc_part, enc_part_len); +} + +static CK_RV +proxy_C_DecryptDigestUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_part, + CK_ULONG enc_part_len, CK_BYTE_PTR part, + CK_ULONG_PTR part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DecryptDigestUpdate) (handle, enc_part, enc_part_len, part, part_len); +} + +static CK_RV +proxy_C_SignEncryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, + CK_ULONG part_len, CK_BYTE_PTR enc_part, + CK_ULONG_PTR enc_part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_SignEncryptUpdate) (handle, part, part_len, enc_part, enc_part_len); +} + +static CK_RV +proxy_C_DecryptVerifyUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_part, + CK_ULONG enc_part_len, CK_BYTE_PTR part, + CK_ULONG_PTR part_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DecryptVerifyUpdate) (handle, enc_part, enc_part_len, part, part_len); +} + +static CK_RV +proxy_C_GenerateKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_ATTRIBUTE_PTR template, CK_ULONG count, + CK_OBJECT_HANDLE_PTR key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GenerateKey) (handle, mechanism, template, count, key); +} + +static CK_RV +proxy_C_GenerateKeyPair (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_ATTRIBUTE_PTR pub_template, CK_ULONG pub_count, + CK_ATTRIBUTE_PTR priv_template, CK_ULONG priv_count, + CK_OBJECT_HANDLE_PTR pub_key, CK_OBJECT_HANDLE_PTR priv_key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GenerateKeyPair) (handle, mechanism, pub_template, pub_count, priv_template, priv_count, pub_key, priv_key); +} + +static CK_RV +proxy_C_WrapKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_OBJECT_HANDLE wrapping_key, CK_OBJECT_HANDLE key, + CK_BYTE_PTR wrapped_key, CK_ULONG_PTR wrapped_key_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_WrapKey) (handle, mechanism, wrapping_key, key, wrapped_key, wrapped_key_len); +} + +static CK_RV +proxy_C_UnwrapKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_OBJECT_HANDLE unwrapping_key, CK_BYTE_PTR wrapped_key, + CK_ULONG wrapped_key_len, CK_ATTRIBUTE_PTR template, + CK_ULONG count, CK_OBJECT_HANDLE_PTR key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_UnwrapKey) (handle, mechanism, unwrapping_key, wrapped_key, wrapped_key_len, template, count, key); +} + +static CK_RV +proxy_C_DeriveKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism, + CK_OBJECT_HANDLE base_key, CK_ATTRIBUTE_PTR template, + CK_ULONG count, CK_OBJECT_HANDLE_PTR key) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_DeriveKey) (handle, mechanism, base_key, template, count, key); +} + +static CK_RV +proxy_C_SeedRandom (CK_SESSION_HANDLE handle, CK_BYTE_PTR seed, CK_ULONG seed_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_SeedRandom) (handle, seed, seed_len); +} + +static CK_RV +proxy_C_GenerateRandom (CK_SESSION_HANDLE handle, CK_BYTE_PTR random_data, + CK_ULONG random_len) +{ + Mapping map; + CK_RV rv; + + rv = map_session_to_real (&handle, &map, NULL); + if (rv != CKR_OK) + return rv; + return (map.funcs->C_GenerateRandom) (handle, random_data, random_len); +} + +/* -------------------------------------------------------------------- + * MODULE ENTRY POINT + */ + +static CK_FUNCTION_LIST proxy_function_list = { + { CRYPTOKI_VERSION_MAJOR, CRYPTOKI_VERSION_MINOR }, /* version */ + proxy_C_Initialize, + proxy_C_Finalize, + proxy_C_GetInfo, + proxy_C_GetFunctionList, + proxy_C_GetSlotList, + proxy_C_GetSlotInfo, + proxy_C_GetTokenInfo, + proxy_C_GetMechanismList, + proxy_C_GetMechanismInfo, + proxy_C_InitToken, + proxy_C_InitPIN, + proxy_C_SetPIN, + proxy_C_OpenSession, + proxy_C_CloseSession, + proxy_C_CloseAllSessions, + proxy_C_GetSessionInfo, + proxy_C_GetOperationState, + proxy_C_SetOperationState, + proxy_C_Login, + proxy_C_Logout, + proxy_C_CreateObject, + proxy_C_CopyObject, + proxy_C_DestroyObject, + proxy_C_GetObjectSize, + proxy_C_GetAttributeValue, + proxy_C_SetAttributeValue, + proxy_C_FindObjectsInit, + proxy_C_FindObjects, + proxy_C_FindObjectsFinal, + proxy_C_EncryptInit, + proxy_C_Encrypt, + proxy_C_EncryptUpdate, + proxy_C_EncryptFinal, + proxy_C_DecryptInit, + proxy_C_Decrypt, + proxy_C_DecryptUpdate, + proxy_C_DecryptFinal, + proxy_C_DigestInit, + proxy_C_Digest, + proxy_C_DigestUpdate, + proxy_C_DigestKey, + proxy_C_DigestFinal, + proxy_C_SignInit, + proxy_C_Sign, + proxy_C_SignUpdate, + proxy_C_SignFinal, + proxy_C_SignRecoverInit, + proxy_C_SignRecover, + proxy_C_VerifyInit, + proxy_C_Verify, + proxy_C_VerifyUpdate, + proxy_C_VerifyFinal, + proxy_C_VerifyRecoverInit, + proxy_C_VerifyRecover, + proxy_C_DigestEncryptUpdate, + proxy_C_DecryptDigestUpdate, + proxy_C_SignEncryptUpdate, + proxy_C_DecryptVerifyUpdate, + proxy_C_GenerateKey, + proxy_C_GenerateKeyPair, + proxy_C_WrapKey, + proxy_C_UnwrapKey, + proxy_C_DeriveKey, + proxy_C_SeedRandom, + proxy_C_GenerateRandom, + proxy_C_GetFunctionStatus, + proxy_C_CancelFunction, + proxy_C_WaitForSlotEvent +}; + +CK_RV +C_GetFunctionList (CK_FUNCTION_LIST_PTR_PTR list) +{ + return proxy_C_GetFunctionList (list); +} diff --git a/p11-kit/uri.c b/p11-kit/uri.c new file mode 100644 index 0000000..14d00b1 --- /dev/null +++ b/p11-kit/uri.c @@ -0,0 +1,1337 @@ +/* + * Copyright (C) 2011 Collabora Ltd. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * 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. + * * The names of contributors to this software may not be + * used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 + * COPYRIGHT OWNER 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. + * + * Author: Stef Walter + */ + +#include "config.h" + +#define DEBUG_FLAG DEBUG_URI +#include "debug.h" +#include "pkcs11.h" +#include "uri.h" +#include "util.h" + +#include +#include +#include +#include +#include + +/** + * SECTION:p11-kit-uri + * @title: URIs + * @short_description: Parsing and formatting PKCS\#11 URIs + * + * PKCS\#11 URIs can be used in configuration files or applications to represent + * PKCS\#11 modules, tokens or objects. An example of a URI might be: + * + * + * pkcs11:token=The\%20Software\%20PKCS\#11\%20softtoken; + * manufacturer=Snake\%20Oil,\%20Inc.;serial=;object=my-certificate; + * model=1.0;objecttype=cert;id=\%69\%95\%3e\%5c\%f4\%bd\%ec\%91 + * + * + * You can use p11_kit_uri_parse() to parse such a URI, and p11_kit_uri_format() + * to build one. URIs are represented by the #P11KitUri structure. You can match + * a parsed URI against PKCS\#11 tokens with p11_kit_uri_match_token_info() + * or attributes with p11_kit_uri_match_attributes(). + * + * Since URIs can represent different sorts of things, when parsing or formatting + * a URI a 'context' can be used to indicate which sort of URI is expected. + * + * URIs have an unrecognized flag. This flag is set during parsing + * if any parts of the URI are not recognized. This may be because the part is + * from a newer version of the PKCS\#11 spec or because that part was not valid + * inside of the desired context used when parsing. + */ + +/** + * P11KitUri: + * + * A structure representing a PKCS\#11 URI. There are no public fields + * visible in this structure. Use the various accessor functions. + */ + +/** + * P11KitUriType: + * @P11_KIT_URI_IS_MODULE: The URI represents one or more modules + * @P11_KIT_URI_IS_TOKEN: The URI represents one or more tokens + * @P11_KIT_URI_IS_OBJECT: The URI represents one or more objects + * @P11_KIT_URI_IS_ANY: The URI can represent anything + * + * A PKCS\#11 URI can represent different kinds of things. This flag is used by + * p11_kit_uri_parse() to denote in what context the URI will be used. + */ + +/** + * P11KitUriResult: + * @P11_KIT_URI_OK: Success + * @P11_KIT_URI_NO_MEMORY: Memory allocation failed + * @P11_KIT_URI_BAD_SCHEME: The URI had a bad scheme + * @P11_KIT_URI_BAD_ENCODING: The URI had a bad encoding + * @P11_KIT_URI_BAD_SYNTAX: The URI had a bad syntax + * @P11_KIT_URI_BAD_VERSION: The URI contained a bad version number + * @P11_KIT_URI_NOT_FOUND: A requested part of the URI was not found + * + * Error codes returned by various functions. The functions each clearly state + * which error codes they are capable of returning. + */ + +/** + * P11_KIT_URI_SCHEME: + * + * String of URI scheme for PKCS\#11 URIs. + */ + +/** + * P11_KIT_URI_SCHEME_LEN: + * + * Length of %P11_KIT_URI_SCHEME. + */ + +static const CK_ATTRIBUTE_TYPE SUPPORTED_ATTRIBUTE_TYPES[] = { + CKA_CLASS, + CKA_LABEL, + CKA_ID +}; + +#define NUM_ATTRIBUTE_TYPES \ + (sizeof (SUPPORTED_ATTRIBUTE_TYPES) / sizeof (SUPPORTED_ATTRIBUTE_TYPES[0])) + +struct _P11KitUri { + int unrecognized; + CK_INFO module; + CK_TOKEN_INFO token; + CK_ATTRIBUTE attributes[NUM_ATTRIBUTE_TYPES]; + CK_ULONG n_attributes; + char *pinfile; +}; + +const static char HEX_CHARS[] = "0123456789abcdef"; + +static int +url_decode (const char *value, const char *end, + unsigned char** output, size_t *length) +{ + char *a, *b; + unsigned char *result, *p; + + assert (output); + assert (value <= end); + + /* String can only get shorter */ + result = malloc ((end - value) + 1); + if (!result) + return P11_KIT_URI_NO_MEMORY; + + /* Now loop through looking for escapes */ + p = result; + while (value != end) { + /* + * A percent sign followed by two hex digits means + * that the digits represent an escaped character. + */ + if (*value == '%') { + value++; + if (value + 2 > end) { + free (result); + return P11_KIT_URI_BAD_ENCODING; + } + a = strchr (HEX_CHARS, tolower (value[0])); + b = strchr (HEX_CHARS, tolower (value[1])); + if (!a || !b) { + free (result); + return P11_KIT_URI_BAD_ENCODING; + } + *p = (a - HEX_CHARS) << 4; + *(p++) |= (b - HEX_CHARS); + value += 2; + } else { + *(p++) = *(value++); + } + } + + /* Null terminate string, in case its a string */ + *p = 0; + + if (length) + *length = p - result; + *output = result; + return P11_KIT_URI_OK; +} + +static char* +url_encode (const unsigned char *value, const unsigned char *end, size_t *length) +{ + char *p; + char *result; + + assert (value <= end); + + /* Just allocate for worst case */ + result = malloc (((end - value) * 3) + 1); + if (!result) + return NULL; + + /* Now loop through looking for escapes */ + p = result; + while (value != end) { + + /* These characters we let through verbatim */ + if (*value && (isalnum (*value) || strchr ("_-.", *value) != NULL)) { + *(p++) = *(value++); + + /* All others get encoded */ + } else { + *(p++) = '%'; + *(p++) = HEX_CHARS[((unsigned char)*value) >> 4]; + *(p++) = HEX_CHARS[((unsigned char)*value) & 0x0F]; + ++value; + } + } + + *p = 0; + if (length) + *length = p - result; + return result; +} + +static int +match_struct_string (const unsigned char *inuri, const unsigned char *real, + size_t length) +{ + assert (inuri); + assert (real); + assert (length > 0); + + /* NULL matches anything */ + if (inuri[0] == 0) + return 1; + + return memcmp (inuri, real, length) == 0 ? 1 : 0; +} + +static int +match_struct_version (CK_VERSION_PTR inuri, CK_VERSION_PTR real) +{ + /* This matches anything */ + if (inuri->major == (CK_BYTE)-1 && inuri->minor == (CK_BYTE)-1) + return 1; + + return memcmp (inuri, real, sizeof (CK_VERSION)); +} + +/** + * p11_kit_uri_get_module_info: + * @uri: the URI + * + * Get the CK_INFO structure associated with this URI. + * + * If this is a parsed URI, then the fields corresponding to library parts of + * the URI will be filled in. Any library URI parts that were missing will have + * their fields filled with zeros. + * + * If the caller wishes to setup information for building a URI, then relevant + * fields should be filled in. Fields that should not appear as parts in the + * resulting URI should be filled with zeros. + * + * Returns: A pointer to the CK_INFO structure. + */ +CK_INFO_PTR +p11_kit_uri_get_module_info (P11KitUri *uri) +{ + assert (uri); + return &uri->module; +} + +/** + * p11_kit_uri_match_module_info: + * @uri: the URI + * @info: the structure to match against the URI + * + * Match a CK_INFO structure against the library parts of this URI. + * + * Only the fields of the CK_INFO structure that are valid for use + * in a URI will be matched. A URI part that was not specified in the URI will + * match any value in the structure. If during the URI parsing any unrecognized + * parts were encountered then this match will fail. + * + * Returns: 1 if the URI matches, 0 if not. + */ +int +p11_kit_uri_match_module_info (P11KitUri *uri, CK_INFO_PTR info) +{ + assert (uri); + assert (info); + + if (uri->unrecognized) + return 0; + + return (match_struct_string (uri->module.libraryDescription, + info->libraryDescription, + sizeof (info->libraryDescription)) && + match_struct_string (uri->module.manufacturerID, + info->manufacturerID, + sizeof (info->manufacturerID)) && + match_struct_version (&uri->module.libraryVersion, + &info->libraryVersion)); +} + +/** + * p11_kit_uri_get_token_info: + * @uri: the URI + * + * Get the CK_TOKEN_INFO structure associated with this URI. + * + * If this is a parsed URI, then the fields corresponding to token parts of + * the URI will be filled in. Any token URI parts that were missing will have + * their fields filled with zeros. + * + * If the caller wishes to setup information for building a URI, then relevant + * fields should be filled in. Fields that should not appear as parts in the + * resulting URI should be filled with zeros. + * + * Returns: A pointer to the CK_INFO structure. + */ +CK_TOKEN_INFO_PTR +p11_kit_uri_get_token_info (P11KitUri *uri) +{ + assert (uri); + return &uri->token; +} + +/** + * p11_kit_uri_match_token_info: + * @uri: the URI + * @token_info: the structure to match against the URI + * + * Match a CK_TOKEN_INFO structure against the token parts of this + * URI. + * + * Only the fields of the CK_TOKEN_INFO structure that are valid + * for use in a URI will be matched. A URI part that was not specified in the + * URI will match any value in the structure. If during the URI parsing any + * unrecognized parts were encountered then this match will fail. + * + * Returns: 1 if the URI matches, 0 if not. + */ +int +p11_kit_uri_match_token_info (P11KitUri *uri, CK_TOKEN_INFO_PTR token_info) +{ + assert (uri); + assert (token_info); + + if (uri->unrecognized) + return 0; + + return (match_struct_string (uri->token.label, + token_info->label, + sizeof (token_info->label)) && + match_struct_string (uri->token.manufacturerID, + token_info->manufacturerID, + sizeof (token_info->manufacturerID)) && + match_struct_string (uri->token.model, + token_info->model, + sizeof (token_info->model)) && + match_struct_string (uri->token.serialNumber, + token_info->serialNumber, + sizeof (token_info->serialNumber))); +} + +/** + * p11_kit_uri_get_attribute: + * @uri: The URI + * @attr_type: The attribute type + * + * Get a pointer to an attribute present in this URI. + * + * Returns: A pointer to the attribute, or NULL if not present. + * The attribute is owned by the URI and should not be freed. + */ +CK_ATTRIBUTE_PTR +p11_kit_uri_get_attribute (P11KitUri *uri, CK_ATTRIBUTE_TYPE attr_type) +{ + CK_ULONG i; + + assert (uri); + + for (i = 0; i < uri->n_attributes; i++) { + if (uri->attributes[i].type == attr_type) + return &uri->attributes[i]; + } + + return NULL; +} + +static void +uri_take_attribute (P11KitUri *uri, CK_ATTRIBUTE_PTR attr) +{ + CK_ULONG i; + + assert (uri); + assert (attr); + + /* Replace an attribute already set */ + for (i = 0; i < uri->n_attributes; i++) { + if (uri->attributes[i].type == attr->type) { + free (uri->attributes[i].pValue); + memcpy (&uri->attributes[i], attr, sizeof (CK_ATTRIBUTE)); + memset (attr, 0, sizeof (CK_ATTRIBUTE)); + return; + } + } + + /* Add one at the end */ + assert (uri->n_attributes < NUM_ATTRIBUTE_TYPES); + memcpy (&uri->attributes[uri->n_attributes], attr, sizeof (CK_ATTRIBUTE)); + memset (attr, 0, sizeof (CK_ATTRIBUTE)); + uri->n_attributes++; +} + +/** + * p11_kit_uri_set_attribute: + * @uri: The URI + * @attr: The attribute to set + * + * Set an attribute on the URI. + * + * Only attributes that map to parts in a PKCS\#11 URI will be accepted. + * + * Returns: %P11_KIT_URI_OK if the attribute was successfully set. + * %P11_KIT_URI_NOT_FOUND if the attribute was not valid for a URI. + * %P11_KIT_URI_NO_MEMORY if allocation failed. + */ +int +p11_kit_uri_set_attribute (P11KitUri *uri, CK_ATTRIBUTE_PTR attr) +{ + CK_ATTRIBUTE copy; + CK_ULONG i; + + assert (uri); + assert (attr); + + /* Make sure the attribute type is valid */ + for (i = 0; i < NUM_ATTRIBUTE_TYPES; i++) { + if (SUPPORTED_ATTRIBUTE_TYPES[i] == attr->type) + break; + } + if (i == NUM_ATTRIBUTE_TYPES) + return P11_KIT_URI_NOT_FOUND; + + memcpy (©, attr, sizeof (CK_ATTRIBUTE)); + + /* Duplicate the value */ + if (attr->pValue && attr->ulValueLen && attr->ulValueLen != (CK_ULONG)-1) { + copy.pValue = malloc (attr->ulValueLen); + if (!copy.pValue) + return P11_KIT_URI_NO_MEMORY; + memcpy (copy.pValue, attr->pValue, attr->ulValueLen); + } + + uri_take_attribute (uri, ©); + return P11_KIT_URI_OK; +} + +/** + * p11_kit_uri_clear_attribute: + * @uri: The URI + * @attr_type: The type of the attribute to clear + * + * Clear an attribute on the URI. + * + * Only attributes that map to parts in a PKCS\#11 URI will be accepted. + * + * Returns: %P11_KIT_URI_OK if the attribute was successfully cleared. + * %P11_KIT_URI_NOT_FOUND if the attribute was not valid for a URI. + */ +int +p11_kit_uri_clear_attribute (P11KitUri *uri, CK_ATTRIBUTE_TYPE attr_type) +{ + CK_ATTRIBUTE_PTR clear = NULL; + CK_ATTRIBUTE_PTR last; + CK_ULONG i; + + assert (uri); + + /* Make sure the attribute type is valid */ + for (i = 0; i < NUM_ATTRIBUTE_TYPES; i++) { + if (SUPPORTED_ATTRIBUTE_TYPES[i] == attr_type) + break; + } + if (i == NUM_ATTRIBUTE_TYPES) + return P11_KIT_URI_NOT_FOUND; + + /* Cleanup the values in the attribute */ + for (i = 0; i < uri->n_attributes; i++) { + if (uri->attributes[i].type == attr_type) { + clear = &uri->attributes[i]; + free (uri->attributes[i].pValue); + break; + } + } + + /* A valid attribute, but not present */ + if (clear == NULL) + return P11_KIT_URI_OK; + + assert (uri->n_attributes > 0); + uri->n_attributes--; + + /* If not the last attribute, then make last take its place */ + last = &uri->attributes[uri->n_attributes]; + if (clear != last) { + memcpy (clear, last, sizeof (CK_ATTRIBUTE)); + clear = last; + } + + memset (clear, 0, sizeof (CK_ATTRIBUTE)); + return P11_KIT_URI_OK; +} + +/** + * p11_kit_uri_get_attribute_types: + * @uri: The URI + * @n_attrs: A location to store the number of attributes returned. + * + * Get the attributes present in this URI. The attributes and values are + * owned by the URI. If the URI is modified, then the attributes that were + * returned from this function will not remain consistent. + * + * Returns: The attributes for this URI. These are owned by the URI. + */ +CK_ATTRIBUTE_PTR +p11_kit_uri_get_attributes (P11KitUri *uri, CK_ULONG_PTR n_attrs) +{ + assert (uri); + assert (n_attrs); + + *n_attrs = uri->n_attributes; + return uri->attributes; +} + +int +p11_kit_uri_set_attributes (P11KitUri *uri, CK_ATTRIBUTE_PTR attrs, + CK_ULONG n_attrs) +{ + CK_ULONG i; + int ret; + + assert (uri); + + p11_kit_uri_clear_attributes (uri); + + for (i = 0; i < n_attrs; i++) { + ret = p11_kit_uri_set_attribute (uri, &attrs[i]); + if (ret != P11_KIT_URI_OK && ret != P11_KIT_URI_NOT_FOUND) + return ret; + } + + return P11_KIT_URI_OK; +} + +void +p11_kit_uri_clear_attributes (P11KitUri *uri) +{ + CK_ULONG i; + + assert (uri); + + for (i = 0; i < uri->n_attributes; i++) + free (uri->attributes[i].pValue); + uri->n_attributes = 0; +} + + +static int +match_attributes (CK_ATTRIBUTE_PTR one, CK_ATTRIBUTE_PTR two) +{ + assert (one); + assert (two); + + if (one->type != two->type) + return 0; + if (one->ulValueLen != two->ulValueLen) + return 0; + if (one->pValue == two->pValue) + return 1; + if (!one->pValue || !two->pValue) + return 0; + return memcmp (one->pValue, two->pValue, one->ulValueLen) == 0; +} + +/** + * p11_kit_uri_match_attributes: + * @uri: The URI + * @attrs: The attributes to match + * @n_attrs: The number of attributes + * + * Match a attributes against the object parts of this URI. + * + * Only the attributes that are valid for use in a URI will be matched. A URI + * part that was not specified in the URI will match any attribute value. If + * during the URI parsing any unrecognized parts were encountered then this + * match will fail. + * + * Returns: 1 if the URI matches, 0 if not. + */ +int +p11_kit_uri_match_attributes (P11KitUri *uri, CK_ATTRIBUTE_PTR attrs, + CK_ULONG n_attrs) +{ + CK_ULONG j; + CK_ULONG i; + + assert (uri); + assert (attrs || !n_attrs); + + if (uri->unrecognized) + return 0; + + for (i = 0; i < uri->n_attributes; i++) { + for (j = 0; j < n_attrs; ++j) { + if (uri->attributes[i].type == attrs[j].type) { + if (!match_attributes (&uri->attributes[i], &attrs[j])) + return 0; + break; + } + } + } + + return 1; +} + +/** + * p11_kit_uri_set_unrecognized: + * @uri: The URI + * @unrecognized: The new unregognized flag value + * + * Set the unrecognized flag on this URI. + * + * The unrecognized flag is automatically set to 1 when during parsing any part + * of the URI is unrecognized. If the unrecognized flag is set to 1, then + * matching against this URI will always fail. + */ +void +p11_kit_uri_set_unrecognized (P11KitUri *uri, int unrecognized) +{ + assert (uri); + uri->unrecognized = unrecognized; +} + +/** + * p11_kit_uri_any_unrecognized: + * @uri: The URI + * + * Get the unrecognized flag for this URI. + * + * The unrecognized flag is automatically set to 1 when during parsing any part + * of the URI is unrecognized. If the unrecognized flag is set to 1, then + * matching against this URI will always fail. + * + * Returns: 1 if unrecognized flag is set, 0 otherwise. + */ +int +p11_kit_uri_any_unrecognized (P11KitUri *uri) +{ + assert (uri); + return uri->unrecognized; +} + +/** + * p11_kit_uri_get_pinfile: + * @uri: The URI + * + * Get the 'pinfile' part of the URI. This is used by some applications to + * lookup a PIN for logging into a PKCS\#11 token. + * + * Returns: The pinfile or %NULL if not present. + */ +const char* +p11_kit_uri_get_pinfile (P11KitUri *uri) +{ + assert (uri); + return uri->pinfile; +} + +/** + * p11_kit_uri_set_pinfile: + * @uri: The URI + * @pinfile: The new pinfile + * + * Set the 'pinfile' part of the URI. This is used by some applications to + * lookup a PIN for logging into a PKCS\#11 token. + */ +void +p11_kit_uri_set_pinfile (P11KitUri *uri, const char *pinfile) +{ + assert (uri); + free (uri->pinfile); + uri->pinfile = strdup (pinfile); +} + +/** + * p11_kit_uri_new: + * + * Create a new blank PKCS\#11 URI. + * + * The new URI is in the right state to parse a string into. All relevant fields + * are zeroed out. Formatting this URI will produce a valid but empty URI. + * + * Returns: A newly allocated URI. This should be freed with p11_kit_uri_free(). + */ +P11KitUri* +p11_kit_uri_new (void) +{ + P11KitUri *uri; + + uri = calloc (1, sizeof (P11KitUri)); + if (!uri) + return NULL; + + /* So that it matches anything */ + uri->module.libraryVersion.major = (CK_BYTE)-1; + uri->module.libraryVersion.minor = (CK_BYTE)-1; + + return uri; +} + +static size_t +space_strlen (const unsigned char *string, size_t max_length) +{ + size_t i = max_length - 1; + + assert (string); + + while (i > 0 && string[i] == ' ') + --i; + return i + 1; +} + +static int +format_raw_string (char **string, size_t *length, int *is_first, + const char *name, const char *value) +{ + size_t namelen; + size_t vallen; + + /* Not set */ + if (!value) + return 1; + + namelen = strlen (name); + vallen = strlen (value); + + *string = xrealloc (*string, *length + namelen + vallen + 3); + if (!*string) + return 0; + + if (!*is_first) + (*string)[(*length)++] = ';'; + memcpy ((*string) + *length, name, namelen); + *length += namelen; + (*string)[(*length)++] = '='; + memcpy ((*string) + *length, value, vallen); + *length += vallen; + (*string)[*length] = 0; + *is_first = 0; + + return 1; +} + +static int +format_encode_string (char **string, size_t *length, int *is_first, + const char *name, const unsigned char *value, + size_t n_value) +{ + char *encoded; + int ret; + + encoded = url_encode (value, value + n_value, NULL); + if (!encoded) + return 0; + + ret = format_raw_string (string, length, is_first, name, encoded); + free (encoded); + return ret; +} + + +static int +format_struct_string (char **string, size_t *length, int *is_first, + const char *name, const unsigned char *value, + size_t value_max) +{ + size_t len; + + /* Not set */ + if (!value[0]) + return 1; + + len = space_strlen (value, value_max); + return format_encode_string (string, length, is_first, name, value, len); +} + +static int +format_attribute_string (char **string, size_t *length, int *is_first, + const char *name, CK_ATTRIBUTE_PTR attr) +{ + /* Not set */; + if (attr == NULL) + return 1; + + return format_encode_string (string, length, is_first, name, + attr->pValue, attr->ulValueLen); +} + +static int +format_attribute_class (char **string, size_t *length, int *is_first, + const char *name, CK_ATTRIBUTE_PTR attr) +{ + CK_OBJECT_CLASS klass; + const char *value; + + /* Not set */; + if (attr == NULL) + return 1; + + klass = *((CK_OBJECT_CLASS*)attr->pValue); + switch (klass) { + case CKO_DATA: + value = "data"; + break; + case CKO_SECRET_KEY: + value = "secretkey"; + break; + case CKO_CERTIFICATE: + value = "cert"; + break; + case CKO_PUBLIC_KEY: + value = "public"; + break; + case CKO_PRIVATE_KEY: + value = "private"; + break; + default: + return 1; + } + + return format_raw_string (string, length, is_first, name, value); +} + +static int +format_struct_version (char **string, size_t *length, int *is_first, + const char *name, CK_VERSION_PTR version) +{ + char buffer[64]; + + /* Not set */ + if (version->major == (CK_BYTE)-1 && version->minor == (CK_BYTE)-1) + return 1; + + snprintf (buffer, sizeof (buffer), "%d.%d", + (int)version->major, (int)version->minor); + return format_raw_string (string, length, is_first, name, buffer); +} + +/** + * p11_kit_uri_format: + * @uri: The URI. + * @uri_type: The type of URI that should be produced. + * @string: Location to store a newly allocated string. + * + * Format a PKCS\#11 URI into a string. + * + * Fields which are zeroed out will not be included in the resulting string. + * Attributes which are not present will also not be included. + * + * The uri_type of URI specified limits the different parts of the resulting + * URI. To format a URI containing all possible information use + * %P11_KIT_URI_IS_ANY + * + * The resulting string should be freed with free(). + * + * Returns: %P11_KIT_URI_OK if the URI was formatted successfully. + * %P11_KIT_URI_NO_MEMORY if memory allocation failed. + */ +int +p11_kit_uri_format (P11KitUri *uri, P11KitUriType uri_type, char **string) +{ + char *result = NULL; + size_t length = 0; + int is_first = 1; + + result = malloc (128); + if (!result) + return P11_KIT_URI_NO_MEMORY; + + length = P11_KIT_URI_SCHEME_LEN; + memcpy (result, P11_KIT_URI_SCHEME, length); + result[length] = 0; + + if (uri_type & P11_KIT_URI_IS_MODULE) { + if (!format_struct_string (&result, &length, &is_first, "library-description", + uri->module.libraryDescription, + sizeof (uri->module.libraryDescription)) || + !format_struct_version (&result, &length, &is_first, "library-version", + &uri->module.libraryVersion) || + !format_struct_string (&result, &length, &is_first, "library-manufacturer", + uri->module.manufacturerID, + sizeof (uri->module.manufacturerID))) { + free (result); + return P11_KIT_URI_NO_MEMORY; + } + } + + if (uri_type & P11_KIT_URI_IS_TOKEN) { + if (!format_struct_string (&result, &length, &is_first, "model", + uri->token.model, + sizeof (uri->token.model)) || + !format_struct_string (&result, &length, &is_first, "manufacturer", + uri->token.manufacturerID, + sizeof (uri->token.manufacturerID)) || + !format_struct_string (&result, &length, &is_first, "serial", + uri->token.serialNumber, + sizeof (uri->token.serialNumber)) || + !format_struct_string (&result, &length, &is_first, "token", + uri->token.label, + sizeof (uri->token.label))) { + free (result); + return P11_KIT_URI_NO_MEMORY; + } + } + + if (uri_type & P11_KIT_URI_IS_OBJECT) { + if (!format_attribute_string (&result, &length, &is_first, "id", + p11_kit_uri_get_attribute (uri, CKA_ID)) || + !format_attribute_string (&result, &length, &is_first, "object", + p11_kit_uri_get_attribute (uri, CKA_LABEL))) { + free (result); + return P11_KIT_URI_NO_MEMORY; + } + + if (!format_attribute_class (&result, &length, &is_first, "objecttype", + p11_kit_uri_get_attribute (uri, CKA_CLASS))) { + free (result); + return P11_KIT_URI_NO_MEMORY; + } + } + + if (uri->pinfile) { + format_encode_string (&result, &length, &is_first, "pinfile", + (const unsigned char*)uri->pinfile, + strlen (uri->pinfile)); + } + + *string = result; + return P11_KIT_URI_OK; +} + +static int +parse_string_attribute (const char *name, const char *start, const char *end, + P11KitUri *uri) +{ + unsigned char *value; + CK_ATTRIBUTE attr; + size_t length; + int ret; + + assert (start <= end); + + if (strcmp ("id", name) == 0) + attr.type = CKA_ID; + else if (strcmp ("object", name) == 0) + attr.type = CKA_LABEL; + else + return 0; + + ret = url_decode (start, end, &value, &length); + if (ret < 0) + return ret; + + attr.pValue = value; + attr.ulValueLen = length; + uri_take_attribute (uri, &attr); + return 1; +} + +static int +equals_segment (const char *start, const char *end, const char *match) +{ + size_t len = strlen (match); + assert (start <= end); + return (end - start == len) && memcmp (start, match, len) == 0; +} + +static int +parse_class_attribute (const char *name, const char *start, const char *end, + P11KitUri *uri) +{ + CK_OBJECT_CLASS klass = 0; + CK_ATTRIBUTE attr; + + assert (start <= end); + + if (strcmp ("objecttype", name) != 0) + return 0; + + if (equals_segment (start, end, "cert")) + klass = CKO_CERTIFICATE; + else if (equals_segment (start, end, "public")) + klass = CKO_PUBLIC_KEY; + else if (equals_segment (start, end, "private")) + klass = CKO_PRIVATE_KEY; + else if (equals_segment (start, end, "secretkey")) + klass = CKO_SECRET_KEY; + else if (equals_segment (start, end, "data")) + klass = CKO_DATA; + else { + uri->unrecognized = 1; + return 1; + } + + attr.pValue = malloc (sizeof (klass)); + if (attr.pValue == NULL) + return P11_KIT_URI_NO_MEMORY; + + memcpy (attr.pValue, &klass, sizeof (klass)); + attr.ulValueLen = sizeof (klass); + attr.type = CKA_CLASS; + + uri_take_attribute (uri, &attr); + return 1; +} + +static int +parse_struct_info (unsigned char *where, size_t length, const char *start, + const char *end, P11KitUri *uri) +{ + unsigned char *value; + size_t value_length; + int ret; + + assert (start <= end); + + ret = url_decode (start, end, &value, &value_length); + if (ret < 0) + return ret; + + /* Too long, shouldn't match anything */ + if (value_length > length) { + free (value); + uri->unrecognized = 1; + return 1; + } + + memset (where, ' ', length); + memcpy (where, value, value_length); + + free (value); + return 1; +} + +static int +parse_token_info (const char *name, const char *start, const char *end, + P11KitUri *uri) +{ + unsigned char *where; + size_t length; + + assert (start <= end); + + if (strcmp (name, "model") == 0) { + where = uri->token.model; + length = sizeof (uri->token.model); + } else if (strcmp (name, "manufacturer") == 0) { + where = uri->token.manufacturerID; + length = sizeof (uri->token.manufacturerID); + } else if (strcmp (name, "serial") == 0) { + where = uri->token.serialNumber; + length = sizeof (uri->token.serialNumber); + } else if (strcmp (name, "token") == 0) { + where = uri->token.label; + length = sizeof (uri->token.label); + } else { + return 0; + } + + return parse_struct_info (where, length, start, end, uri); +} + +static int +atoin (const char *start, const char *end) +{ + int ret = 0; + while (start != end) { + if (*start < '0' || *start > '9') + return -1; + ret *= 10; + ret += (*start - '0'); + ++start; + } + return ret; +} + +static int +parse_struct_version (const char *start, const char *end, CK_VERSION_PTR version) +{ + const char *dot; + int val; + + assert (start <= end); + + dot = memchr (start, '.', end - start); + if (!dot) + dot = end; + + if (dot == start) + return P11_KIT_URI_BAD_VERSION; + val = atoin (start, dot); + if (val < 0 || val >= 255) + return P11_KIT_URI_BAD_VERSION; + version->major = (CK_BYTE)val; + version->minor = 0; + + if (dot != end) { + if (dot + 1 == end) + return P11_KIT_URI_BAD_VERSION; + val = atoin (dot + 1, end); + if (val < 0 || val >= 255) + return P11_KIT_URI_BAD_VERSION; + version->minor = (CK_BYTE)val; + } + + return 1; +} + +static int +parse_module_info (const char *name, const char *start, const char *end, + P11KitUri *uri) +{ + unsigned char *where; + size_t length; + + assert (start <= end); + + if (strcmp (name, "library-description") == 0) { + where = uri->module.libraryDescription; + length = sizeof (uri->module.libraryDescription); + } else if (strcmp (name, "library-manufacturer") == 0) { + where = uri->module.manufacturerID; + length = sizeof (uri->module.manufacturerID); + } else if (strcmp (name, "library-version") == 0) { + return parse_struct_version (start, end, + &uri->module.libraryVersion); + } else { + return 0; + } + + return parse_struct_info (where, length, start, end, uri); +} + +static int +parse_extra_info (const char *name, const char *start, const char *end, + P11KitUri *uri) +{ + unsigned char *pinfile; + int ret; + + assert (start <= end); + + if (strcmp (name, "pinfile") == 0) { + ret = url_decode (start, end, &pinfile, NULL); + if (ret < 0) + return ret; + free (uri->pinfile); + uri->pinfile = (char*)pinfile; + return 1; + } + + return 0; +} + +/** + * p11_kit_uri_parse: + * @string: The string to parse + * @uri_type: The type of URI that is expected + * @uri: The blank URI to parse the values into + * + * Parse a PKCS\#11 URI string. + * + * PKCS\#11 URIs can represent tokens, objects or modules. The uri_type argument + * allows the caller to specify what type of URI is expected and the sorts of + * objects the URI should match. %P11_KIT_URI_IS_ANY can be used to parse a URI + * for any context. It's then up to the caller to make sense of the way that + * it is used. + * + * If the PKCS\#11 URI contains unrecognized URI parts or parts not applicable + * to the specified context, then the unrecognized flag will be set. This will + * prevent the URI from matching using the various match functions. + * + * Returns: %P11_KIT_URI_OK if the URI was parsed successfully. + * %P11_KIT_URI_BAD_SCHEME if this was not a PKCS\#11 URI. + * %P11_KIT_URI_BAD_SYNTAX if the URI syntax was bad. + * %P11_KIT_URI_NO_MEMORY if memory allocation failed. + * %P11_KIT_URI_BAD_VERSION if a version number was bad. + * %P11_KIT_URI_BAD_ENCODING if the URI encoding was invalid. + */ +int +p11_kit_uri_parse (const char *string, P11KitUriType uri_type, + P11KitUri *uri) +{ + const char *spos, *epos; + char *key = NULL; + int ret = -1; + int i; + + assert (string); + assert (uri); + + if (strncmp (string, P11_KIT_URI_SCHEME, P11_KIT_URI_SCHEME_LEN) != 0) + return P11_KIT_URI_BAD_SCHEME; + + string += P11_KIT_URI_SCHEME_LEN; + + /* Clear everything out */ + memset (&uri->module, 0, sizeof (uri->module)); + memset (&uri->token, 0, sizeof (uri->module)); + for (i = 0; i < uri->n_attributes; ++i) { + free (uri->attributes[i].pValue); + memset (&uri->attributes[i], 0, sizeof (CK_ATTRIBUTE)); + } + uri->n_attributes = 0; + uri->module.libraryVersion.major = (CK_BYTE)-1; + uri->module.libraryVersion.minor = (CK_BYTE)-1; + uri->unrecognized = 0; + free (uri->pinfile); + uri->pinfile = NULL; + + for (;;) { + spos = strchr (string, ';'); + if (spos == NULL) { + spos = string + strlen (string); + assert (*spos == '\0'); + if (spos == string) + break; + } + + epos = strchr (string, '='); + if (epos == NULL || spos == string || epos == string || epos >= spos) + return P11_KIT_URI_BAD_SYNTAX; + + key = malloc ((epos - string) + 1); + if (key == NULL) + return P11_KIT_URI_NO_MEMORY; + memcpy (key, string, epos - string); + key[epos - string] = 0; + epos++; + + ret = 0; + if (uri_type & P11_KIT_URI_IS_OBJECT) + ret = parse_string_attribute (key, epos, spos, uri); + if (ret == 0 && uri_type & P11_KIT_URI_IS_OBJECT) + ret = parse_class_attribute (key, epos, spos, uri); + if (ret == 0 && uri_type & P11_KIT_URI_IS_TOKEN) + ret = parse_token_info (key, epos, spos, uri); + if (ret == 0 && uri_type & P11_KIT_URI_IS_MODULE) + ret = parse_module_info (key, epos, spos, uri); + if (ret == 0) + ret = parse_extra_info (key, epos, spos, uri); + free (key); + + if (ret < 0) + return ret; + if (ret == 0) + uri->unrecognized = 1; + + if (*spos == '\0') + break; + string = spos + 1; + } + + return P11_KIT_URI_OK; +} + +/** + * p11_kit_uri_free: + * @uri: The URI + * + * Free a PKCS\#11 URI. + */ +void +p11_kit_uri_free (P11KitUri *uri) +{ + int i; + + if (!uri) + return; + + for (i = 0; i < uri->n_attributes; ++i) + free (uri->attributes[i].pValue); + + free (uri); +} + +/** + * p11_kit_uri_message: + * @code: The error code + * + * Lookup a message for the uri error code. These codes are the P11_KIT_URI_XXX + * error codes that can be returned from p11_kit_uri_parse() or + * p11_kit_uri_format(). As a special case %NULL, will be returned for + * %P11_KIT_URI_OK. + * + * Returns: The message for the error code. This string is owned by the p11-kit + * library. + */ +const char* +p11_kit_uri_message (int code) +{ + switch (code) { + case P11_KIT_URI_OK: + return NULL; + case P11_KIT_URI_NO_MEMORY: + return "Out of memory"; + case P11_KIT_URI_BAD_SCHEME: + return "URI scheme must be 'pkcs11:'"; + case P11_KIT_URI_BAD_ENCODING: + return "URI encoding invalid or corrupted"; + case P11_KIT_URI_BAD_SYNTAX: + return "URI syntax is invalid"; + case P11_KIT_URI_BAD_VERSION: + return "URI version component is invalid"; + case P11_KIT_URI_NOT_FOUND: + return "The URI component was not found"; + default: + debug ("unknown error code: %d", code); + return "Unknown error"; + } +} diff --git a/p11-kit/uri.h b/p11-kit/uri.h new file mode 100644 index 0000000..1cf5c00 --- /dev/null +++ b/p11-kit/uri.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2011 Collabora Ltd. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * 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. + * * The names of contributors to this software may not be + * used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 + * COPYRIGHT OWNER 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. + * + * Author: Stef Walter + */ + +#ifndef P11_KIT_URI_H +#define P11_KIT_URI_H + +/* + * To use this API, you need to be prepared for changes to the API, + * and add the C flag: -DP11_KIT_API_SUBJECT_TO_CHANGE + */ + +#ifndef P11_KIT_API_SUBJECT_TO_CHANGE +#error "This API has not yet reached stability." +#endif + +#include "p11-kit/pkcs11.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define P11_KIT_URI_SCHEME "pkcs11:" +#define P11_KIT_URI_SCHEME_LEN 7 + +typedef enum { + P11_KIT_URI_OK = 0, + P11_KIT_URI_NO_MEMORY = -1, + P11_KIT_URI_BAD_SCHEME = -2, + P11_KIT_URI_BAD_ENCODING = -3, + P11_KIT_URI_BAD_SYNTAX = -4, + P11_KIT_URI_BAD_VERSION = -5, + P11_KIT_URI_NOT_FOUND = -6, +} P11KitUriResult; + +typedef enum { + P11_KIT_URI_IS_MODULE = (1 << 1), + P11_KIT_URI_IS_TOKEN = (1 << 2) | P11_KIT_URI_IS_MODULE, + P11_KIT_URI_IS_OBJECT = (1 << 3) | P11_KIT_URI_IS_TOKEN, + P11_KIT_URI_IS_ANY = 0x0000FFFF, +} P11KitUriType; + +typedef struct _P11KitUri P11KitUri; + +CK_INFO_PTR p11_kit_uri_get_module_info (P11KitUri *uri); + +int p11_kit_uri_match_module_info (P11KitUri *uri, + CK_INFO_PTR info); + +CK_TOKEN_INFO_PTR p11_kit_uri_get_token_info (P11KitUri *uri); + +int p11_kit_uri_match_token_info (P11KitUri *uri, + CK_TOKEN_INFO_PTR token_info); + +CK_ATTRIBUTE_PTR p11_kit_uri_get_attribute (P11KitUri *uri, + CK_ATTRIBUTE_TYPE attr_type); + +int p11_kit_uri_set_attribute (P11KitUri *uri, + CK_ATTRIBUTE_PTR attr); + +int p11_kit_uri_clear_attribute (P11KitUri *uri, + CK_ATTRIBUTE_TYPE attr_type); + +CK_ATTRIBUTE_PTR p11_kit_uri_get_attributes (P11KitUri *uri, + CK_ULONG *n_attrs); + +int p11_kit_uri_set_attributes (P11KitUri *uri, + CK_ATTRIBUTE_PTR attrs, + CK_ULONG n_attrs); + +void p11_kit_uri_clear_attributes (P11KitUri *uri); + +int p11_kit_uri_match_attributes (P11KitUri *uri, + CK_ATTRIBUTE_PTR attrs, + CK_ULONG n_attrs); + +const char* p11_kit_uri_get_pinfile (P11KitUri *uri); + +void p11_kit_uri_set_pinfile (P11KitUri *uri, + const char *pinfile); + +void p11_kit_uri_set_unrecognized (P11KitUri *uri, + int unrecognized); + +int p11_kit_uri_any_unrecognized (P11KitUri *uri); + +P11KitUri* p11_kit_uri_new (void); + +int p11_kit_uri_format (P11KitUri *uri, + P11KitUriType uri_type, + char **string); + +int p11_kit_uri_parse (const char *string, + P11KitUriType uri_type, + P11KitUri *uri); + +void p11_kit_uri_free (P11KitUri *uri); + +const char* p11_kit_uri_message (int code); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* P11_KIT_URI_H */ -- cgit v1.1