9f8d002a665cb12a5236883c697ea1f1c96409b8Evan Hunt-my $usage="Usage: Configure [no-<cipher> ...] [enable-<cipher> ...] [experimental-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [enable-montasm] [no-asm] [no-dso] [no-krb5] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--test-sanity]
os/compiler[:flags]\n";
ab023a65562e62b85a824509d829b6fad87e00b1Rob Austein+my $usage="Usage: Configure --pk11-libname=PK11_LIB_LOCATION --pk11-flavor=FLAVOR [no-<cipher> ...] [enable-<cipher> ...] [experimental-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [enable-montasm] [no-asm] [no-dso] [no-krb5] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--test-sanity]
os/compiler[:flags]\n";
96754ed7b400ce080279de2f92111ad868105290Bob Halley-"linux-elf", "gcc:-DL_ENDIAN -DTERMIO -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
96754ed7b400ce080279de2f92111ad868105290Bob Halley+"linux-elf", "gcc:-DL_ENDIAN -DTERMIO -O3 -fomit-frame-pointer -Wall::-D_REENTRANT -pthread::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
96754ed7b400ce080279de2f92111ad868105290Bob Halley "linux-generic64","gcc:-DTERMIO -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
96754ed7b400ce080279de2f92111ad868105290Bob Halley-"linux-x86_64", "gcc:-m64 -DL_ENDIAN -DTERMIO -O3 -Wall -DMD32_REG_T=int::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
96754ed7b400ce080279de2f92111ad868105290Bob Halley+"linux-x86_64", "gcc:-m64 -DL_ENDIAN -DTERMIO -O3 -Wall -DMD32_REG_T=int::-D_REENTRANT -pthread::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
+The previous key naming scheme was kept for backward compatibility.
+The PKCS#11 engine exists in two flavors, crypto-accelerator and
+sign-only. The first one is from the Solaris patch and uses the
+PKCS#11 device for all crypto operations it supports. The second
+is a stripped down version which provides only the useful
+function (
i.e., signature with a RSA private key in the device
+protected key store and key loading).
+As a hint PKCS#11 boards should use the crypto-accelerator flavor,
+external PKCS#11 devices the sign-only. SCA 6000 is an example
+of the first, AEP Keyper of the second.
+Note it is mandatory to set a pk11-flavor (and only one) in
+It is highly recommended to compile in (vs. as a DSO) the engine.
+The way to configure this is system dependent, on Unixes it is no-shared
+(and is in general the default), on WIN32 it is enable-static-engine
+(and still enable to build the OpenSSL libraries as DLLs).
+PKCS#11 engine support for OpenSSL 0.9.8l
+=========================================
+Revisions of the patch for 0.9.8 branch
+This patch containing code available in OpenSolaris adds support for PKCS#11
+engine into OpenSSL and implements PKCS#11 v2.20. It is to be applied against
+OpenSSL 0.9.8l source code distribution as shipped by
OpenSSL.Org. Your system
+must provide PKCS#11 backend otherwise the patch is useless. You provide the
+PKCS#11 library name during the build configuration phase, see below.
+Patch can be applied like this:
+ # NOTE: use gtar if on Solaris
+ # now download the patch to the current directory
+ # NOTE: must use gpatch if on Solaris (is part of the system)
+It is designed to support pure acceleration for RSA, DSA, DH and all the
+symetric ciphers and message digest algorithms that PKCS#11 and OpenSSL share
+except for missing support for patented algorithms MDC2, RC3, RC5 and IDEA.
+According to the PKCS#11 providers installed on your machine, it can support
+ RSA, DSA, DH, RAND, DES-CBC, DES-EDE3-CBC, DES-ECB, DES-EDE3, RC4,
+ AES-128-CBC, AES-192-CBC, AES-256-CBC, AES-128-ECB, AES-192-ECB,
+ AES-256-ECB, AES-128-CTR, AES-192-CTR, AES-256-CTR, MD5, SHA1, SHA224,
+Note that for AES counter mode the application must provide their own EVP
+functions since OpenSSL doesn't support counter mode through EVP yet. You may
+see OpenSSH source code (
cipher.c) to get the idea how to do that. SunSSH is an
+example of code that uses the PKCS#11 engine and deals with the fork-safety
+You must provide the location of PKCS#11 library in your system to the
+configure script. You will be instructed to do that when you try to run the
+ Operating system: i86pc-whatever-solaris2
+ Configuring for solaris-x86-cc
+ You must set --pk11-libname for PKCS#11 library.
+Taking openCryptoki project on Linux AMD64 box as an example, you would run
+configure script like this:
+To check whether newly built openssl really supports PKCS#11 it's enough to run
+"
apps/openssl engine" and look for "(pkcs11) PKCS #11 engine support" in the
+output. If you see no PKCS#11 engine support check that the built openssl binary
+and the PKCS#11 library from --pk11-libname don't conflict on 32/64 bits.
+The patch, during various phases of development, was tested on Solaris against
+PKCS#11 engine available from Solaris Cryptographic Framework (Solaris 10 and
+OpenSolaris) and also on Linux using PKCS#11 libraries from openCryptoki project
+information). Some Linux distributions even ship those libraries with the
+system. The patch should work on any system that is supported by OpenSSL itself
+and has functional PKCS#11 library.
+The patch contains "RSA Security Inc. PKCS #11 Cryptographic Token Interface
+copyrighted by RSA Security Inc., see
pkcs11.h for more information.
+Other
added/modified code in this patch is copyrighted by Sun Microsystems,
+Inc. and is released under the OpenSSL license (see LICENSE file for more
+Revisions of the patch for 0.9.8 branch
+=======================================
+- adjusted for OpenSSL version 0.9.8l
+ 6732677 make check to trigger Solaris specific code automatic in the
+- adjusted for OpenSSL version 0.9.8j
+-
README.pkcs11 moved out of the patch, and is shipped together with it in a
+ tarball instead so that it can be read before the patch is applied.
+ 6804216 pkcs#11 engine should support a key length range for RC4
+ 6734038 Apache SSL web server using the pkcs11 engine fails to start if
+- fixed bugs and RFEs (most of the work done by Vladimir Kotal)
+ 6723504 more granular locking in PKCS#11 engine
+ 6667128 CRYPTO_LOCK_PK11_ENGINE assumption does not hold true
+ 6710420 PKCS#11 engine source should be lint clean
+ 6747327 PKCS#11 engine atfork handlers need to be aware of guys who take
+ 6746712 PKCS#11 engine source code should be cstyle clean
+ 6731380 return codes of several functions are not checked in the PKCS#11
+ 6746735 PKCS#11 engine should use extended FILE space API
+ 6734038 Apache SSL web server using the pkcs11 engine fails to start if
+ 6731839 OpenSSL PKCS#11 engine no longer uses n2cp for symmetric ciphers
+- Solaris specific code for slot selection made automatic
+- update the patch to OpenSSL 0.9.8h version
+ 6545665 make CKM_AES_CTR available to non-kernel users
+- fixed bugs in the engine code:
+ 6602801 PK11_SESSION cache has to employ reference counting scheme for
+ asymmetric key operations
+ 6605538 pkcs11 functions C_FindObjects[{Init,Final}]() not called
+ 6607307 pkcs#11 engine can't read RSA private keys
+ 6652362 pk11_RSA_finish() is cutting corners
+ 6662112 pk11_destroy_{rsa,dsa,dh}_key_objects() use locking in
+ 6666625 pk11_destroy_{rsa,dsa,dh}_key_objects() should be more
+ resilient to destroy failures
+ 6667273 OpenSSL engine should not use free() but OPENSSL_free()
+ 6670363 PKCS#11 engine fails to reuse existing symmetric keys
+ 6678135 memory corruption in pk11_DH_generate_key() in pkcs#11 engine
+ 6678503 DSA signature conversion in pk11_dsa_do_verify() ignores size
+ of big numbers leading to failures
+ 6706562 pk11_DH_compute_key() returns 0 in case of failure instead of
+ 6706622 pk11_load_{pub,priv}key create corrupted RSA key references
+ 6707129 return values from BN_new() in pk11_DH_generate_key() are not
+ 6707274
DSA/RSA/DH PKCS#11 engine operations need to be resistant to
+ 6707782 OpenSSL PKCS#11 engine pretends to be aware of
+ OPENSSL_NO_{RSA,DSA,DH}
+ defines but fails miserably
+ 6709966 make check_new_*() to return values to indicate cache
hit/miss+ 6705200 pk11_dh struct initialization in PKCS#11 engine is missing
+ generate_params parameter
+ 6709513 PKCS#11 engine sets IV length even for ECB modes
+ 6728296 buffer length not initialized for C_(En|De)crypt_Final() in the
+ 6728871 PKCS#11 engine must reset global_session in pk11_finish()
+- new features and enhancements:
+ 6562155 OpenSSL pkcs#11 engine needs support for SHA224/256/384/512
+ 6685012 OpenSSL pkcs#11 engine needs support for new cipher modes
+ 6725903 OpenSSL PKCS#11 engine shouldn't use soft token for symmetric
+- update for 0.9.8f version
+- update for "6607670 teach pkcs#11 engine how to use keys be reference"
+- draft for "6607670 teach pkcs#11 engine how to use keys be reference"
+- draft for "6607307 pkcs#11 engine can't read RSA private keys"
+- 6375348 Using pkcs11 as the SSLCryptoDevice with
Apache/OpenSSL causes
+ significant performance drop
+- 6573196 memory is leaked when OpenSSL is used with PKCS#11 engine
+- 6558630 race in OpenSSL pkcs11 engine when using symetric block ciphers
+- initial patch for 0.9.8e using latest OpenSolaris code
+(1) my build failed on Linux distro with this error:
+
hw_pk11.c:(.text+0x20f5): undefined reference to `pthread_atfork'
+ - don't use "no-threads" when configuring
+ - if you didn't then OpenSSL failed to create a threaded library by
+ default. You may manually edit Configure and try again. Look for the
+ architecture that Configure printed, for example:
+Configured for linux-elf.
+ - then edit Configure, find string "linux-elf" (inluding the quotes),
+ and add flags to support threads to the 4th column of the 2nd string.
+ If you build with GCC then adding "-pthread" should be enough. With
+ "linux-elf" as an example, you would add " -pthread" right after
+ "-D_REENTRANT", like this:
+....-O3 -fomit-frame-pointer -Wall::-D_REENTRANT -pthread::-ldl:.....
+(2) I'm using
MinGW/MSYS environment and get undeclared reference error for
+pthread_atfork() function when trying to build OpenSSL with the patch.
+ Sorry, pthread_atfork() is not implemented in the current pthread-win32
+ (as of Nov 2009). You can not use the patch there.
+Please send feedback to security-discuss@opensolaris.org. The patch was
+created by Jan.Pechanec@Sun.COM from code available in OpenSolaris.
#endif /* OPENSSL_DOING_MAKEDEPEND */
+# define OPENSSL_THREADS
#ifndef OPENSSL_NO_DYNAMIC_ENGINE
# define OPENSSL_NO_DYNAMIC_ENGINE
+#define OPENSSL_CPUID_OBJ
#ifdef OPENSSL_DOING_MAKEDEPEND
* This enables code handling data aligned at natural CPU word
+#define RC4_CHUNK unsigned long
/* If this is set to 'unsigned int' on a DEC Alpha, this gives about a
* %20 speed up (longs are 8 bytes, int's are 4). */
-#define DES_LONG unsigned long
+#define DES_LONG unsigned int
/* The prime number generation stuff may not work when
* EIGHT_BIT but I don't care since I've only used this mode
* for debuging the bignum libraries */
-#undef SIXTY_FOUR_BIT_LONG
+#define SIXTY_FOUR_BIT_LONG
#if defined(HEADER_BF_LOCL_H) && !defined(CONFIG_HEADER_BF_LOCL_H)
#define CONFIG_HEADER_BF_LOCL_H
#endif /* HEADER_BF_LOCL_H */
#if defined(HEADER_DES_LOCL_H) && !defined(CONFIG_HEADER_DES_LOCL_H)
/* Unroll the inner loop, this sometimes helps, sometimes hinders.
* Very mucy CPU dependant */
/* These default values were supplied by
if ((file = fopen(filename, mode)) == NULL) {
SYSerr(SYS_F_FOPEN, get_last_sys_error());
ERR_add_error_data(5, "fopen('", filename, "','", mode, "')");
+ if ((errno == ENOENT) || ((*mode == 'r') && (errno == EACCES)))
BIOerr(BIO_F_BIO_NEW_FILE, BIO_R_NO_SUCH_FILE);
BIOerr(BIO_F_BIO_NEW_FILE, ERR_R_SYS_LIB);
+ * The contents of this file are subject to the terms of the
+ * Common Development and Distribution License, Version 1.0 only
+ * (the "License"). You may not use this file except in compliance
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * When distributing Covered Code, include this CDDL HEADER in each
+ * If applicable, add the following below this CDDL HEADER, with the
+ * fields enclosed by brackets "[]" replaced with your own identifying
+ * information: Portions Copyright [yyyy] [name of copyright owner]
+ * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
+#ifndef CK_DEFINE_FUNCTION
+#define CK_DEFINE_FUNCTION(returnType, name) returnType name
+#ifndef CK_DECLARE_FUNCTION
+#define CK_DECLARE_FUNCTION(returnType, name) returnType name
+#ifndef CK_DECLARE_FUNCTION_POINTER
+#define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType (* name)
+#ifndef CK_CALLBACK_FUNCTION
+#define CK_CALLBACK_FUNCTION(returnType, name) returnType (* name)
+ *
pkcs11t.h defines TRUE and FALSE in a way that upsets lint
+#ifndef CK_DISABLE_TRUE_FALSE
+#define CK_DISABLE_TRUE_FALSE
+#endif /* CK_DISABLE_TRUE_FALSE */
+#undef CK_PKCS11_FUNCTION_INFO
+/* Solaris specific functions */
+ * SUNW_C_GetMechSession will initialize the framework and do all
+ * the necessary PKCS#11 calls to create a session capable of
+ * providing operations on the requested mechanism
+CK_RV SUNW_C_GetMechSession(CK_MECHANISM_TYPE mech,
+ CK_SESSION_HANDLE_PTR hSession);
+ * SUNW_C_KeyToObject will create a secret key object for the given
+ * mechanism from the rawkey data.
+CK_RV SUNW_C_KeyToObject(CK_SESSION_HANDLE hSession,
+ CK_MECHANISM_TYPE mech, const void *rawkey, size_t rawkey_len,
+ CK_OBJECT_HANDLE_PTR obj);
+#endif /* _CRYPTOKI_H */
# if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(HAVE_CRYPTODEV)
+# ifndef OPENSSL_NO_HW_PKCS11
+# ifndef OPENSSL_NO_HW_PKCS11CA
+# ifndef OPENSSL_NO_HW_PKCS11SO
void ENGINE_load_cryptodev(void);
void ENGINE_load_padlock(void);
void ENGINE_load_builtin_engines(void);
+# ifndef OPENSSL_NO_HW_PKCS11CA
+void ENGINE_load_pk11ca(void);
+# ifndef OPENSSL_NO_HW_PKCS11SO
+void ENGINE_load_pk11so(void);
* Get and set global flags (ENGINE_TABLE_FLAG_***) for the implementation
+ * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
+ * This product includes software developed by the OpenSSL Project for
+ * ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project. All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation
and/or other materials provided with the
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * licensing@OpenSSL.org.
+ * 5. Products derived from this software may not be called "OpenSSL"
+ * nor may "OpenSSL" appear in their names without prior written
+ * permission of the OpenSSL Project.
+ * 6. Redistributions of any form whatsoever must retain the following
+ * "This product includes software developed by the OpenSSL Project
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com). This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+#ifdef OPENSSL_SYS_WIN32
+#define getpid() GetCurrentProcessId()
+#define CK_DEFINE_FUNCTION(returnType, name) \
+ returnType __declspec(dllexport) name
+#define CK_DECLARE_FUNCTION(returnType, name) \
+ returnType __declspec(dllimport) name
+#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ returnType __declspec(dllimport) (* name)
+/* for pthread error check on Linuxes */
+#ifndef OPENSSL_NO_HW_PK11
+#ifndef OPENSSL_NO_HW_PK11CA
+/* label for debug messages printed on stderr */
+#define PK11_DBG "PKCS#11 ENGINE DEBUG"
+/* prints a lot of debug messages on stderr about slot selection process */
+/* #undef DEBUG_SLOT_SELECTION */
+ * Solaris specific code. See comment at check_hw_mechanisms() for more
+#if defined(__SVR4) && defined(__sun)
+#undef SOLARIS_HW_SLOT_SELECTION
+ * AES counter mode is not supported in the OpenSSL EVP API yet and neither
+ * there are official OIDs for mechanisms based on this mode. With our changes,
+ * an application can define its own EVP calls for AES counter mode and then
+ * it can make use of hardware acceleration through this engine. However, it's
+ * better if we keep AES CTR support code under ifdef's.
+#ifdef OPENSSL_SYS_WIN32
+#pragma pack(push, cryptoki, 1)
+#pragma pack(pop, cryptoki)
+ * NIDs for AES counter mode that will be defined during the engine
+static int NID_aes_128_ctr = NID_undef;
+static int NID_aes_192_ctr = NID_undef;
+static int NID_aes_256_ctr = NID_undef;
+#endif /* SOLARIS_AES_CTR */
+ * We use this lock to prevent multiple C_Login()s, guard getpassphrase(),
+ * uri_struct manipulation, and static token info. All of that is used by the
+ * RSA keys by reference feature.
+pthread_mutex_t *token_lock;
+#ifdef SOLARIS_HW_SLOT_SELECTION
+ * Tables for symmetric ciphers and digest mechs found in the pkcs11_kernel
+ * library. See comment at check_hw_mechanisms() for more information.
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+/* PKCS#11 session caches and their locks for all operation types */
+static PK11_CACHE session_cache[OP_MAX];
+ * We cache the flags so that we do not have to run C_GetTokenInfo() again when
+ * logging into the token.
+CK_FLAGS pubkey_token_flags;
+ * As stated in v2.20, 11.7 Object Management Function, in section for
+ * C_FindObjectsInit(), at most one search operation may be active at a given
+ * time in a given session. Therefore, C_Find{,Init,Final}Objects() should be
+ * grouped together to form one atomic search operation. This is already
+ * ensured by the property of unique PKCS#11 session handle used for each
+ * This is however not the biggest concern - maintaining consistency of the
+ * underlying object store is more important. The same section of the spec also
+ * says that one thread can be in the middle of a search operation while another
+ * thread destroys the object matching the search template which would result in
+ * invalid handle returned from the search operation.
+ * Hence, the following locks are used for both protection of the object stores.
+ * They are also used for active list protection.
+pthread_mutex_t *find_lock[OP_MAX] = { NULL };
+ * lists of asymmetric key handles which are active (referenced by at least one
+ * PK11_SESSION structure, either held by a thread or present in free_session
+ * list) for given algorithm type
+PK11_active *active_list[OP_MAX] = { NULL };
+ * Create all secret key objects in a global session so that they are available
+ * to use for other sessions. These other sessions may be opened or closed
+ * without losing the secret key objects.
+static CK_SESSION_HANDLE global_session = CK_INVALID_HANDLE;
+/* ENGINE level stuff */
+static int pk11_init(ENGINE *e);
+static int pk11_library_init(ENGINE *e);
+static int pk11_finish(ENGINE *e);
+static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void));
+static int pk11_destroy(ENGINE *e);
+static void pk11_rand_seed(const void *buf, int num);
+static void pk11_rand_add(const void *buf, int num, double add_entropy);
+static void pk11_rand_cleanup(void);
+static int pk11_rand_bytes(unsigned char *buf, int num);
+static int pk11_rand_status(void);
+/* These functions are also used in other files */
+PK11_SESSION *pk11_get_session(PK11_OPTYPE optype);
+void pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype);
+/* active list manipulation functions used in this file */
+extern int pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type);
+extern void pk11_free_active_list(PK11_OPTYPE type);
+int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
+int pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
+int pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
+int pk11_destroy_dsa_key_objects(PK11_SESSION *session);
+int pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
+int pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
+int pk11_destroy_dh_key_objects(PK11_SESSION *session);
+int pk11_destroy_dh_object(PK11_SESSION *session, CK_BBOOL uselock);
+/* Local helper functions */
+static int pk11_free_all_sessions(void);
+static int pk11_free_session_list(PK11_OPTYPE optype);
+static int pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype);
+static int pk11_destroy_cipher_key_objects(PK11_SESSION *session);
+static int pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh,
+static const char *get_PK11_LIBNAME(void);
+static void free_PK11_LIBNAME(void);
+static long set_PK11_LIBNAME(const char *name);
+/* Symmetric cipher and digest support functions */
+static int cipher_nid_to_pk11(int nid);
+static int pk11_add_NID(char *sn, char *ln);
+static int pk11_add_aes_ctr_NIDs(void);
+#endif /* SOLARIS_AES_CTR */
+static int pk11_usable_ciphers(const int **nids);
+static int pk11_usable_digests(const int **nids);
+static int pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
+ const unsigned char *iv, int enc);
+static int pk11_cipher_final(PK11_SESSION *sp);
+#if OPENSSL_VERSION_NUMBER < 0x10000000L
+static int pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ const unsigned char *in, unsigned int inl);
+static int pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ const unsigned char *in, size_t inl);
+static int pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx);
+static int pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
+ const int **nids, int nid);
+static int pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
+ const int **nids, int nid);
+static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
+ const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp);
+static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
+static int md_nid_to_pk11(int nid);
+static int pk11_digest_init(EVP_MD_CTX *ctx);
+static int pk11_digest_update(EVP_MD_CTX *ctx, const void *data,
+static int pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md);
+static int pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from);
+static int pk11_digest_cleanup(EVP_MD_CTX *ctx);
+static int pk11_choose_slots(int *any_slot_found);
+static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist,
+ CK_SLOT_ID current_slot, int *current_slot_n_cipher,
+ int *local_cipher_nids);
+static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
+ CK_SLOT_ID current_slot, int *current_slot_n_digest,
+ int *local_digest_nids);
+static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR, int slot_id,
+ CK_MECHANISM_TYPE mech, int *current_slot_n_cipher, int *local_cipher_nids,
+static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist, int slot_id,
+ CK_MECHANISM_TYPE mech, int *current_slot_n_digest, int *local_digest_nids,
+static int pk11_init_all_locks(void);
+static void pk11_free_all_locks(void);
+#ifdef SOLARIS_HW_SLOT_SELECTION
+static int check_hw_mechanisms(void);
+static int nid_in_table(int nid, int *nid_table);
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+/* Index for the supported ciphers */
+#endif /* SOLARIS_AES_CTR */
+/* Index for the supported digests */
+#define TRY_OBJ_DESTROY(sp, obj_hdl, retval, uselock, alg_type, priv) \
+ LOCK_OBJSTORE(alg_type); \
+ if (pk11_active_delete(obj_hdl, alg_type) == 1) \
+ retval = pk11_destroy_object(sp->session, obj_hdl, \
+ priv ? sp->priv_persistent : sp->pub_persistent); \
+ UNLOCK_OBJSTORE(alg_type); \
+static int cipher_nids[PK11_CIPHER_MAX];
+static int digest_nids[PK11_DIGEST_MAX];
+static int cipher_count = 0;
+static int digest_count = 0;
+static CK_BBOOL pk11_have_rsa = CK_FALSE;
+static CK_BBOOL pk11_have_recover = CK_FALSE;
+static CK_BBOOL pk11_have_dsa = CK_FALSE;
+static CK_BBOOL pk11_have_dh = CK_FALSE;
+static CK_BBOOL pk11_have_random = CK_FALSE;
+typedef struct PK11_CIPHER_st
+ enum pk11_cipher_id id;
+ CK_MECHANISM_TYPE mech_type;
+static PK11_CIPHER ciphers[] =
+ { PK11_DES_CBC, NID_des_cbc, 8, 8, 8,
+ CKK_DES, CKM_DES_CBC, },
+ { PK11_DES3_CBC, NID_des_ede3_cbc, 8, 24, 24,
+ CKK_DES3, CKM_DES3_CBC, },
+ { PK11_DES_ECB, NID_des_ecb, 0, 8, 8,
+ CKK_DES, CKM_DES_ECB, },
+ { PK11_DES3_ECB, NID_des_ede3_ecb, 0, 24, 24,
+ CKK_DES3, CKM_DES3_ECB, },
+ { PK11_RC4, NID_rc4, 0, 16, 256,
+ { PK11_AES_128_CBC, NID_aes_128_cbc, 16, 16, 16,
+ CKK_AES, CKM_AES_CBC, },
+ { PK11_AES_192_CBC, NID_aes_192_cbc, 16, 24, 24,
+ CKK_AES, CKM_AES_CBC, },
+ { PK11_AES_256_CBC, NID_aes_256_cbc, 16, 32, 32,
+ CKK_AES, CKM_AES_CBC, },
+ { PK11_AES_128_ECB, NID_aes_128_ecb, 0, 16, 16,
+ CKK_AES, CKM_AES_ECB, },
+ { PK11_AES_192_ECB, NID_aes_192_ecb, 0, 24, 24,
+ CKK_AES, CKM_AES_ECB, },
+ { PK11_AES_256_ECB, NID_aes_256_ecb, 0, 32, 32,
+ CKK_AES, CKM_AES_ECB, },
+ { PK11_BLOWFISH_CBC, NID_bf_cbc, 8, 16, 16,
+ CKK_BLOWFISH, CKM_BLOWFISH_CBC, },
+ /* we don't know the correct NIDs until the engine is initialized */
+ { PK11_AES_128_CTR, NID_undef, 16, 16, 16,
+ CKK_AES, CKM_AES_CTR, },
+ { PK11_AES_192_CTR, NID_undef, 16, 24, 24,
+ CKK_AES, CKM_AES_CTR, },
+ { PK11_AES_256_CTR, NID_undef, 16, 32, 32,
+ CKK_AES, CKM_AES_CTR, },
+#endif /* SOLARIS_AES_CTR */
+typedef struct PK11_DIGEST_st
+ enum pk11_digest_id id;
+ CK_MECHANISM_TYPE mech_type;
+static PK11_DIGEST digests[] =
+ {PK11_MD5, NID_md5, CKM_MD5, },
+ {PK11_SHA1, NID_sha1, CKM_SHA_1, },
+ {PK11_SHA224, NID_sha224, CKM_SHA224, },
+ {PK11_SHA256, NID_sha256, CKM_SHA256, },
+ {PK11_SHA384, NID_sha384, CKM_SHA384, },
+ {PK11_SHA512, NID_sha512, CKM_SHA512, },
+ {0, NID_undef, 0xFFFF, },
+ * session in multiple cipher_update calls
+typedef struct PK11_CIPHER_STATE_st
+ * libcrypto EVP stuff - this is how we get wired to EVP so the engine gets
+ * called when libcrypto requests a cipher NID.
+ * Note how the PK11_CIPHER_STATE is used here.
+static const EVP_CIPHER pk11_des_cbc =
+ sizeof (PK11_CIPHER_STATE),
+ EVP_CIPHER_set_asn1_iv,
+ EVP_CIPHER_get_asn1_iv,
+static const EVP_CIPHER pk11_3des_cbc =
+ sizeof (PK11_CIPHER_STATE),
+ EVP_CIPHER_set_asn1_iv,
+ EVP_CIPHER_get_asn1_iv,
+ * ECB modes don't use an Initial Vector so that's why set_asn1_parameters and
+ * get_asn1_parameters fields are set to NULL.
+static const EVP_CIPHER pk11_des_ecb =
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_CIPHER pk11_3des_ecb =
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_CIPHER pk11_aes_128_cbc =
+ sizeof (PK11_CIPHER_STATE),
+ EVP_CIPHER_set_asn1_iv,
+ EVP_CIPHER_get_asn1_iv,
+static const EVP_CIPHER pk11_aes_192_cbc =
+ sizeof (PK11_CIPHER_STATE),
+ EVP_CIPHER_set_asn1_iv,
+ EVP_CIPHER_get_asn1_iv,
+static const EVP_CIPHER pk11_aes_256_cbc =
+ sizeof (PK11_CIPHER_STATE),
+ EVP_CIPHER_set_asn1_iv,
+ EVP_CIPHER_get_asn1_iv,
+ * ECB modes don't use IV so that's why set_asn1_parameters and
+ * get_asn1_parameters are set to NULL.
+static const EVP_CIPHER pk11_aes_128_ecb =
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_CIPHER pk11_aes_192_ecb =
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_CIPHER pk11_aes_256_ecb =
+ sizeof (PK11_CIPHER_STATE),
+ * NID_undef's will be changed to the AES counter mode NIDs as soon they are
+ * created in pk11_library_init(). Note that the need to change these structures
+ * is the reason why we don't define them with the const keyword.
+static EVP_CIPHER pk11_aes_128_ctr =
+ sizeof (PK11_CIPHER_STATE),
+ EVP_CIPHER_set_asn1_iv,
+ EVP_CIPHER_get_asn1_iv,
+static EVP_CIPHER pk11_aes_192_ctr =
+ sizeof (PK11_CIPHER_STATE),
+ EVP_CIPHER_set_asn1_iv,
+ EVP_CIPHER_get_asn1_iv,
+static EVP_CIPHER pk11_aes_256_ctr =
+ sizeof (PK11_CIPHER_STATE),
+ EVP_CIPHER_set_asn1_iv,
+ EVP_CIPHER_get_asn1_iv,
+#endif /* SOLARIS_AES_CTR */
+static const EVP_CIPHER pk11_bf_cbc =
+ EVP_CIPH_VARIABLE_LENGTH,
+ sizeof (PK11_CIPHER_STATE),
+ EVP_CIPHER_set_asn1_iv,
+ EVP_CIPHER_get_asn1_iv,
+static const EVP_CIPHER pk11_rc4 =
+ EVP_CIPH_VARIABLE_LENGTH,
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_MD pk11_md5 =
+ NID_md5WithRSAEncryption,
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_MD pk11_sha1 =
+ NID_sha1WithRSAEncryption,
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_MD pk11_sha224 =
+ NID_sha224WithRSAEncryption,
+ /* SHA-224 uses the same cblock size as SHA-256 */
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_MD pk11_sha256 =
+ NID_sha256WithRSAEncryption,
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_MD pk11_sha384 =
+ NID_sha384WithRSAEncryption,
+ /* SHA-384 uses the same cblock size as SHA-512 */
+ sizeof (PK11_CIPHER_STATE),
+static const EVP_MD pk11_sha512 =
+ NID_sha512WithRSAEncryption,
+ sizeof (PK11_CIPHER_STATE),
+ * Initialization function. Sets up various PKCS#11 library components.
+ * The definitions for control commands specific to this engine
+#define PK11_CMD_SO_PATH ENGINE_CMD_BASE
+#define PK11_CMD_PIN (ENGINE_CMD_BASE+1)
+#define PK11_CMD_SLOT (ENGINE_CMD_BASE+2)
+static const ENGINE_CMD_DEFN pk11_cmd_defns[] =
+ "Specifies the path to the 'pkcs#11' shared library",
+ "Specifies the pin code",
+ "Specifies the slot (default is auto select)",
+ ENGINE_CMD_FLAG_NUMERIC,
+static RAND_METHOD pk11_random =
+/* Constants used when creating the ENGINE */
+#ifdef OPENSSL_NO_HW_PK11SO
+#error "can't load both crypto-accelerator and sign-only PKCS#11 engines"
+static const char *engine_pk11_id = "pkcs11";
+static const char *engine_pk11_name =
+ "PKCS #11 engine support (crypto accelerator)";
+CK_FUNCTION_LIST_PTR pFuncList = NULL;
+static const char PK11_GET_FUNCTION_LIST[] = "C_GetFunctionList";
+ * This is a static string constant for the DSO file name and the function
+ * symbol names to bind to. We set it in the Configure script based on whether
+ * this is 32 or 64 bit build.
+static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;
+static CK_BBOOL mytrue = TRUE;
+static CK_BBOOL myfalse = FALSE;
+/* Needed in
hw_pk11_pub.c as well so that's why it is not static. */
+CK_SLOT_ID pubkey_SLOTID = 0;
+static CK_SLOT_ID rand_SLOTID = 0;
+static CK_SLOT_ID SLOTID = 0;
+static CK_BBOOL pk11_library_initialized = FALSE;
+static CK_BBOOL pk11_atfork_initialized = FALSE;
+static int pk11_pid = 0;
+static DSO *pk11_dso = NULL;
+/* allocate and initialize all locks used by the engine itself */
+static int pk11_init_all_locks(void)
+ pthread_mutexattr_t attr;
+ if (pthread_mutexattr_init(&attr) != 0)
+ PK11err(PK11_F_INIT_ALL_LOCKS, 100);
+ if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK) != 0)
+ PK11err(PK11_F_INIT_ALL_LOCKS, 101);
+ if ((token_lock = OPENSSL_malloc(sizeof (pthread_mutex_t))) == NULL)
+ (void) pthread_mutex_init(token_lock, &attr);
+ find_lock[OP_RSA] = OPENSSL_malloc(sizeof (pthread_mutex_t));
+ if (find_lock[OP_RSA] == NULL)
+ (void) pthread_mutex_init(find_lock[OP_RSA], &attr);
+#endif /* OPENSSL_NO_RSA */
+ find_lock[OP_DSA] = OPENSSL_malloc(sizeof (pthread_mutex_t));
+ if (find_lock[OP_DSA] == NULL)
+ (void) pthread_mutex_init(find_lock[OP_DSA], &attr);
+#endif /* OPENSSL_NO_DSA */
+ find_lock[OP_DH] = OPENSSL_malloc(sizeof (pthread_mutex_t));
+ if (find_lock[OP_DH] == NULL)
+ (void) pthread_mutex_init(find_lock[OP_DH], &attr);
+#endif /* OPENSSL_NO_DH */
+ for (type = 0; type < OP_MAX; type++)
+ session_cache[type].lock =
+ OPENSSL_malloc(sizeof (pthread_mutex_t));
+ if (session_cache[type].lock == NULL)
+ (void) pthread_mutex_init(session_cache[type].lock, &attr);
+ PK11err(PK11_F_INIT_ALL_LOCKS, PK11_R_MALLOC_FAILURE);
+static void pk11_free_all_locks(void)
+ if (token_lock != NULL)
+ (void) pthread_mutex_destroy(token_lock);
+ OPENSSL_free(token_lock);
+ if (find_lock[OP_RSA] != NULL)
+ (void) pthread_mutex_destroy(find_lock[OP_RSA]);
+ OPENSSL_free(find_lock[OP_RSA]);
+ find_lock[OP_RSA] = NULL;
+#endif /* OPENSSL_NO_RSA */
+ if (find_lock[OP_DSA] != NULL)
+ (void) pthread_mutex_destroy(find_lock[OP_DSA]);
+ OPENSSL_free(find_lock[OP_DSA]);
+ find_lock[OP_DSA] = NULL;
+#endif /* OPENSSL_NO_DSA */
+ if (find_lock[OP_DH] != NULL)
+ (void) pthread_mutex_destroy(find_lock[OP_DH]);
+ OPENSSL_free(find_lock[OP_DH]);
+ find_lock[OP_DH] = NULL;
+#endif /* OPENSSL_NO_DH */
+ for (type = 0; type < OP_MAX; type++)
+ if (session_cache[type].lock != NULL)
+ (void) pthread_mutex_destroy(session_cache[type].lock);
+ OPENSSL_free(session_cache[type].lock);
+ session_cache[type].lock = NULL;
+ * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
+static int bind_pk11(ENGINE *e)
+ const RSA_METHOD *rsa = NULL;
+ RSA_METHOD *pk11_rsa = PK11_RSA();
+#endif /* OPENSSL_NO_RSA */
+ if (!pk11_library_initialized)
+ if (!pk11_library_init(e))
+ if (!ENGINE_set_id(e, engine_pk11_id) ||
+ !ENGINE_set_name(e, engine_pk11_name) ||
+ !ENGINE_set_ciphers(e, pk11_engine_ciphers) ||
+ !ENGINE_set_digests(e, pk11_engine_digests))
+ if (pk11_have_rsa == CK_TRUE)
+ if (!ENGINE_set_RSA(e, PK11_RSA()) ||
+ !ENGINE_set_load_privkey_function(e, pk11_load_privkey) ||
+ !ENGINE_set_load_pubkey_function(e, pk11_load_pubkey))
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: registered RSA\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+#endif /* OPENSSL_NO_RSA */
+ if (pk11_have_dsa == CK_TRUE)
+ if (!ENGINE_set_DSA(e, PK11_DSA()))
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: registered DSA\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+#endif /* OPENSSL_NO_DSA */
+ if (pk11_have_dh == CK_TRUE)
+ if (!ENGINE_set_DH(e, PK11_DH()))
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: registered DH\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+#endif /* OPENSSL_NO_DH */
+ if (!ENGINE_set_RAND(e, &pk11_random))
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: registered random\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ if (!ENGINE_set_init_function(e, pk11_init) ||
+ !ENGINE_set_destroy_function(e, pk11_destroy) ||
+ !ENGINE_set_finish_function(e, pk11_finish) ||
+ !ENGINE_set_ctrl_function(e, pk11_ctrl) ||
+ !ENGINE_set_cmd_defns(e, pk11_cmd_defns))
+ * Apache calls OpenSSL function RSA_blinding_on() once during startup
+ * which in turn calls bn_mod_exp. Since we do not implement bn_mod_exp
+ * here, we wire it back to the OpenSSL software implementation.
+ * Since it is used only once, performance is not a concern.
+ rsa = RSA_PKCS1_SSLeay();
+ pk11_rsa->rsa_mod_exp = rsa->rsa_mod_exp;
+ pk11_rsa->bn_mod_exp = rsa->bn_mod_exp;
+ if (pk11_have_recover != CK_TRUE)
+ pk11_rsa->rsa_pub_dec = rsa->rsa_pub_dec;
+#endif /* OPENSSL_NO_RSA */
+ /* Ensure the pk11 error handling is set up */
+ ERR_load_pk11_strings();
+/* Dynamic engine support is disabled at a higher level for Solaris */
+#ifdef ENGINE_DYNAMIC_SUPPORT
+#error "dynamic engine not supported"
+static int bind_helper(ENGINE *e, const char *id)
+ if (id && (strcmp(id, engine_pk11_id) != 0))
+IMPLEMENT_DYNAMIC_CHECK_FN()
+IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
+static ENGINE *engine_pk11(void)
+ ENGINE *ret = ENGINE_new();
+ * Do not use dynamic PKCS#11 library on Solaris due to
+ * security reasons. We will link it in statically.
+ /* Attempt to load PKCS#11 library */
+ pk11_dso = DSO_load(NULL, get_PK11_LIBNAME(), NULL, 0);
+ PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
+ e_pk11 = engine_pk11();
+ * At this point, the pk11 shared library is either dynamically
+ * loaded or statically linked in. So, initialize the pk11
+ * library before calling ENGINE_set_default since the latter
+ * needs cipher and digest algorithm information
+ if (!pk11_library_init(e_pk11))
+#endif /* ENGINE_DYNAMIC_SUPPORT */
+ * These are the static string constants for the DSO file name and
+ * the function symbol names to bind to.
+static const char *PK11_LIBNAME = NULL;
+static const char *get_PK11_LIBNAME(void)
+ return (def_PK11_LIBNAME);
+static void free_PK11_LIBNAME(void)
+ OPENSSL_free((void*)PK11_LIBNAME);
+static long set_PK11_LIBNAME(const char *name)
+ return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
+/* acquire all engine specific mutexes before fork */
+static void pk11_fork_prepare(void)
+ if (!pk11_library_initialized)
+ OPENSSL_assert(pthread_mutex_lock(token_lock) == 0);
+ for (i = 0; i < OP_MAX; i++)
+ OPENSSL_assert(pthread_mutex_lock(session_cache[i].lock) == 0);
+/* release all engine specific mutexes */
+static void pk11_fork_parent(void)
+ if (!pk11_library_initialized)
+ for (i = OP_MAX - 1; i >= 0; i--)
+ OPENSSL_assert(pthread_mutex_unlock(session_cache[i].lock) == 0);
+ UNLOCK_OBJSTORE(OP_DH);
+ UNLOCK_OBJSTORE(OP_DSA);
+ UNLOCK_OBJSTORE(OP_RSA);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ * same situation as in parent - we need to unlock all locks to make them
+ * accessible to all threads.
+static void pk11_fork_child(void)
+ if (!pk11_library_initialized)
+ for (i = OP_MAX - 1; i >= 0; i--)
+ OPENSSL_assert(pthread_mutex_unlock(session_cache[i].lock) == 0);
+ UNLOCK_OBJSTORE(OP_DH);
+ UNLOCK_OBJSTORE(OP_DSA);
+ UNLOCK_OBJSTORE(OP_RSA);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+/* Initialization function for the pk11 engine */
+static int pk11_init(ENGINE *e)
+ return (pk11_library_init(e));
+static CK_C_INITIALIZE_ARGS pk11_init_args =
+ NULL_PTR, /* CreateMutex */
+ NULL_PTR, /* DestroyMutex */
+ NULL_PTR, /* LockMutex */
+ NULL_PTR, /* UnlockMutex */
+ CKF_OS_LOCKING_OK, /* flags */
+ NULL_PTR, /* pReserved */
+ * Initialization function. Sets up various PKCS#11 library components.
+ * It selects a slot based on predefined critiera. In the process, it also
+ * count how many ciphers and digests to support. Since the cipher and
+ * digest information is needed when setting default engine, this function
+ * needs to be called before calling ENGINE_set_default.
+static int pk11_library_init(ENGINE *e)
+ CK_C_GetFunctionList p;
+#ifndef OPENSSL_SYS_WIN32
+ struct sigaction sigint_act, sigterm_act, sighup_act;
+ * pk11_library_initialized is set to 0 in pk11_finish() which
+ * is called from ENGINE_finish(). However, if there is still
+ * at least one existing functional reference to the engine
+ * (see engine(3) for more information), pk11_finish() is
+ * skipped. For example, this can happen if an application
+ * forgets to clear one cipher context. In case of a fork()
+ * when the application is finishing the engine so that it can
+ * be reinitialized in the child, forgotten functional
+ * reference causes pk11_library_initialized to stay 1. In
+ * that case we need the PID check so that we properly
+ * initialize the engine again.
+ if (pk11_library_initialized)
+ if (pk11_pid == getpid())
+ global_session = CK_INVALID_HANDLE;
+ * free the locks first to prevent memory leak in case
+ * the application calls fork() without finishing the
+ PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
+ * We must do this before we start working with slots since we need all
+ if (pk11_add_aes_ctr_NIDs() == 0)
+#endif /* SOLARIS_AES_CTR */
+#ifdef SOLARIS_HW_SLOT_SELECTION
+ if (check_hw_mechanisms() == 0)
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+ /* get the C_GetFunctionList function from the loaded library */
+ p = (CK_C_GetFunctionList)DSO_bind_func(pk11_dso,
+ PK11_GET_FUNCTION_LIST);
+ PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
+ /* get the full function list from the loaded library */
+ PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE, rv);
+#ifndef OPENSSL_SYS_WIN32
+ /* Not all PKCS#11 library are signal safe! */
+ (void) memset(&sigint_act, 0, sizeof(sigint_act));
+ (void) memset(&sigterm_act, 0, sizeof(sigterm_act));
+ (void) memset(&sighup_act, 0, sizeof(sighup_act));
+ (void) sigaction(SIGINT, NULL, &sigint_act);
+ (void) sigaction(SIGTERM, NULL, &sigterm_act);
+ (void) sigaction(SIGHUP, NULL, &sighup_act);
+ rv = pFuncList->C_Initialize((CK_VOID_PTR)&pk11_init_args);
+#ifndef OPENSSL_SYS_WIN32
+ (void) sigaction(SIGINT, &sigint_act, NULL);
+ (void) sigaction(SIGTERM, &sigterm_act, NULL);
+ (void) sigaction(SIGHUP, &sighup_act, NULL);
+ if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
+ PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE, rv);
+ rv = pFuncList->C_GetInfo(&info);
+ PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_GETINFO, rv);
+ if (pk11_choose_slots(&any_slot_found) == 0)
+ * The library we use, set in def_PK11_LIBNAME, may not offer any
+ * slot(s). In that case, we must not proceed but we must not return an
+ * error. The reason is that applications that try to set up the PKCS#11
+ * engine don't exit on error during the engine initialization just
+ * because no slot was present.
+ if (any_slot_found == 0)
+ if (global_session == CK_INVALID_HANDLE)
+ /* Open the global_session for the new process */
+ rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+ NULL_PTR, NULL_PTR, &global_session);
+ PK11err_add_data(PK11_F_LIBRARY_INIT,
+ PK11_R_OPENSESSION, rv);
+ * Disable digest if C_GetOperationState is not supported since
+ * this function is required by OpenSSL digest copy function
+ /* Keyper fails to return CKR_FUNCTION_NOT_SUPPORTED */
+ if (pFuncList->C_GetOperationState(global_session, NULL, &ul_state_len)
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: C_GetOperationState() not supported, "
+ "setting digest_count to 0\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ pk11_library_initialized = TRUE;
+ * if initialization of the locks fails pk11_init_all_locks()
+ if (!pk11_init_all_locks())
+ for (i = 0; i < OP_MAX; i++)
+ session_cache[i].head = NULL;
+ * initialize active lists. We only use active lists
+ * for asymmetric ciphers.
+ for (i = 0; i < OP_MAX; i++)
+ if (!pk11_atfork_initialized)
+ if (pthread_atfork(pk11_fork_prepare, pk11_fork_parent,
+ PK11err(PK11_F_LIBRARY_INIT, PK11_R_ATFORK_FAILED);
+ pk11_atfork_initialized = TRUE;
+/* Destructor (complements the "ENGINE_pk11()" constructor) */
+static int pk11_destroy(ENGINE *e)
+ ERR_unload_pk11_strings();
+ memset(pk11_pin, 0, strlen(pk11_pin));
+ OPENSSL_free((void*)pk11_pin);
+ * Termination function to clean up the session, the token, and the pk11
+static int pk11_finish(ENGINE *e)
+ memset(pk11_pin, 0, strlen(pk11_pin));
+ OPENSSL_free((void*)pk11_pin);
+ PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
+ OPENSSL_assert(pFuncList != NULL);
+ if (pk11_free_all_sessions() == 0)
+ /* free all active lists */
+ for (i = 0; i < OP_MAX; i++)
+ pk11_free_active_list(i);
+ pFuncList->C_CloseSession(global_session);
+ global_session = CK_INVALID_HANDLE;
+ * Since we are part of a library (
libcrypto.so), calling this function
+ * may have side-effects.
+ pFuncList->C_Finalize(NULL);
+ if (!DSO_free(pk11_dso))
+ PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
+ pk11_library_initialized = FALSE;
+ * There is no way how to unregister atfork handlers (other than
+ * unloading the library) so we just free the locks. For this reason
+ * the atfork handlers check if the engine is initialized and bail out
+ * immediately if not. This is necessary in case a process finishes
+ * the engine before calling fork().
+/* Standard engine interface function to set the dynamic library path */
+static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
+ int initialized = ((pk11_dso == NULL) ? 0 : 1);
+ PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
+ PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
+ return (set_PK11_LIBNAME((const char *)p));
+ memset(pk11_pin, 0, strlen(pk11_pin));
+ OPENSSL_free((void*)pk11_pin);
+ PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
+ pk11_pin = BUF_strdup(p);
+ PK11err(PK11_F_GET_SESSION, PK11_R_MALLOC_FAILURE);
+ SLOTID = (CK_SLOT_ID)i;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: slot set\n", PK11_DBG);
+ PK11err(PK11_F_CTRL, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
+/* Required function by the engine random interface. It does nothing here */
+static void pk11_rand_cleanup(void)
+static void pk11_rand_add(const void *buf, int num, double add)
+ if ((sp = pk11_get_session(OP_RAND)) == NULL)
+ * Ignore any errors (
e.g. CKR_RANDOM_SEED_NOT_SUPPORTED) since
+ * the calling functions do not care anyway
+ pFuncList->C_SeedRandom(sp->session, (unsigned char *) buf, num);
+ pk11_return_session(sp, OP_RAND);
+static void pk11_rand_seed(const void *buf, int num)
+ pk11_rand_add(buf, num, 0);
+static int pk11_rand_bytes(unsigned char *buf, int num)
+ if ((sp = pk11_get_session(OP_RAND)) == NULL)
+ rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
+ PK11err_add_data(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM, rv);
+ pk11_return_session(sp, OP_RAND);
+ pk11_return_session(sp, OP_RAND);
+/* Required function by the engine random interface. It does nothing here */
+static int pk11_rand_status(void)
+/* Free all BIGNUM structures from PK11_SESSION. */
+static void pk11_free_nums(PK11_SESSION *sp, PK11_OPTYPE optype)
+ if (sp->opdata_rsa_n_num != NULL)
+ BN_free(sp->opdata_rsa_n_num);
+ sp->opdata_rsa_n_num = NULL;
+ if (sp->opdata_rsa_e_num != NULL)
+ BN_free(sp->opdata_rsa_e_num);
+ sp->opdata_rsa_e_num = NULL;
+ if (sp->opdata_rsa_pn_num != NULL)
+ BN_free(sp->opdata_rsa_pn_num);
+ sp->opdata_rsa_pn_num = NULL;
+ if (sp->opdata_rsa_pe_num != NULL)
+ BN_free(sp->opdata_rsa_pe_num);
+ sp->opdata_rsa_pe_num = NULL;
+ if (sp->opdata_rsa_d_num != NULL)
+ BN_free(sp->opdata_rsa_d_num);
+ sp->opdata_rsa_d_num = NULL;
+ if (sp->opdata_dsa_pub_num != NULL)
+ BN_free(sp->opdata_dsa_pub_num);
+ sp->opdata_dsa_pub_num = NULL;
+ if (sp->opdata_dsa_priv_num != NULL)
+ BN_free(sp->opdata_dsa_priv_num);
+ sp->opdata_dsa_priv_num = NULL;
+ if (sp->opdata_dh_priv_num != NULL)
+ BN_free(sp->opdata_dh_priv_num);
+ sp->opdata_dh_priv_num = NULL;
+ * Get new PK11_SESSION structure ready for use. Every process must have
+ * its own freelist of PK11_SESSION structures so handle fork() here
+ * by destroying the old and creating new freelist.
+ * The returned PK11_SESSION structure is disconnected from the freelist.
+pk11_get_session(PK11_OPTYPE optype)
+ PK11_SESSION *sp = NULL, *sp1, *freelist;
+ pthread_mutex_t *freelist_lock = NULL;
+ freelist_lock = session_cache[optype].lock;
+ PK11err(PK11_F_GET_SESSION,
+ PK11_R_INVALID_OPERATION_TYPE);
+ OPENSSL_assert(pthread_mutex_lock(freelist_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ * Will use it to find out if we forked. We cannot use the PID field in
+ * the session structure because we could get a newly allocated session
+ * here, with no PID information.
+ freelist = session_cache[optype].head;
+ * If the free list is empty, allocate new unitialized (filled
+ * with zeroes) PK11_SESSION structure otherwise return first
+ * structure from the freelist.
+ if ((sp = OPENSSL_malloc(sizeof (PK11_SESSION))) == NULL)
+ PK11err(PK11_F_GET_SESSION,
+ PK11_R_MALLOC_FAILURE);
+ (void) memset(sp, 0, sizeof (PK11_SESSION));
+ * It is a new session so it will look like a cache miss to the
+ * code below. So, we must not try to to destroy its members so
+ sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
+ * Check whether we have forked. In that case, we must get rid of all
+ * inherited sessions and start allocating new ones.
+ if (pid != (new_pid = getpid()))
+ * We are a new process and thus need to free any inherited
+ * PK11_SESSION objects aside from the first session (sp) which
+ * is the only PK11_SESSION structure we will reuse (for the
+ while ((sp1 = freelist) != NULL)
+ * NOTE: we do not want to call pk11_free_all_sessions()
+ * here because it would close underlying PKCS#11
+ * sessions and destroy all objects.
+ pk11_free_nums(sp1, optype);
+ /* we have to free the active list as well. */
+ pk11_free_active_list(optype);
+ /* Initialize the process */
+ rv = pFuncList->C_Initialize((CK_VOID_PTR)&pk11_init_args);
+ if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
+ PK11err_add_data(PK11_F_GET_SESSION, PK11_R_INITIALIZE,
+ * Choose slot here since the slot table is different on this
+ * process. If we are here then we must have found at least one
+ * usable slot before so we don't need to check any_slot_found.
+ * See pk11_library_init()'s usage of this function for more
+#ifdef SOLARIS_HW_SLOT_SELECTION
+ if (check_hw_mechanisms() == 0)
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+ if (pk11_choose_slots(NULL) == 0)
+ /* Open the global_session for the new process */
+ rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+ NULL_PTR, NULL_PTR, &global_session);
+ PK11err_add_data(PK11_F_GET_SESSION, PK11_R_OPENSESSION,
+ * It is an inherited session from our parent so it needs
+ if (pk11_setup_session(sp, optype) == 0)
+ if (pk11_token_relogin(sp->session) == 0)
+ * We will keep the session in the cache list and let
+ * the caller cope with the situation.
+ /* It is a new session and needs initialization. */
+ if (pk11_setup_session(sp, optype) == 0)
+ /* set new head for the list of PK11_SESSION objects */
+ session_cache[optype].head = freelist;
+ OPENSSL_assert(pthread_mutex_unlock(freelist_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype)
+ pthread_mutex_t *freelist_lock;
+ PK11_SESSION *freelist;
+ * If this is a session from the parent it will be taken care of and
+ * freed in pk11_get_session() as part of the post-fork clean up the
+ * next time we will ask for a new session.
+ if (sp == NULL || sp->pid != getpid())
+ freelist_lock = session_cache[optype].lock;
+ PK11err(PK11_F_RETURN_SESSION,
+ PK11_R_INVALID_OPERATION_TYPE);
+ OPENSSL_assert(pthread_mutex_lock(freelist_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ freelist = session_cache[optype].head;
+ session_cache[optype].head = sp;
+ OPENSSL_assert(pthread_mutex_unlock(freelist_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+/* Destroy all objects. This function is called when the engine is finished */
+static int pk11_free_all_sessions()
+ (void) pk11_destroy_rsa_key_objects(NULL);
+#endif /* OPENSSL_NO_RSA */
+ (void) pk11_destroy_dsa_key_objects(NULL);
+#endif /* OPENSSL_NO_DSA */
+ (void) pk11_destroy_dh_key_objects(NULL);
+#endif /* OPENSSL_NO_DH */
+ (void) pk11_destroy_cipher_key_objects(NULL);
+ * We try to release as much as we can but any error means that we will
+ for (type = 0; type < OP_MAX; type++)
+ if (pk11_free_session_list(type) == 0)
+ * Destroy session structures from the linked list specified. Free as many
+ * sessions as possible but any failure in C_CloseSession() means that we
+ * return an error on return.
+static int pk11_free_session_list(PK11_OPTYPE optype)
+ PK11_SESSION *sp = NULL;
+ PK11_SESSION *freelist = NULL;
+ pid_t mypid = getpid();
+ pthread_mutex_t *freelist_lock;
+ freelist_lock = session_cache[optype].lock;
+ PK11err(PK11_F_FREE_ALL_SESSIONS,
+ PK11_R_INVALID_OPERATION_TYPE);
+ OPENSSL_assert(pthread_mutex_lock(freelist_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ freelist = session_cache[optype].head;
+ while ((sp = freelist) != NULL)
+ if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
+ rv = pFuncList->C_CloseSession(sp->session);
+ PK11err_add_data(PK11_F_FREE_ALL_SESSIONS,
+ PK11_R_CLOSESESSION, rv);
+ pk11_free_nums(sp, optype);
+ OPENSSL_assert(pthread_mutex_unlock(freelist_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype)
+ myslot = pubkey_SLOTID;
+ PK11err(PK11_F_SETUP_SESSION,
+ PK11_R_INVALID_OPERATION_TYPE);
+ sp->session = CK_INVALID_HANDLE;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: myslot=%d optype=%d\n", PK11_DBG, myslot, optype);
+#endif /* DEBUG_SLOT_SELECTION */
+ rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
+ NULL_PTR, NULL_PTR, &sp->session);
+ if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
+ * We are probably a child process so force the
+ * reinitialize of the session
+ pk11_library_initialized = FALSE;
+ if (!pk11_library_init(NULL))
+ rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
+ NULL_PTR, NULL_PTR, &sp->session);
+ PK11err_add_data(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION, rv);
+ sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_pub = NULL;
+ sp->opdata_rsa_n_num = NULL;
+ sp->opdata_rsa_e_num = NULL;
+ sp->opdata_rsa_priv = NULL;
+ sp->opdata_rsa_pn_num = NULL;
+ sp->opdata_rsa_pe_num = NULL;
+ sp->opdata_rsa_d_num = NULL;
+#endif /* OPENSSL_NO_RSA */
+ sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
+ sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
+ sp->opdata_dsa_pub = NULL;
+ sp->opdata_dsa_pub_num = NULL;
+ sp->opdata_dsa_priv = NULL;
+ sp->opdata_dsa_priv_num = NULL;
+#endif /* OPENSSL_NO_DSA */
+ sp->opdata_dh_key = CK_INVALID_HANDLE;
+ sp->opdata_dh_priv_num = NULL;
+#endif /* OPENSSL_NO_DH */
+ sp->opdata_cipher_key = CK_INVALID_HANDLE;
+ sp->opdata_encrypt = -1;
+ * We always initialize the session as containing a non-persistent
+ * object. The key load functions set it to persistent if that is so.
+ sp->pub_persistent = CK_FALSE;
+ sp->priv_persistent = CK_FALSE;
+/* Destroy RSA public key from single session. */
+pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
+ if (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE)
+ TRY_OBJ_DESTROY(sp, sp->opdata_rsa_pub_key,
+ ret, uselock, OP_RSA, CK_FALSE);
+ sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_pub = NULL;
+ if (sp->opdata_rsa_n_num != NULL)
+ BN_free(sp->opdata_rsa_n_num);
+ sp->opdata_rsa_n_num = NULL;
+ if (sp->opdata_rsa_e_num != NULL)
+ BN_free(sp->opdata_rsa_e_num);
+ sp->opdata_rsa_e_num = NULL;
+/* Destroy RSA private key from single session. */
+pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
+ if (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE)
+ TRY_OBJ_DESTROY(sp, sp->opdata_rsa_priv_key,
+ ret, uselock, OP_RSA, CK_TRUE);
+ sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_priv = NULL;
+ if (sp->opdata_rsa_d_num != NULL)
+ BN_free(sp->opdata_rsa_d_num);
+ sp->opdata_rsa_d_num = NULL;
+ * For the RSA key by reference code, public components 'n'/'e'
+ * are the key components we use to check for the cache hit. We
+ * must free those as well.
+ if (sp->opdata_rsa_pn_num != NULL)
+ BN_free(sp->opdata_rsa_pn_num);
+ sp->opdata_rsa_pn_num = NULL;
+ if (sp->opdata_rsa_pe_num != NULL)
+ BN_free(sp->opdata_rsa_pe_num);
+ sp->opdata_rsa_pe_num = NULL;
+ * Destroy RSA key object wrapper. If session is NULL, try to destroy all
+ * objects in the free list.
+pk11_destroy_rsa_key_objects(PK11_SESSION *session)
+ PK11_SESSION *sp = NULL;
+ PK11_SESSION *local_free_session;
+ CK_BBOOL uselock = TRUE;
+ local_free_session = session;
+ OPENSSL_assert(pthread_mutex_lock(session_cache[OP_RSA].lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ local_free_session = session_cache[OP_RSA].head;
+ * go through the list of sessions and delete key objects
+ while ((sp = local_free_session) != NULL)
+ local_free_session = sp->next;
+ * Do not terminate list traversal if one of the
+ * destroy operations fails.
+ if (pk11_destroy_rsa_object_pub(sp, uselock) == 0)
+ if (pk11_destroy_rsa_object_priv(sp, uselock) == 0)
+ OPENSSL_assert(pthread_mutex_unlock(session_cache[OP_RSA].lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+#endif /* OPENSSL_NO_RSA */
+/* Destroy DSA public key from single session. */
+pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
+ if (sp->opdata_dsa_pub_key != CK_INVALID_HANDLE)
+ TRY_OBJ_DESTROY(sp, sp->opdata_dsa_pub_key,
+ ret, uselock, OP_DSA, CK_FALSE);
+ sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
+ sp->opdata_dsa_pub = NULL;
+ if (sp->opdata_dsa_pub_num != NULL)
+ BN_free(sp->opdata_dsa_pub_num);
+ sp->opdata_dsa_pub_num = NULL;
+/* Destroy DSA private key from single session. */
+pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
+ if (sp->opdata_dsa_priv_key != CK_INVALID_HANDLE)
+ TRY_OBJ_DESTROY(sp, sp->opdata_dsa_priv_key,
+ ret, uselock, OP_DSA, CK_TRUE);
+ sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
+ sp->opdata_dsa_priv = NULL;
+ if (sp->opdata_dsa_priv_num != NULL)
+ BN_free(sp->opdata_dsa_priv_num);
+ sp->opdata_dsa_priv_num = NULL;
+ * Destroy DSA key object wrapper. If session is NULL, try to destroy all
+ * objects in the free list.
+pk11_destroy_dsa_key_objects(PK11_SESSION *session)
+ PK11_SESSION *sp = NULL;
+ PK11_SESSION *local_free_session;
+ CK_BBOOL uselock = TRUE;
+ local_free_session = session;
+ OPENSSL_assert(pthread_mutex_lock(session_cache[OP_DSA].lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ local_free_session = session_cache[OP_DSA].head;
+ * go through the list of sessions and delete key objects
+ while ((sp = local_free_session) != NULL)
+ local_free_session = sp->next;
+ * Do not terminate list traversal if one of the
+ * destroy operations fails.
+ if (pk11_destroy_dsa_object_pub(sp, uselock) == 0)
+ if (pk11_destroy_dsa_object_priv(sp, uselock) == 0)
+ OPENSSL_assert(pthread_mutex_unlock(session_cache[OP_DSA].lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+#endif /* OPENSSL_NO_DSA */
+/* Destroy DH key from single session. */
+pk11_destroy_dh_object(PK11_SESSION *sp, CK_BBOOL uselock)
+ if (sp->opdata_dh_key != CK_INVALID_HANDLE)
+ TRY_OBJ_DESTROY(sp, sp->opdata_dh_key,
+ ret, uselock, OP_DH, CK_TRUE);
+ sp->opdata_dh_key = CK_INVALID_HANDLE;
+ if (sp->opdata_dh_priv_num != NULL)
+ BN_free(sp->opdata_dh_priv_num);
+ sp->opdata_dh_priv_num = NULL;
+ * Destroy DH key object wrapper.
+ * arg0: pointer to PKCS#11 engine session structure
+ * if session is NULL, try to destroy all objects in the free list
+pk11_destroy_dh_key_objects(PK11_SESSION *session)
+ PK11_SESSION *sp = NULL;
+ PK11_SESSION *local_free_session;
+ CK_BBOOL uselock = TRUE;
+ local_free_session = session;
+ OPENSSL_assert(pthread_mutex_lock(session_cache[OP_DH].lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ local_free_session = session_cache[OP_DH].head;
+ while ((sp = local_free_session) != NULL)
+ local_free_session = sp->next;
+ * Do not terminate list traversal if one of the
+ * destroy operations fails.
+ if (pk11_destroy_dh_object(sp, uselock) == 0)
+ OPENSSL_assert(pthread_mutex_unlock(session_cache[OP_DH].lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+#endif /* OPENSSL_NO_DH */
+pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh,
+ * We never try to destroy persistent objects which are the objects
+ * stored in the keystore. Also, we always use read-only sessions so
+ * C_DestroyObject() would be returning CKR_SESSION_READ_ONLY here.
+ if (persistent == CK_TRUE)
+ rv = pFuncList->C_DestroyObject(session, oh);
+ PK11err_add_data(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT,
+/* Symmetric ciphers and digests support functions */
+cipher_nid_to_pk11(int nid)
+ for (i = 0; i < PK11_CIPHER_MAX; i++)
+ if (ciphers[i].nid == nid)
+ return (ciphers[i].id);
+pk11_usable_ciphers(const int **nids)
+pk11_usable_digests(const int **nids)
+ * Init context for encryption or decryption using a symmetric key.
+static int pk11_init_symmetric(EVP_CIPHER_CTX *ctx, PK11_CIPHER *pcipher,
+ PK11_SESSION *sp, CK_MECHANISM_PTR pmech)
+ CK_AES_CTR_PARAMS ctr_params;
+#endif /* SOLARIS_AES_CTR */
+ * We expect pmech->mechanism to be already set and
+ * pk11_init_symetric() is called.
+ OPENSSL_assert(pmech->mechanism != 0);
+ OPENSSL_assert(pmech->pParameter == NULL);
+ OPENSSL_assert(pmech->ulParameterLen == 0);
+ if (ctx->cipher->nid == NID_aes_128_ctr ||
+ ctx->cipher->nid == NID_aes_192_ctr ||
+ ctx->cipher->nid == NID_aes_256_ctr)
+ pmech->pParameter = (void *)(&ctr_params);
+ pmech->ulParameterLen = sizeof (ctr_params);
+ * For now, we are limited to the fixed length of the counter,
+ * it covers the whole counter block. That's what RFC 4344
+ * needs. For more information on internal structure of the
+ * counter block, see RFC 3686. If needed in the future, we can
+ * add code so that the counter length can be set via
+ * ENGINE_ctrl() function.
+ OPENSSL_assert(pcipher->iv_len == AES_BLOCK_SIZE);
+#endif /* SOLARIS_AES_CTR */
+ if (pcipher->iv_len > 0)
+ pmech->pParameter = (void *)ctx->iv;
+ pmech->ulParameterLen = pcipher->iv_len;
+ /* if we get here, the encryption needs to be reinitialized */
+ rv = pFuncList->C_EncryptInit(sp->session, pmech,
+ sp->opdata_cipher_key);
+ rv = pFuncList->C_DecryptInit(sp->session, pmech,
+ sp->opdata_cipher_key);
+ PK11err_add_data(PK11_F_CIPHER_INIT, ctx->encrypt ?
+ PK11_R_ENCRYPTINIT : PK11_R_DECRYPTINIT, rv);
+ pk11_return_session(sp, OP_CIPHER);
+pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
+ const unsigned char *iv, int enc)
+ PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
+ PK11_CIPHER *p_ciph_table_row;
+ index = cipher_nid_to_pk11(ctx->cipher->nid);
+ if (index < 0 || index >= PK11_CIPHER_MAX)
+ p_ciph_table_row = &ciphers[index];
+ * iv_len in the ctx->cipher structure is the maximum IV length for the
+ * current cipher and it must be less or equal to the IV length in our
+ * ciphers table. The key length must be in the allowed interval. From
+ * all cipher modes that the PKCS#11 engine supports only RC4 allows a
+ * key length to be in some range, all other NIDs have a precise key
+ * length. Every application can define its own EVP functions so this
+ * code serves as a sanity check.
+ * Note that the reason why the IV length in ctx->cipher might be
+ * greater than the actual length is that OpenSSL uses BLOCK_CIPHER_defs
+ * macro to define functions that return EVP structures for all DES
+ * modes. So, even ECB modes get 8 byte IV.
+ if (ctx->cipher->iv_len < p_ciph_table_row->iv_len ||
+ ctx->key_len < p_ciph_table_row->min_key_len ||
+ ctx->key_len > p_ciph_table_row->max_key_len) {
+ PK11err(PK11_F_CIPHER_INIT, PK11_R_KEY_OR_IV_LEN_PROBLEM);
+ if ((sp = pk11_get_session(OP_CIPHER)) == NULL)
+ /* if applicable, the mechanism parameter is used for IV */
+ /* The key object is destroyed here if it is not the current key. */
+ (void) check_new_cipher_key(sp, key, ctx->key_len);
+ * If the key is the same and the encryption is also the same, then
+ * just reuse it. However, we must not forget to reinitialize the
+ * context that was finalized in pk11_cipher_cleanup().
+ if (sp->opdata_cipher_key != CK_INVALID_HANDLE &&
+ sp->opdata_encrypt == ctx->encrypt)
+ if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
+ * Check if the key has been invalidated. If so, a new key object
+ if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
+ sp->opdata_cipher_key = pk11_get_cipher_key(
+ ctx, key, p_ciph_table_row->key_type, sp);
+ if (sp->opdata_encrypt != ctx->encrypt && sp->opdata_encrypt != -1)
+ if (!pk11_cipher_final(sp))
+ pk11_return_session(sp, OP_CIPHER);
+ if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
+ pk11_return_session(sp, OP_CIPHER);
+ /* now initialize the context with a new key */
+ if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
+ sp->opdata_encrypt = ctx->encrypt;
+ * and recreate a new one. Note that the key is in the global session so
+ * that it needs not be recreated.
+ * development, these two functions in the PKCS#11 libraries used return
+ * unexpected errors when passing in 0 length output. It may be a good
+ * idea to try them again if performance is a problem here and fix
+pk11_cipher_final(PK11_SESSION *sp)
+ rv = pFuncList->C_CloseSession(sp->session);
+ PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_CLOSESESSION, rv);
+ rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+ NULL_PTR, NULL_PTR, &sp->session);
+ PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_OPENSESSION, rv);
+ * An engine interface function. The calling function allocates sufficient
+ * memory for the output buffer "out" to hold the results.
+#if OPENSSL_VERSION_NUMBER < 0x10000000L
+pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ const unsigned char *in, unsigned int inl)
+pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ const unsigned char *in, size_t inl)
+ PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
+ unsigned long outl = inl;
+ if (state == NULL || state->sp == NULL)
+ sp = (PK11_SESSION *) state->sp;
+ /* RC4 is the only stream cipher we support */
+ if (ctx->cipher->nid != NID_rc4 && (inl % ctx->cipher->block_size) != 0)
+ rv = pFuncList->C_EncryptUpdate(sp->session,
+ (unsigned char *)in, inl, out, &outl);
+ PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
+ PK11_R_ENCRYPTUPDATE, rv);
+ rv = pFuncList->C_DecryptUpdate(sp->session,
+ (unsigned char *)in, inl, out, &outl);
+ PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
+ PK11_R_DECRYPTUPDATE, rv);
+ * For DES_CBC, DES3_CBC, AES_CBC, and RC4, the output size is always
+ * the same size of input.
+ * The application has guaranteed to call the block ciphers with
+ * correctly aligned buffers.
+ * Return the session to the pool. Calling C_EncryptFinal() and C_DecryptFinal()
+ * here is the right thing because in EVP_DecryptFinal_ex(), engine's
+ * do_cipher() is not even called, and in EVP_EncryptFinal_ex() it is called but
+ * the engine can't find out that it's the finalizing call. We wouldn't
+ * necessarily have to finalize the context here since reinitializing it with
+ * C_(Encrypt|Decrypt)Init() should be fine but for the sake of correctness,
+ * let's do it. Some implementations might leak memory if the previously used
+ * context is initialized without finalizing it first.
+pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx)
+ CK_ULONG len = EVP_MAX_BLOCK_LENGTH;
+ CK_BYTE buf[EVP_MAX_BLOCK_LENGTH];
+ PK11_CIPHER_STATE *state = ctx->cipher_data;
+ if (state != NULL && state->sp != NULL)
+ * We are not interested in the data here, we just need to get
+ rv = pFuncList->C_EncryptFinal(
+ state->sp->session, buf, &len);
+ rv = pFuncList->C_DecryptFinal(
+ state->sp->session, buf, &len);
+ PK11err_add_data(PK11_F_CIPHER_CLEANUP, ctx->encrypt ?
+ PK11_R_ENCRYPTFINAL : PK11_R_DECRYPTFINAL, rv);
+ pk11_return_session(state->sp, OP_CIPHER);
+ pk11_return_session(state->sp, OP_CIPHER);
+ * Registered by the ENGINE when used to find out how to deal with
+ * a particular NID in the ENGINE. This says what we'll do at the
+ * top level - note, that list is restricted by what we answer with
+pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
+ const int **nids, int nid)
+ return (pk11_usable_ciphers(nids));
+ *cipher = &pk11_3des_cbc;
+ *cipher = &pk11_des_cbc;
+ *cipher = &pk11_3des_ecb;
+ *cipher = &pk11_des_ecb;
+ *cipher = &pk11_aes_128_cbc;
+ *cipher = &pk11_aes_192_cbc;
+ *cipher = &pk11_aes_256_cbc;
+ *cipher = &pk11_aes_128_ecb;
+ *cipher = &pk11_aes_192_ecb;
+ *cipher = &pk11_aes_256_ecb;
+ *cipher = &pk11_bf_cbc;
+ * These can't be in separated cases because the NIDs
+ * here are not constants.
+ if (nid == NID_aes_128_ctr)
+ *cipher = &pk11_aes_128_ctr;
+ else if (nid == NID_aes_192_ctr)
+ *cipher = &pk11_aes_192_ctr;
+ else if (nid == NID_aes_256_ctr)
+ *cipher = &pk11_aes_256_ctr;
+#endif /* SOLARIS_AES_CTR */
+ return (*cipher != NULL);
+pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
+ const int **nids, int nid)
+ return (pk11_usable_digests(nids));
+ *digest = &pk11_sha224;
+ *digest = &pk11_sha256;
+ *digest = &pk11_sha384;
+ *digest = &pk11_sha512;
+ return (*digest != NULL);
+/* Create a secret key object in a PKCS#11 session */
+static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
+ const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp)
+ CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+ CK_OBJECT_CLASS obj_key = CKO_SECRET_KEY;
+ CK_ULONG ul_key_attr_count = 6;
+ unsigned char key_buf[PK11_KEY_LEN_MAX];
+ CK_ATTRIBUTE a_key_template[] =
+ {CKA_CLASS, (void*) NULL, sizeof (CK_OBJECT_CLASS)},
+ {CKA_KEY_TYPE, (void*) NULL, sizeof (CK_KEY_TYPE)},
+ {CKA_TOKEN, &myfalse, sizeof (myfalse)},
+ {CKA_ENCRYPT, &mytrue, sizeof (mytrue)},
+ {CKA_DECRYPT, &mytrue, sizeof (mytrue)},
+ {CKA_VALUE, (void*) NULL, 0},
+ * Create secret key object in global_session. All other sessions
+ * can use the key handles. Here is why:
+ * OpenSSL will call EncryptInit and EncryptUpdate using a secret key.
+ * It may then call DecryptInit and DecryptUpdate using the same key.
+ * To use the same key object, we need to call EncryptFinal with
+ * a 0 length message. Currently, this does not work for 3DES
+ * mechanism. To get around this problem, we close the session and
+ * then create a new session to use the same key object. When a session
+ * is closed, all the object handles will be invalid. Thus, create key
+ * objects in a global session, an individual session may be closed to
+ * terminate the active operation.
+ CK_SESSION_HANDLE session = global_session;
+ a_key_template[0].pValue = &obj_key;
+ a_key_template[1].pValue = &key_type;
+ if (ctx->key_len > PK11_KEY_LEN_MAX)
+ a_key_template[5].pValue = (void *) key;
+ memset(key_buf, 0, PK11_KEY_LEN_MAX);
+ memcpy(key_buf, key, ctx->key_len);
+ if ((key_type == CKK_DES) ||
+ (key_type == CKK_DES2) ||
+ (key_type == CKK_DES3))
+ DES_fixup_key_parity((DES_cblock *) &key_buf[0]);
+ if ((key_type == CKK_DES2) ||
+ (key_type == CKK_DES3))
+ DES_fixup_key_parity((DES_cblock *) &key_buf[8]);
+ if (key_type == CKK_DES3)
+ DES_fixup_key_parity((DES_cblock *) &key_buf[16]);
+ a_key_template[5].pValue = (void *) key_buf;
+ a_key_template[5].ulValueLen = (unsigned long) ctx->key_len;
+ rv = pFuncList->C_CreateObject(session,
+ a_key_template, ul_key_attr_count, &h_key);
+ memset(key_buf, 0, PK11_KEY_LEN_MAX);
+ PK11err_add_data(PK11_F_GET_CIPHER_KEY, PK11_R_CREATEOBJECT,
+ * Save the key information used in this session.
+ * The max can be saved is PK11_KEY_LEN_MAX.
+ if (ctx->key_len > PK11_KEY_LEN_MAX)
+ sp->opdata_key_len = PK11_KEY_LEN_MAX;
+ (void) memcpy(sp->opdata_key, key, sp->opdata_key_len);
+ sp->opdata_key_len = ctx->key_len;
+ (void) memcpy(sp->opdata_key, key_buf, sp->opdata_key_len);
+ memset(key_buf, 0, PK11_KEY_LEN_MAX);
+ for (i = 0; i < PK11_DIGEST_MAX; i++)
+ if (digests[i].nid == nid)
+ return (digests[i].id);
+pk11_digest_init(EVP_MD_CTX *ctx)
+ PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
+ index = md_nid_to_pk11(ctx->digest->type);
+ if (index < 0 || index >= PK11_DIGEST_MAX)
+ if ((sp = pk11_get_session(OP_DIGEST)) == NULL)
+ /* at present, no parameter is needed for supported digests */
+ rv = pFuncList->C_DigestInit(sp->session, &mech);
+ PK11err_add_data(PK11_F_DIGEST_INIT, PK11_R_DIGESTINIT, rv);
+ pk11_return_session(sp, OP_DIGEST);
+pk11_digest_update(EVP_MD_CTX *ctx, const void *data, size_t count)
+ PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
+ /* 0 length message will cause a failure in C_DigestFinal */
+ if (state == NULL || state->sp == NULL)
+ rv = pFuncList->C_DigestUpdate(state->sp->session, (CK_BYTE *) data,
+ PK11err_add_data(PK11_F_DIGEST_UPDATE, PK11_R_DIGESTUPDATE, rv);
+ pk11_return_session(state->sp, OP_DIGEST);
+pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
+ PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
+ len = ctx->digest->md_size;
+ if (state == NULL || state->sp == NULL)
+ rv = pFuncList->C_DigestFinal(state->sp->session, md, &len);
+ PK11err_add_data(PK11_F_DIGEST_FINAL, PK11_R_DIGESTFINAL, rv);
+ pk11_return_session(state->sp, OP_DIGEST);
+ if (ctx->digest->md_size != len)
+ * Final is called and digest is returned, so return the session
+ pk11_return_session(state->sp, OP_DIGEST);
+pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
+ PK11_CIPHER_STATE *state, *state_to;
+ CK_BYTE_PTR pstate = NULL;
+ /* The copy-from state */
+ state = (PK11_CIPHER_STATE *) from->md_data;
+ if (state == NULL || state->sp == NULL)
+ /* Initialize the copy-to state */
+ if (!pk11_digest_init(to))
+ state_to = (PK11_CIPHER_STATE *) to->md_data;
+ /* Get the size of the operation state of the copy-from session */
+ rv = pFuncList->C_GetOperationState(state->sp->session, NULL,
+ PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
+ pstate = OPENSSL_malloc(ul_state_len);
+ PK11err(PK11_F_DIGEST_COPY, PK11_R_MALLOC_FAILURE);
+ /* Get the operation state of the copy-from session */
+ rv = pFuncList->C_GetOperationState(state->sp->session, pstate,
+ PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
+ /* Set the operation state of the copy-to session */
+ rv = pFuncList->C_SetOperationState(state_to->sp->session, pstate,
+ PK11err_add_data(PK11_F_DIGEST_COPY,
+ PK11_R_SET_OPERATION_STATE, rv);
+/* Return any pending session state to the pool */
+pk11_digest_cleanup(EVP_MD_CTX *ctx)
+ PK11_CIPHER_STATE *state = ctx->md_data;
+ unsigned char buf[EVP_MAX_MD_SIZE];
+ if (state != NULL && state->sp != NULL)
+ * If state->sp is not NULL then pk11_digest_final() has not
+ * been called yet. We must call it now to free any memory
+ * that might have been allocated in the token when
+ * pk11_digest_init() was called. pk11_digest_final()
+ * will return the session to the cache.
+ if (!pk11_digest_final(ctx, buf))
+ * Check if the new key is the same as the key object in the session. If the key
+ * is the same, no need to create a new key object. Otherwise, the old key
+ * object needs to be destroyed and a new one will be created. Return 1 for
+ * cache hit, 0 for cache miss. Note that we must check the key length first
+ * otherwise we could end up reusing a different, longer key with the same
+static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
+ if (sp->opdata_key_len != key_len ||
+ memcmp(sp->opdata_key, key, key_len) != 0)
+ (void) pk11_destroy_cipher_key_objects(sp);
+/* Destroy one or more secret key objects. */
+static int pk11_destroy_cipher_key_objects(PK11_SESSION *session)
+ PK11_SESSION *sp = NULL;
+ PK11_SESSION *local_free_session;
+ local_free_session = session;
+ OPENSSL_assert(pthread_mutex_lock(session_cache[OP_CIPHER].lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ local_free_session = session_cache[OP_CIPHER].head;
+ while ((sp = local_free_session) != NULL)
+ local_free_session = sp->next;
+ if (sp->opdata_cipher_key != CK_INVALID_HANDLE)
+ * The secret key object is created in the
+ * global_session. See pk11_get_cipher_key().
+ if (pk11_destroy_object(global_session,
+ sp->opdata_cipher_key, CK_FALSE) == 0)
+ sp->opdata_cipher_key = CK_INVALID_HANDLE;
+ OPENSSL_assert(pthread_mutex_unlock(session_cache[OP_CIPHER].lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ * Public key mechanisms optionally supported
+ * The first slot that supports at least one of those mechanisms is chosen as a
+ * Symmetric ciphers optionally supported
+ * Digests optionally supported
+ * The output of this function is a set of global variables indicating which
+ * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
+ * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
+ * variables carry information about which slot was chosen for (a) public key
+ * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
+pk11_choose_slots(int *any_slot_found)
+ CK_SLOT_ID_PTR pSlotList = NULL_PTR;
+ CK_ULONG ulSlotCount = 0;
+ CK_MECHANISM_INFO mech_info;
+ CK_TOKEN_INFO token_info;
+ CK_SLOT_ID best_slot_sofar = 0;
+ CK_BBOOL found_candidate_slot = CK_FALSE;
+ CK_SLOT_ID current_slot = 0;
+ int current_slot_n_cipher = 0;
+ int current_slot_n_digest = 0;
+ int local_cipher_nids[PK11_CIPHER_MAX];
+ int local_digest_nids[PK11_DIGEST_MAX];
+ /* let's initialize the output parameter */
+ if (any_slot_found != NULL)
+ /* Get slot list for memory allocation */
+ rv = pFuncList->C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount);
+ PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
+ /* it's not an error if we didn't find any providers */
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: no crypto providers found\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
+ PK11err(PK11_F_CHOOSE_SLOT, PK11_R_MALLOC_FAILURE);
+ /* Get the slot list for processing */
+ rv = pFuncList->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount);
+ PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
+ OPENSSL_free(pSlotList);
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: provider: %s\n", PK11_DBG, def_PK11_LIBNAME);
+ fprintf(stderr, "%s: number of slots: %d\n", PK11_DBG, ulSlotCount);
+ fprintf(stderr, "%s: == checking rand slots ==\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ for (i = 0; i < ulSlotCount; i++)
+ current_slot = pSlotList[i];
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
+#endif /* DEBUG_SLOT_SELECTION */
+ /* Check if slot has random support. */
+ rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
+#ifdef DEBUG_SLOT_SELECTION
+#endif /* DEBUG_SLOT_SELECTION */
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: this token has CKF_RNG flag\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ pk11_have_random = CK_TRUE;
+ rand_SLOTID = current_slot;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: == checking pubkey slots ==\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ pubkey_SLOTID = pSlotList[0];
+ for (i = 0; i < ulSlotCount; i++)
+ CK_BBOOL slot_has_rsa = CK_FALSE;
+ CK_BBOOL slot_has_recover = CK_FALSE;
+ CK_BBOOL slot_has_dsa = CK_FALSE;
+ CK_BBOOL slot_has_dh = CK_FALSE;
+ current_slot = pSlotList[i];
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
+#endif /* DEBUG_SLOT_SELECTION */
+ rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
+#ifdef DEBUG_SLOT_SELECTION
+#endif /* DEBUG_SLOT_SELECTION */
+ * Check if this slot is capable of signing and
+ * verifying with CKM_RSA_PKCS.
+ rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS,
+ * Check if this slot is capable of encryption,
+ * decryption, sign, and verify with CKM_RSA_X_509.
+ rv = pFuncList->C_GetMechanismInfo(current_slot,
+ CKM_RSA_X_509, &mech_info);
+ slot_has_rsa = CK_TRUE;
+ slot_has_recover = CK_TRUE;
+#endif /* OPENSSL_NO_RSA */
+ * Check if this slot is capable of signing and
+ * verifying with CKM_DSA.
+ rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_DSA,
+ slot_has_dsa = CK_TRUE;
+#endif /* OPENSSL_NO_DSA */
+ * Check if this slot is capable of DH key generataion and
+ rv = pFuncList->C_GetMechanismInfo(current_slot,
+ CKM_DH_PKCS_KEY_PAIR_GEN, &mech_info);
+ rv = pFuncList->C_GetMechanismInfo(current_slot,
+ CKM_DH_PKCS_DERIVE, &mech_info);
+#endif /* OPENSSL_NO_DH */
+ if (!found_candidate_slot &&
+ (slot_has_rsa || slot_has_dsa || slot_has_dh))
+#ifdef DEBUG_SLOT_SELECTION
+ "%s: potential slot: %d\n", PK11_DBG, current_slot);
+#endif /* DEBUG_SLOT_SELECTION */
+ best_slot_sofar = current_slot;
+ pk11_have_rsa = slot_has_rsa;
+ pk11_have_recover = slot_has_recover;
+ pk11_have_dsa = slot_has_dsa;
+ pk11_have_dh = slot_has_dh;
+ found_candidate_slot = CK_TRUE;
+ * Cache the flags for later use. We might
+ * need those if RSA keys by reference feature
+#ifdef DEBUG_SLOT_SELECTION
+ "%s: setting found_candidate_slot to CK_TRUE\n",
+ "%s: best so far slot: %d\n", PK11_DBG,
+ fprintf(stderr, "%s: pubkey flags changed to "
+ "%lu.\n", PK11_DBG, pubkey_token_flags);
+#endif /* DEBUG_SLOT_SELECTION */
+ if (found_candidate_slot == CK_TRUE)
+ pubkey_SLOTID = best_slot_sofar;
+ found_candidate_slot = CK_FALSE;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: == checking
cipher/digest ==\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ for (i = 0; i < ulSlotCount; i++)
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
+#endif /* DEBUG_SLOT_SELECTION */
+ current_slot = pSlotList[i];
+ current_slot_n_cipher = 0;
+ current_slot_n_digest = 0;
+ (void) memset(local_cipher_nids, 0, sizeof (local_cipher_nids));
+ (void) memset(local_digest_nids, 0, sizeof (local_digest_nids));
+ pk11_find_symmetric_ciphers(pFuncList, current_slot,
+ ¤t_slot_n_cipher, local_cipher_nids);
+ pk11_find_digests(pFuncList, current_slot,
+ ¤t_slot_n_digest, local_digest_nids);
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: current_slot_n_cipher %d\n", PK11_DBG,
+ current_slot_n_cipher);
+ fprintf(stderr, "%s: current_slot_n_digest %d\n", PK11_DBG,
+ current_slot_n_digest);
+ PK11_DBG, best_slot_sofar);
+#endif /* DEBUG_SLOT_SELECTION */
+ * the previous best one we change the current best to this one,
+ * otherwise leave it where it is.
+ if ((current_slot_n_cipher + current_slot_n_digest) >
+ (slot_n_cipher + slot_n_digest))
+#ifdef DEBUG_SLOT_SELECTION
+ "%s: changing best so far slot to %d\n",
+ PK11_DBG, current_slot);
+#endif /* DEBUG_SLOT_SELECTION */
+ best_slot_sofar = SLOTID = current_slot;
+ cipher_count = slot_n_cipher = current_slot_n_cipher;
+ digest_count = slot_n_digest = current_slot_n_digest;
+ (void) memcpy(cipher_nids, local_cipher_nids,
+ sizeof (local_cipher_nids));
+ (void) memcpy(digest_nids, local_digest_nids,
+ sizeof (local_digest_nids));
+#ifdef DEBUG_SLOT_SELECTION
+ "%s: chosen pubkey slot: %d\n", PK11_DBG, pubkey_SLOTID);
+ "%s: chosen rand slot: %d\n", PK11_DBG, rand_SLOTID);
+ "%s: pk11_have_rsa %d\n", PK11_DBG, pk11_have_rsa);
+ "%s: pk11_have_recover %d\n", PK11_DBG, pk11_have_recover);
+ "%s: pk11_have_dsa %d\n", PK11_DBG, pk11_have_dsa);
+ "%s: pk11_have_dh %d\n", PK11_DBG, pk11_have_dh);
+ "%s: pk11_have_random %d\n", PK11_DBG, pk11_have_random);
+ "%s: cipher_count %d\n", PK11_DBG, cipher_count);
+ "%s: digest_count %d\n", PK11_DBG, digest_count);
+#endif /* DEBUG_SLOT_SELECTION */
+ OPENSSL_free(pSlotList);
+#ifdef SOLARIS_HW_SLOT_SELECTION
+ OPENSSL_free(hw_cnids);
+ OPENSSL_free(hw_dnids);
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+ if (any_slot_found != NULL)
+static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR pflist,
+ int slot_id, CK_MECHANISM_TYPE mech, int *current_slot_n_cipher,
+ int *local_cipher_nids, int id)
+ CK_MECHANISM_INFO mech_info;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: checking mech: %x", PK11_DBG, mech);
+#endif /* DEBUG_SLOT_SELECTION */
+ rv = pflist->C_GetMechanismInfo(slot_id, mech, &mech_info);
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, " not found\n");
+#endif /* DEBUG_SLOT_SELECTION */
+#ifdef SOLARIS_HW_SLOT_SELECTION
+ if (nid_in_table(ciphers[id].nid, hw_cnids))
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, " usable\n");
+#endif /* DEBUG_SLOT_SELECTION */
+ local_cipher_nids[(*current_slot_n_cipher)++] =
+#ifdef SOLARIS_HW_SLOT_SELECTION
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, " rejected, software implementation only\n");
+#endif /* DEBUG_SLOT_SELECTION */
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, " unusable\n");
+#endif /* DEBUG_SLOT_SELECTION */
+static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist, int slot_id,
+ CK_MECHANISM_TYPE mech, int *current_slot_n_digest, int *local_digest_nids,
+ CK_MECHANISM_INFO mech_info;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: checking mech: %x", PK11_DBG, mech);
+#endif /* DEBUG_SLOT_SELECTION */
+ rv = pflist->C_GetMechanismInfo(slot_id, mech, &mech_info);
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, " not found\n");
+#endif /* DEBUG_SLOT_SELECTION */
+#ifdef SOLARIS_HW_SLOT_SELECTION
+ if (nid_in_table(digests[id].nid, hw_dnids))
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, " usable\n");
+#endif /* DEBUG_SLOT_SELECTION */
+ local_digest_nids[(*current_slot_n_digest)++] =
+#ifdef SOLARIS_HW_SLOT_SELECTION
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, " rejected, software implementation only\n");
+#endif /* DEBUG_SLOT_SELECTION */
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, " unusable\n");
+#endif /* DEBUG_SLOT_SELECTION */
+/* create a new NID when we have no OID for that mechanism */
+static int pk11_add_NID(char *sn, char *ln)
+ if ((o = ASN1_OBJECT_create(OBJ_new_nid(1), (unsigned char *)"",
+ /* will return NID_undef on error */
+ nid = OBJ_add_object(o);
+ * Create new NIDs for AES counter mode. OpenSSL doesn't support them now so we
+ * have to help ourselves here.
+static int pk11_add_aes_ctr_NIDs(void)
+ /* are we already set? */
+ if (NID_aes_256_ctr != NID_undef)
+ * There are no official names for AES counter modes yet so we just
+ * follow the format of those that exist.
+ if ((NID_aes_128_ctr = pk11_add_NID("AES-128-CTR", "aes-128-ctr")) ==
+ if ((NID_aes_192_ctr = pk11_add_NID("AES-192-CTR", "aes-192-ctr")) ==
+ if ((NID_aes_256_ctr = pk11_add_NID("AES-256-CTR", "aes-256-ctr")) ==
+ PK11err(PK11_F_ADD_AES_CTR_NIDS, PK11_R_ADD_NID_FAILED);
+#endif /* SOLARIS_AES_CTR */
+/* Find what symmetric ciphers this slot supports. */
+static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist,
+ CK_SLOT_ID current_slot, int *current_slot_n_cipher, int *local_cipher_nids)
+ for (i = 0; i < PK11_CIPHER_MAX; ++i)
+ pk11_get_symmetric_cipher(pflist, current_slot,
+ ciphers[i].mech_type, current_slot_n_cipher,
+ local_cipher_nids, ciphers[i].id);
+/* Find what digest algorithms this slot supports. */
+static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
+ CK_SLOT_ID current_slot, int *current_slot_n_digest, int *local_digest_nids)
+ for (i = 0; i < PK11_DIGEST_MAX; ++i)
+ pk11_get_digest(pflist, current_slot, digests[i].mech_type,
+ current_slot_n_digest, local_digest_nids, digests[i].id);
+#ifdef SOLARIS_HW_SLOT_SELECTION
+ * It would be great if we could use pkcs11_kernel directly since this library
+ * offers hardware slots only. That's the easiest way to achieve the situation
+ * where we use the hardware accelerators when present and OpenSSL native code
+ * otherwise. That presumes the fact that OpenSSL native code is faster than the
+ * code in the soft token. It's a logical assumption - Crypto Framework has some
+ * inherent overhead so going there for the software implementation of a
+ * mechanism should be logically slower in contrast to the OpenSSL native code,
+ * presuming that both implementations are of similar speed. For example, the
+ * soft token for AES is roughly three times slower than OpenSSL for 64 byte
+ * blocks and still 20% slower for 8KB blocks. So, if we want to ship products
+ * that use the PKCS#11 engine by default, we must somehow avoid that regression
+ * on machines without hardware acceleration. That's why switching to the
+ * pkcs11_kernel library seems like a very good idea.
+ * The problem is that OpenSSL built with SunStudio is roughly 2x slower for
+ * asymmetric operations (
RSA/DSA/DH) than the soft token built with the same
+ * compiler. That means that if we switched to pkcs11_kernel from the libpkcs11
+ * library, we would have had a performance regression on machines without
+ * hardware acceleration for asymmetric operations for all applications that use
+ * the PKCS#11 engine. There is one such application - Apache web server since
+ * it's shipped configured to use the PKCS#11 engine by default. Having said
+ * that, we can't switch to the pkcs11_kernel library now and have to come with
+ * a solution that, on non-accelerated machines, uses the OpenSSL native code
+ * for all symmetric ciphers and digests while it uses the soft token for
+ * asymmetric operations.
+ * This is the idea: dlopen() pkcs11_kernel directly and find out what
+ * mechanisms are there. We don't care about duplications (more slots can
+ * support the same mechanism), we just want to know what mechanisms can be
+ * possibly supported in hardware on that particular machine. As said before,
+ * pkcs11_kernel will show you hardware providers only.
+ * Then, we rely on the fact that since we use libpkcs11 library we will find
+ * the metaslot. When we go through the metaslot's mechanisms for symmetric
+ * ciphers and digests, we check that any found mechanism is in the table
+ * created using the pkcs11_kernel library. So, as a result we have two arrays
+ * of mechanisms that were advertised as supported in hardware which was the
+ * goal of that whole excercise. Thus, we can use libpkcs11 but avoid soft token
+ * code for symmetric ciphers and digests. See pk11_choose_slots() for more
+ * This is Solaris specific code, if SOLARIS_HW_SLOT_SELECTION is not defined
+ * the code won't be used.
+#if defined(__sparcv9) || defined(__x86_64) || defined(__amd64)
+ * Check hardware capabilities of the machines. The output are two lists,
+ * hw_cnids and hw_dnids, that contain hardware mechanisms found in all hardware
+ * providers together. They are not sorted and may contain duplicate mechanisms.
+static int check_hw_mechanisms(void)
+ CK_C_GetFunctionList p;
+ CK_TOKEN_INFO token_info;
+ CK_ULONG ulSlotCount = 0;
+ int n_cipher = 0, n_digest = 0;
+ CK_FUNCTION_LIST_PTR pflist = NULL;
+ CK_SLOT_ID_PTR pSlotList = NULL_PTR;
+ int *tmp_hw_cnids = NULL, *tmp_hw_dnids = NULL;
+ int hw_ctable_size, hw_dtable_size;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: SOLARIS_HW_SLOT_SELECTION code running\n",
+ if ((handle = dlopen(pkcs11_kernel, RTLD_LAZY)) == NULL)
+ PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
+ if ((p = (CK_C_GetFunctionList)dlsym(handle,
+ PK11_GET_FUNCTION_LIST)) == NULL)
+ PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
+ /* get the full function list from the loaded library */
+ if (p(&pflist) != CKR_OK)
+ PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
+ rv = pflist->C_Initialize((CK_VOID_PTR)&pk11_init_args);
+ if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
+ PK11err_add_data(PK11_F_CHECK_HW_MECHANISMS,
+ PK11_R_INITIALIZE, rv);
+ if (pflist->C_GetSlotList(0, NULL_PTR, &ulSlotCount) != CKR_OK)
+ PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
+ /* no slots, set the hw mechanism tables as empty */
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: no hardware mechanisms found\n", PK11_DBG);
+ hw_cnids = OPENSSL_malloc(sizeof (int));
+ hw_dnids = OPENSSL_malloc(sizeof (int));
+ if (hw_cnids == NULL || hw_dnids == NULL)
+ PK11err(PK11_F_CHECK_HW_MECHANISMS,
+ PK11_R_MALLOC_FAILURE);
+ /* this means empty tables */
+ hw_cnids[0] = NID_undef;
+ hw_dnids[0] = NID_undef;
+ pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
+ PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
+ /* Get the slot list for processing */
+ if (pflist->C_GetSlotList(0, pSlotList, &ulSlotCount) != CKR_OK)
+ PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
+ * We don't care about duplicit mechanisms in multiple slots and also
+ * reserve one slot for the terminal NID_undef which we use to stop the
+ hw_ctable_size = ulSlotCount * PK11_CIPHER_MAX + 1;
+ hw_dtable_size = ulSlotCount * PK11_DIGEST_MAX + 1;
+ tmp_hw_cnids = OPENSSL_malloc(hw_ctable_size * sizeof (int));
+ tmp_hw_dnids = OPENSSL_malloc(hw_dtable_size * sizeof (int));
+ if (tmp_hw_cnids == NULL || tmp_hw_dnids == NULL)
+ PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
+ * Do not use memset since we should not rely on the fact that NID_undef
+ for (i = 0; i < hw_ctable_size; ++i)
+ tmp_hw_cnids[i] = NID_undef;
+ for (i = 0; i < hw_dtable_size; ++i)
+ tmp_hw_dnids[i] = NID_undef;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: provider: %s\n", PK11_DBG, pkcs11_kernel);
+ fprintf(stderr, "%s: found %d hardware slots\n", PK11_DBG, ulSlotCount);
+ fprintf(stderr, "%s: now looking for mechs supported in hw\n",
+#endif /* DEBUG_SLOT_SELECTION */
+ for (i = 0; i < ulSlotCount; i++)
+ if (pflist->C_GetTokenInfo(pSlotList[i], &token_info) != CKR_OK)
+#ifdef DEBUG_SLOT_SELECTION
+#endif /* DEBUG_SLOT_SELECTION */
+ * We are filling the hw mech tables here. Global tables are
+ * still NULL so all mechanisms are put into tmp tables.
+ pk11_find_symmetric_ciphers(pflist, pSlotList[i],
+ &n_cipher, tmp_hw_cnids);
+ pk11_find_digests(pflist, pSlotList[i],
+ &n_digest, tmp_hw_dnids);
+ * Since we are part of a library (
libcrypto.so), calling this function
+ * may have side-effects. Also, C_Finalize() is triggered by
+ pflist->C_Finalize(NULL);
+ OPENSSL_free(pSlotList);
+ (void) dlclose(handle);
+ hw_cnids = tmp_hw_cnids;
+ hw_dnids = tmp_hw_dnids;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: hw mechs check complete\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ OPENSSL_free(pSlotList);
+ if (tmp_hw_cnids != NULL)
+ OPENSSL_free(tmp_hw_cnids);
+ if (tmp_hw_dnids != NULL)
+ OPENSSL_free(tmp_hw_dnids);
+ * Check presence of a NID in the table of NIDs. The table may be NULL (
i.e.,
+static int nid_in_table(int nid, int *nid_table)
+ * a special case. NULL means that we are initializing a new
+ * the table is never full, there is always at least one
+ while (nid_table[i] != NID_undef)
+ if (nid_table[i++] == nid)
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, " (NID %d in hw table, idx %d)", nid, i);
+#endif /* DEBUG_SLOT_SELECTION */
+#endif /* SOLARIS_HW_SLOT_SELECTION */
+#endif /* OPENSSL_NO_HW_PK11CA */
+#endif /* OPENSSL_NO_HW_PK11 */
+#endif /* OPENSSL_NO_HW */
+ * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
+ * This product includes software developed by the OpenSSL Project for
+ * ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project. All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation
and/or other materials provided with the
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * licensing@OpenSSL.org.
+ * 5. Products derived from this software may not be called "OpenSSL"
+ * nor may "OpenSSL" appear in their names without prior written
+ * permission of the OpenSSL Project.
+ * 6. Redistributions of any form whatsoever must retain the following
+ * "This product includes software developed by the OpenSSL Project
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com). This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+static ERR_STRING_DATA pk11_str_functs[]=
+{ ERR_PACK(0, PK11_F_INIT, 0), "PK11_INIT"},
+{ ERR_PACK(0, PK11_F_FINISH, 0), "PK11_FINISH"},
+{ ERR_PACK(0, PK11_F_DESTROY, 0), "PK11_DESTROY"},
+{ ERR_PACK(0, PK11_F_CTRL, 0), "PK11_CTRL"},
+{ ERR_PACK(0, PK11_F_RSA_INIT, 0), "PK11_RSA_INIT"},
+{ ERR_PACK(0, PK11_F_RSA_FINISH, 0), "PK11_RSA_FINISH"},
+{ ERR_PACK(0, PK11_F_GET_PUB_RSA_KEY, 0), "PK11_GET_PUB_RSA_KEY"},
+{ ERR_PACK(0, PK11_F_GET_PRIV_RSA_KEY, 0), "PK11_GET_PRIV_RSA_KEY"},
+{ ERR_PACK(0, PK11_F_RSA_GEN_KEY, 0), "PK11_RSA_GEN_KEY"},
+{ ERR_PACK(0, PK11_F_RSA_PUB_ENC, 0), "PK11_RSA_PUB_ENC"},
+{ ERR_PACK(0, PK11_F_RSA_PRIV_ENC, 0), "PK11_RSA_PRIV_ENC"},
+{ ERR_PACK(0, PK11_F_RSA_PUB_DEC, 0), "PK11_RSA_PUB_DEC"},
+{ ERR_PACK(0, PK11_F_RSA_PRIV_DEC, 0), "PK11_RSA_PRIV_DEC"},
+{ ERR_PACK(0, PK11_F_RSA_SIGN, 0), "PK11_RSA_SIGN"},
+{ ERR_PACK(0, PK11_F_RSA_VERIFY, 0), "PK11_RSA_VERIFY"},
+{ ERR_PACK(0, PK11_F_RAND_ADD, 0), "PK11_RAND_ADD"},
+{ ERR_PACK(0, PK11_F_RAND_BYTES, 0), "PK11_RAND_BYTES"},
+{ ERR_PACK(0, PK11_F_GET_SESSION, 0), "PK11_GET_SESSION"},
+{ ERR_PACK(0, PK11_F_FREE_SESSION, 0), "PK11_FREE_SESSION"},
+{ ERR_PACK(0, PK11_F_LOAD_PUBKEY, 0), "PK11_LOAD_PUBKEY"},
+{ ERR_PACK(0, PK11_F_LOAD_PRIVKEY, 0), "PK11_LOAD_PRIV_KEY"},
+{ ERR_PACK(0, PK11_F_RSA_PUB_ENC_LOW, 0), "PK11_RSA_PUB_ENC_LOW"},
+{ ERR_PACK(0, PK11_F_RSA_PRIV_ENC_LOW, 0), "PK11_RSA_PRIV_ENC_LOW"},
+{ ERR_PACK(0, PK11_F_RSA_PUB_DEC_LOW, 0), "PK11_RSA_PUB_DEC_LOW"},
+{ ERR_PACK(0, PK11_F_RSA_PRIV_DEC_LOW, 0), "PK11_RSA_PRIV_DEC_LOW"},
+{ ERR_PACK(0, PK11_F_DSA_SIGN, 0), "PK11_DSA_SIGN"},
+{ ERR_PACK(0, PK11_F_DSA_VERIFY, 0), "PK11_DSA_VERIFY"},
+{ ERR_PACK(0, PK11_F_DSA_INIT, 0), "PK11_DSA_INIT"},
+{ ERR_PACK(0, PK11_F_DSA_FINISH, 0), "PK11_DSA_FINISH"},
+{ ERR_PACK(0, PK11_F_GET_PUB_DSA_KEY, 0), "PK11_GET_PUB_DSA_KEY"},
+{ ERR_PACK(0, PK11_F_GET_PRIV_DSA_KEY, 0), "PK11_GET_PRIV_DSA_KEY"},
+{ ERR_PACK(0, PK11_F_DH_INIT, 0), "PK11_DH_INIT"},
+{ ERR_PACK(0, PK11_F_DH_FINISH, 0), "PK11_DH_FINISH"},
+{ ERR_PACK(0, PK11_F_MOD_EXP_DH, 0), "PK11_MOD_EXP_DH"},
+{ ERR_PACK(0, PK11_F_GET_DH_KEY, 0), "PK11_GET_DH_KEY"},
+{ ERR_PACK(0, PK11_F_FREE_ALL_SESSIONS, 0), "PK11_FREE_ALL_SESSIONS"},
+{ ERR_PACK(0, PK11_F_SETUP_SESSION, 0), "PK11_SETUP_SESSION"},
+{ ERR_PACK(0, PK11_F_DESTROY_OBJECT, 0), "PK11_DESTROY_OBJECT"},
+{ ERR_PACK(0, PK11_F_CIPHER_INIT, 0), "PK11_CIPHER_INIT"},
+{ ERR_PACK(0, PK11_F_CIPHER_DO_CIPHER, 0), "PK11_CIPHER_DO_CIPHER"},
+{ ERR_PACK(0, PK11_F_GET_CIPHER_KEY, 0), "PK11_GET_CIPHER_KEY"},
+{ ERR_PACK(0, PK11_F_DIGEST_INIT, 0), "PK11_DIGEST_INIT"},
+{ ERR_PACK(0, PK11_F_DIGEST_UPDATE, 0), "PK11_DIGEST_UPDATE"},
+{ ERR_PACK(0, PK11_F_DIGEST_FINAL, 0), "PK11_DIGEST_FINAL"},
+{ ERR_PACK(0, PK11_F_CHOOSE_SLOT, 0), "PK11_CHOOSE_SLOT"},
+{ ERR_PACK(0, PK11_F_CIPHER_FINAL, 0), "PK11_CIPHER_FINAL"},
+{ ERR_PACK(0, PK11_F_LIBRARY_INIT, 0), "PK11_LIBRARY_INIT"},
+{ ERR_PACK(0, PK11_F_LOAD, 0), "ENGINE_LOAD_PK11"},
+{ ERR_PACK(0, PK11_F_DH_GEN_KEY, 0), "PK11_DH_GEN_KEY"},
+{ ERR_PACK(0, PK11_F_DH_COMP_KEY, 0), "PK11_DH_COMP_KEY"},
+{ ERR_PACK(0, PK11_F_DIGEST_COPY, 0), "PK11_DIGEST_COPY"},
+{ ERR_PACK(0, PK11_F_CIPHER_CLEANUP, 0), "PK11_CIPHER_CLEANUP"},
+{ ERR_PACK(0, PK11_F_ACTIVE_ADD, 0), "PK11_ACTIVE_ADD"},
+{ ERR_PACK(0, PK11_F_ACTIVE_DELETE, 0), "PK11_ACTIVE_DELETE"},
+{ ERR_PACK(0, PK11_F_CHECK_HW_MECHANISMS, 0), "PK11_CHECK_HW_MECHANISMS"},
+{ ERR_PACK(0, PK11_F_INIT_SYMMETRIC, 0), "PK11_INIT_SYMMETRIC"},
+{ ERR_PACK(0, PK11_F_ADD_AES_CTR_NIDS, 0), "PK11_ADD_AES_CTR_NIDS"},
+{ ERR_PACK(0, PK11_F_INIT_ALL_LOCKS, 0), "PK11_INIT_ALL_LOCKS"},
+{ ERR_PACK(0, PK11_F_RETURN_SESSION, 0), "PK11_RETURN_SESSION"},
+{ ERR_PACK(0, PK11_F_GET_PIN, 0), "PK11_GET_PIN"},
+{ ERR_PACK(0, PK11_F_FIND_ONE_OBJECT, 0), "PK11_FIND_ONE_OBJECT"},
+{ ERR_PACK(0, PK11_F_CHECK_TOKEN_ATTRS, 0), "PK11_CHECK_TOKEN_ATTRS"},
+{ ERR_PACK(0, PK11_F_CACHE_PIN, 0), "PK11_CACHE_PIN"},
+{ ERR_PACK(0, PK11_F_MLOCK_PIN_IN_MEMORY, 0), "PK11_MLOCK_PIN_IN_MEMORY"},
+{ ERR_PACK(0, PK11_F_TOKEN_LOGIN, 0), "PK11_TOKEN_LOGIN"},
+{ ERR_PACK(0, PK11_F_TOKEN_RELOGIN, 0), "PK11_TOKEN_RELOGIN"},
+{ ERR_PACK(0, PK11_F_RUN_ASKPASS, 0), "PK11_F_RUN_ASKPASS"},
+static ERR_STRING_DATA pk11_str_reasons[]=
+{ PK11_R_ALREADY_LOADED, "PKCS#11 DSO already loaded"},
+{ PK11_R_DSO_FAILURE, "unable to load PKCS#11 DSO"},
+{ PK11_R_NOT_LOADED, "PKCS#11 DSO not loaded"},
+{ PK11_R_PASSED_NULL_PARAMETER, "null parameter passed"},
+{ PK11_R_COMMAND_NOT_IMPLEMENTED, "command not implemented"},
+{ PK11_R_INITIALIZE, "C_Initialize failed"},
+{ PK11_R_FINALIZE, "C_Finalize failed"},
+{ PK11_R_GETINFO, "C_GetInfo faile"},
+{ PK11_R_GETSLOTLIST, "C_GetSlotList failed"},
+{ PK11_R_NO_MODULUS_OR_NO_EXPONENT, "no modulus or no exponent"},
+{ PK11_R_ATTRIBUT_SENSITIVE_OR_INVALID, "attr sensitive or invalid"},
+{ PK11_R_GETATTRIBUTVALUE, "C_GetAttributeValue failed"},
+{ PK11_R_NO_MODULUS, "no modulus"},
+{ PK11_R_NO_EXPONENT, "no exponent"},
+{ PK11_R_FINDOBJECTSINIT, "C_FindObjectsInit failed"},
+{ PK11_R_FINDOBJECTS, "C_FindObjects failed"},
+{ PK11_R_FINDOBJECTSFINAL, "C_FindObjectsFinal failed"},
+{ PK11_R_CREATEOBJECT, "C_CreateObject failed"},
+{ PK11_R_DESTROYOBJECT, "C_DestroyObject failed"},
+{ PK11_R_OPENSESSION, "C_OpenSession failed"},
+{ PK11_R_CLOSESESSION, "C_CloseSession failed"},
+{ PK11_R_ENCRYPTINIT, "C_EncryptInit failed"},
+{ PK11_R_ENCRYPT, "C_Encrypt failed"},
+{ PK11_R_SIGNINIT, "C_SignInit failed"},
+{ PK11_R_SIGN, "C_Sign failed"},
+{ PK11_R_DECRYPTINIT, "C_DecryptInit failed"},
+{ PK11_R_DECRYPT, "C_Decrypt failed"},
+{ PK11_R_VERIFYINIT, "C_VerifyRecover failed"},
+{ PK11_R_VERIFY, "C_Verify failed"},
+{ PK11_R_VERIFYRECOVERINIT, "C_VerifyRecoverInit failed"},
+{ PK11_R_VERIFYRECOVER, "C_VerifyRecover failed"},
+{ PK11_R_GEN_KEY, "C_GenerateKeyPair failed"},
+{ PK11_R_SEEDRANDOM, "C_SeedRandom failed"},
+{ PK11_R_GENERATERANDOM, "C_GenerateRandom failed"},
+{ PK11_R_INVALID_MESSAGE_LENGTH, "invalid message length"},
+{ PK11_R_UNKNOWN_ALGORITHM_TYPE, "unknown algorithm type"},
+{ PK11_R_UNKNOWN_ASN1_OBJECT_ID, "unknown asn1 onject id"},
+{ PK11_R_UNKNOWN_PADDING_TYPE, "unknown padding type"},
+{ PK11_R_PADDING_CHECK_FAILED, "padding check failed"},
+{ PK11_R_DIGEST_TOO_BIG, "digest too big"},
+{ PK11_R_MALLOC_FAILURE, "malloc failure"},
+{ PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED, "ctl command not implemented"},
+{ PK11_R_DATA_GREATER_THAN_MOD_LEN, "data is bigger than mod"},
+{ PK11_R_DATA_TOO_LARGE_FOR_MODULUS, "data is too larger for mod"},
+{ PK11_R_MISSING_KEY_COMPONENT, "a dsa component is missing"},
+{ PK11_R_INVALID_SIGNATURE_LENGTH, "invalid signature length"},
+{ PK11_R_INVALID_DSA_SIGNATURE_R, "missing r in dsa verify"},
+{ PK11_R_INVALID_DSA_SIGNATURE_S, "missing s in dsa verify"},
+{ PK11_R_INCONSISTENT_KEY, "inconsistent key type"},
+{ PK11_R_ENCRYPTUPDATE, "C_EncryptUpdate failed"},
+{ PK11_R_DECRYPTUPDATE, "C_DecryptUpdate failed"},
+{ PK11_R_DIGESTINIT, "C_DigestInit failed"},
+{ PK11_R_DIGESTUPDATE, "C_DigestUpdate failed"},
+{ PK11_R_DIGESTFINAL, "C_DigestFinal failed"},
+{ PK11_R_ENCRYPTFINAL, "C_EncryptFinal failed"},
+{ PK11_R_DECRYPTFINAL, "C_DecryptFinal failed"},
+{ PK11_R_NO_PRNG_SUPPORT, "Slot does not support PRNG"},
+{ PK11_R_GETTOKENINFO, "C_GetTokenInfo failed"},
+{ PK11_R_DERIVEKEY, "C_DeriveKey failed"},
+{ PK11_R_GET_OPERATION_STATE, "C_GetOperationState failed"},
+{ PK11_R_SET_OPERATION_STATE, "C_SetOperationState failed"},
+{ PK11_R_INVALID_HANDLE, "invalid PKCS#11 object handle"},
+{ PK11_R_KEY_OR_IV_LEN_PROBLEM, "IV or key length incorrect"},
+{ PK11_R_INVALID_OPERATION_TYPE, "invalid operation type"},
+{ PK11_R_ADD_NID_FAILED, "failed to add NID" },
+{ PK11_R_ATFORK_FAILED, "atfork() failed" },
+{ PK11_R_TOKEN_LOGIN_FAILED, "C_Login() failed on token" },
+{ PK11_R_MORE_THAN_ONE_OBJECT_FOUND, "more than one object found" },
+{ PK11_R_INVALID_PKCS11_URI, "pkcs11 URI provided is invalid" },
+{ PK11_R_COULD_NOT_READ_PIN, "could not read PIN from terminal" },
+{ PK11_R_PIN_NOT_READ_FROM_COMMAND, "PIN not read from external command" },
+{ PK11_R_COULD_NOT_OPEN_COMMAND, "could not popen() dialog command" },
+{ PK11_R_PIPE_FAILED, "pipe() failed" },
+{ PK11_R_BAD_PASSPHRASE_SPEC, "bad passphrasedialog specification" },
+{ PK11_R_TOKEN_NOT_INITIALIZED, "token not initialized" },
+{ PK11_R_TOKEN_PIN_NOT_SET, "token PIN required but not set" },
+{ PK11_R_TOKEN_PIN_NOT_PROVIDED, "token PIN required but not provided" },
+{ PK11_R_MISSING_OBJECT_LABEL, "missing mandatory 'object' keyword" },
+{ PK11_R_TOKEN_ATTRS_DO_NOT_MATCH, "token attrs provided do not match" },
+{ PK11_R_PRIV_KEY_NOT_FOUND, "private key not found in keystore" },
+{ PK11_R_NO_OBJECT_FOUND, "specified object not found" },
+{ PK11_R_PIN_CACHING_POLICY_INVALID, "PIN set but caching policy invalid" },
+{ PK11_R_SYSCONF_FAILED, "sysconf() failed" },
+{ PK11_R_MMAP_FAILED, "mmap() failed" },
+{ PK11_R_PRIV_PROC_LOCK_MEMORY_MISSING, "PROC_LOCK_MEMORY privilege missing" },
+{ PK11_R_MLOCK_FAILED, "mlock() failed" },
+{ PK11_R_FORK_FAILED, "fork() failed" },
+#endif /* OPENSSL_NO_ERR */
+static int pk11_lib_error_code = 0;
+static int pk11_error_init = 1;
+ERR_load_pk11_strings(void)
+ if (pk11_lib_error_code == 0)
+ pk11_lib_error_code = ERR_get_next_error_library();
+ ERR_load_strings(pk11_lib_error_code, pk11_str_functs);
+ ERR_load_strings(pk11_lib_error_code, pk11_str_reasons);
+ERR_unload_pk11_strings(void)
+ if (pk11_error_init == 0)
+ ERR_unload_strings(pk11_lib_error_code, pk11_str_functs);
+ ERR_unload_strings(pk11_lib_error_code, pk11_str_reasons);
+ERR_pk11_error(int function, int reason, char *file, int line)
+ if (pk11_lib_error_code == 0)
+ pk11_lib_error_code = ERR_get_next_error_library();
+ ERR_PUT_error(pk11_lib_error_code, function, reason, file, line);
+PK11err_add_data(int function, int reason, CK_RV rv)
+ PK11err(function, reason);
+ (void) BIO_snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+ ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+ * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
+ * This product includes software developed by the OpenSSL Project for
+ * ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project. All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation
and/or other materials provided with the
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * licensing@OpenSSL.org.
+ * 5. Products derived from this software may not be called "OpenSSL"
+ * nor may "OpenSSL" appear in their names without prior written
+ * permission of the OpenSSL Project.
+ * 6. Redistributions of any form whatsoever must retain the following
+ * "This product includes software developed by the OpenSSL Project
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com). This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+void ERR_pk11_error(int function, int reason, char *file, int line);
+void PK11err_add_data(int function, int reason, CK_RV rv);
+#define PK11err(f, r) ERR_pk11_error((f), (r), __FILE__, __LINE__)
+/* Error codes for the PK11 functions. */
+#define PK11_F_FINISH 101
+#define PK11_F_DESTROY 102
+#define PK11_F_RSA_INIT 104
+#define PK11_F_RSA_FINISH 105
+#define PK11_F_GET_PUB_RSA_KEY 106
+#define PK11_F_GET_PRIV_RSA_KEY 107
+#define PK11_F_RSA_GEN_KEY 108
+#define PK11_F_RSA_PUB_ENC 109
+#define PK11_F_RSA_PRIV_ENC 110
+#define PK11_F_RSA_PUB_DEC 111
+#define PK11_F_RSA_PRIV_DEC 112
+#define PK11_F_RSA_SIGN 113
+#define PK11_F_RSA_VERIFY 114
+#define PK11_F_RAND_ADD 115
+#define PK11_F_RAND_BYTES 116
+#define PK11_F_GET_SESSION 117
+#define PK11_F_FREE_SESSION 118
+#define PK11_F_LOAD_PUBKEY 119
+#define PK11_F_LOAD_PRIVKEY 120
+#define PK11_F_RSA_PUB_ENC_LOW 121
+#define PK11_F_RSA_PRIV_ENC_LOW 122
+#define PK11_F_RSA_PUB_DEC_LOW 123
+#define PK11_F_RSA_PRIV_DEC_LOW 124
+#define PK11_F_DSA_SIGN 125
+#define PK11_F_DSA_VERIFY 126
+#define PK11_F_DSA_INIT 127
+#define PK11_F_DSA_FINISH 128
+#define PK11_F_GET_PUB_DSA_KEY 129
+#define PK11_F_GET_PRIV_DSA_KEY 130
+#define PK11_F_DH_INIT 131
+#define PK11_F_DH_FINISH 132
+#define PK11_F_MOD_EXP_DH 133
+#define PK11_F_GET_DH_KEY 134
+#define PK11_F_FREE_ALL_SESSIONS 135
+#define PK11_F_SETUP_SESSION 136
+#define PK11_F_DESTROY_OBJECT 137
+#define PK11_F_CIPHER_INIT 138
+#define PK11_F_CIPHER_DO_CIPHER 139
+#define PK11_F_GET_CIPHER_KEY 140
+#define PK11_F_DIGEST_INIT 141
+#define PK11_F_DIGEST_UPDATE 142
+#define PK11_F_DIGEST_FINAL 143
+#define PK11_F_CHOOSE_SLOT 144
+#define PK11_F_CIPHER_FINAL 145
+#define PK11_F_LIBRARY_INIT 146
+#define PK11_F_DH_GEN_KEY 148
+#define PK11_F_DH_COMP_KEY 149
+#define PK11_F_DIGEST_COPY 150
+#define PK11_F_CIPHER_CLEANUP 151
+#define PK11_F_ACTIVE_ADD 152
+#define PK11_F_ACTIVE_DELETE 153
+#define PK11_F_CHECK_HW_MECHANISMS 154
+#define PK11_F_INIT_SYMMETRIC 155
+#define PK11_F_ADD_AES_CTR_NIDS 156
+#define PK11_F_INIT_ALL_LOCKS 157
+#define PK11_F_RETURN_SESSION 158
+#define PK11_F_GET_PIN 159
+#define PK11_F_FIND_ONE_OBJECT 160
+#define PK11_F_CHECK_TOKEN_ATTRS 161
+#define PK11_F_CACHE_PIN 162
+#define PK11_F_MLOCK_PIN_IN_MEMORY 163
+#define PK11_F_TOKEN_LOGIN 164
+#define PK11_F_TOKEN_RELOGIN 165
+#define PK11_F_RUN_ASKPASS 166
+#define PK11_R_ALREADY_LOADED 100
+#define PK11_R_DSO_FAILURE 101
+#define PK11_R_NOT_LOADED 102
+#define PK11_R_PASSED_NULL_PARAMETER 103
+#define PK11_R_COMMAND_NOT_IMPLEMENTED 104
+#define PK11_R_INITIALIZE 105
+#define PK11_R_FINALIZE 106
+#define PK11_R_GETINFO 107
+#define PK11_R_GETSLOTLIST 108
+#define PK11_R_NO_MODULUS_OR_NO_EXPONENT 109
+#define PK11_R_ATTRIBUT_SENSITIVE_OR_INVALID 110
+#define PK11_R_GETATTRIBUTVALUE 111
+#define PK11_R_NO_MODULUS 112
+#define PK11_R_NO_EXPONENT 113
+#define PK11_R_FINDOBJECTSINIT 114
+#define PK11_R_FINDOBJECTS 115
+#define PK11_R_FINDOBJECTSFINAL 116
+#define PK11_R_CREATEOBJECT 118
+#define PK11_R_DESTROYOBJECT 119
+#define PK11_R_OPENSESSION 120
+#define PK11_R_CLOSESESSION 121
+#define PK11_R_ENCRYPTINIT 122
+#define PK11_R_ENCRYPT 123
+#define PK11_R_SIGNINIT 124
+#define PK11_R_DECRYPTINIT 126
+#define PK11_R_DECRYPT 127
+#define PK11_R_VERIFYINIT 128
+#define PK11_R_VERIFY 129
+#define PK11_R_VERIFYRECOVERINIT 130
+#define PK11_R_VERIFYRECOVER 131
+#define PK11_R_GEN_KEY 132
+#define PK11_R_SEEDRANDOM 133
+#define PK11_R_GENERATERANDOM 134
+#define PK11_R_INVALID_MESSAGE_LENGTH 135
+#define PK11_R_UNKNOWN_ALGORITHM_TYPE 136
+#define PK11_R_UNKNOWN_ASN1_OBJECT_ID 137
+#define PK11_R_UNKNOWN_PADDING_TYPE 138
+#define PK11_R_PADDING_CHECK_FAILED 139
+#define PK11_R_DIGEST_TOO_BIG 140
+#define PK11_R_MALLOC_FAILURE 141
+#define PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED 142
+#define PK11_R_DATA_GREATER_THAN_MOD_LEN 143
+#define PK11_R_DATA_TOO_LARGE_FOR_MODULUS 144
+#define PK11_R_MISSING_KEY_COMPONENT 145
+#define PK11_R_INVALID_SIGNATURE_LENGTH 146
+#define PK11_R_INVALID_DSA_SIGNATURE_R 147
+#define PK11_R_INVALID_DSA_SIGNATURE_S 148
+#define PK11_R_INCONSISTENT_KEY 149
+#define PK11_R_ENCRYPTUPDATE 150
+#define PK11_R_DECRYPTUPDATE 151
+#define PK11_R_DIGESTINIT 152
+#define PK11_R_DIGESTUPDATE 153
+#define PK11_R_DIGESTFINAL 154
+#define PK11_R_ENCRYPTFINAL 155
+#define PK11_R_DECRYPTFINAL 156
+#define PK11_R_NO_PRNG_SUPPORT 157
+#define PK11_R_GETTOKENINFO 158
+#define PK11_R_DERIVEKEY 159
+#define PK11_R_GET_OPERATION_STATE 160
+#define PK11_R_SET_OPERATION_STATE 161
+#define PK11_R_INVALID_HANDLE 162
+#define PK11_R_KEY_OR_IV_LEN_PROBLEM 163
+#define PK11_R_INVALID_OPERATION_TYPE 164
+#define PK11_R_ADD_NID_FAILED 165
+#define PK11_R_ATFORK_FAILED 166
+#define PK11_R_TOKEN_LOGIN_FAILED 167
+#define PK11_R_MORE_THAN_ONE_OBJECT_FOUND 168
+#define PK11_R_INVALID_PKCS11_URI 169
+#define PK11_R_COULD_NOT_READ_PIN 170
+#define PK11_R_COULD_NOT_OPEN_COMMAND 171
+#define PK11_R_PIPE_FAILED 172
+#define PK11_R_PIN_NOT_READ_FROM_COMMAND 173
+#define PK11_R_BAD_PASSPHRASE_SPEC 174
+#define PK11_R_TOKEN_NOT_INITIALIZED 175
+#define PK11_R_TOKEN_PIN_NOT_SET 176
+#define PK11_R_TOKEN_PIN_NOT_PROVIDED 177
+#define PK11_R_MISSING_OBJECT_LABEL 178
+#define PK11_R_TOKEN_ATTRS_DO_NOT_MATCH 179
+#define PK11_R_PRIV_KEY_NOT_FOUND 180
+#define PK11_R_NO_OBJECT_FOUND 181
+#define PK11_R_PIN_CACHING_POLICY_INVALID 182
+#define PK11_R_SYSCONF_FAILED 183
+#define PK11_R_MMAP_FAILED 183
+#define PK11_R_PRIV_PROC_LOCK_MEMORY_MISSING 184
+#define PK11_R_MLOCK_FAILED 185
+#define PK11_R_FORK_FAILED 186
+/* max byte length of a symetric key we support */
+#define PK11_KEY_LEN_MAX 32
+ * CRYPTO_LOCK_PK11_ENGINE lock is primarily used for the protection of the
+ * free_session list and active_list but generally serves as a global
+ * per-process lock for the whole engine.
+ * We reuse CRYPTO_LOCK_EC lock (which is defined in OpenSSL for EC method) as
+ * the global engine lock. This is not optimal
w.r.t. performance but
+#define CRYPTO_LOCK_PK11_ENGINE CRYPTO_LOCK_EC
+ * This structure encapsulates all reusable information for a PKCS#11
+ * session. A list of these objects is created on behalf of the
+ * calling application using an on-demand method. Each operation
+ * type (see PK11_OPTYPE below) has its own per-process list.
+ * Each of the lists is basically a cache for faster PKCS#11 object
+ * access to avoid expensive C_Find{,Init,Final}Object() calls.
+ * When a new request comes in, an object will be taken from the list
+ * (if there is one) or a new one is created to handle the request
+ * (if the list is empty). See pk11_get_session() on how it is done.
+typedef struct PK11_st_SESSION
+ struct PK11_st_SESSION *next;
+ CK_SESSION_HANDLE session; /* PK11 session handle */
+ pid_t pid; /* Current process ID */
+ CK_BBOOL pub_persistent; /* is pub key in keystore? */
+ CK_BBOOL priv_persistent;/* is priv key in keystore? */
+ CK_OBJECT_HANDLE rsa_pub_key; /* pub handle */
+ CK_OBJECT_HANDLE rsa_priv_key; /* priv handle */
+ RSA *rsa_pub; /* pub key addr */
+ BIGNUM *rsa_n_num; /* pub modulus */
+ BIGNUM *rsa_e_num; /* pub exponent */
+ RSA *rsa_priv; /* priv key addr */
+ BIGNUM *rsa_pn_num; /* pub modulus */
+ BIGNUM *rsa_pe_num; /* pub exponent */
+ BIGNUM *rsa_d_num; /* priv exponent */
+#endif /* OPENSSL_NO_RSA */
+ CK_OBJECT_HANDLE dsa_pub_key; /* pub handle */
+ CK_OBJECT_HANDLE dsa_priv_key; /* priv handle */
+ DSA *dsa_pub; /* pub key addr */
+ BIGNUM *dsa_pub_num; /* pub key */
+ DSA *dsa_priv; /* priv key addr */
+ BIGNUM *dsa_priv_num; /* priv key */
+#endif /* OPENSSL_NO_DSA */
+ CK_OBJECT_HANDLE dh_key; /* key handle */
+ DH *dh; /* dh key addr */
+ BIGNUM *dh_priv_num; /* priv dh key */
+#endif /* OPENSSL_NO_DH */
+ CK_OBJECT_HANDLE cipher_key; /* key handle */
+ unsigned char key[PK11_KEY_LEN_MAX];
+ int key_len; /* priv key len */
+ * We have 3 different groups of operation types:
+ * 1) asymmetric operations
+ * 3) symmetric and digest operations
+ * This division into groups stems from the fact that it's common that hardware
+ * providers may support operations from one group only. For example, hardware
+ * providers on UltraSPARC T2, n2rng(7d), ncp(7d), and n2cp(7d), each support
+ * only a single group of operations.
+ * For every group a different slot can be chosen. That means that we must have
+ * at least 3 different lists of cached PKCS#11 sessions since sessions from
+ * different groups may be initialized in different slots.
+ * To provide locking granularity in multithreaded environment, the groups are
+ * further splitted into types with each type having a separate session cache.
+typedef enum PK11_OPTYPE_ENUM
+ * This structure contains the heads of the lists forming the object caches
+ * and locks associated with the lists.
+typedef struct PK11_st_CACHE
+/* structure for tracking handles of asymmetric key objects */
+typedef struct PK11_active_st
+ struct PK11_active_st *prev;
+ struct PK11_active_st *next;
+extern pthread_mutex_t *find_lock[];
+extern PK11_active *active_list[];
+ * These variables are specific for the RSA keys by reference code. See
+extern CK_FLAGS pubkey_token_flags;
+#define LOCK_OBJSTORE(alg_type) \
+ OPENSSL_assert(pthread_mutex_lock(find_lock[alg_type]) == 0)
+#define UNLOCK_OBJSTORE(alg_type) \
+ OPENSSL_assert(pthread_mutex_unlock(find_lock[alg_type]) == 0)
+#define LOCK_OBJSTORE(alg_type) \
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE)
+#define UNLOCK_OBJSTORE(alg_type) \
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE)
+extern PK11_SESSION *pk11_get_session(PK11_OPTYPE optype);
+extern void pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype);
+extern int pk11_token_relogin(CK_SESSION_HANDLE session);
+extern int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
+extern int pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
+extern int pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
+extern EVP_PKEY *pk11_load_privkey(ENGINE *e, const char *pubkey_file,
+ UI_METHOD *ui_method, void *callback_data);
+extern EVP_PKEY *pk11_load_pubkey(ENGINE *e, const char *pubkey_file,
+ UI_METHOD *ui_method, void *callback_data);
+extern RSA_METHOD *PK11_RSA(void);
+#endif /* OPENSSL_NO_RSA */
+extern int pk11_destroy_dsa_key_objects(PK11_SESSION *session);
+extern int pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
+extern int pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
+extern DSA_METHOD *PK11_DSA(void);
+#endif /* OPENSSL_NO_DSA */
+extern int pk11_destroy_dh_key_objects(PK11_SESSION *session);
+extern int pk11_destroy_dh_object(PK11_SESSION *sp, CK_BBOOL uselock);
+extern DH_METHOD *PK11_DH(void);
+#endif /* OPENSSL_NO_DH */
+extern CK_FUNCTION_LIST_PTR pFuncList;
+#endif /* HW_PK11_ERR_H */
+ * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
+ * This product includes software developed by the OpenSSL Project for
+ * ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project. All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation
and/or other materials provided with the
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * licensing@OpenSSL.org.
+ * 5. Products derived from this software may not be called "OpenSSL"
+ * nor may "OpenSSL" appear in their names without prior written
+ * permission of the OpenSSL Project.
+ * 6. Redistributions of any form whatsoever must retain the following
+ * "This product includes software developed by the OpenSSL Project
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com). This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+#endif /* OPENSSL_NO_RSA */
+#endif /* OPENSSL_NO_DSA */
+#endif /* OPENSSL_NO_DH */
+#ifdef OPENSSL_SYS_WIN32
+#define HAVE_GETPASSPHRASE
+static char *getpassphrase(const char *prompt);
+#define CK_DEFINE_FUNCTION(returnType, name) \
+ returnType __declspec(dllexport) name
+#define CK_DECLARE_FUNCTION(returnType, name) \
+ returnType __declspec(dllimport) name
+#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ returnType __declspec(dllimport) (* name)
+#ifndef OPENSSL_NO_HW_PK11
+#ifndef OPENSSL_NO_HW_PK11CA
+#ifdef OPENSSL_SYS_WIN32
+#pragma pack(push, cryptoki, 1)
+#pragma pack(pop, cryptoki)
+static CK_BBOOL pk11_login_done = CK_FALSE;
+extern CK_SLOT_ID pubkey_SLOTID;
+extern pthread_mutex_t *token_lock;
+#if !(defined(HAVE_GETPASSPHRASE) || (defined (__SVR4) && defined (__sun)))
+#define getpassphrase(x) getpass(x)
+static int pk11_RSA_public_encrypt(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding);
+static int pk11_RSA_private_encrypt(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding);
+static int pk11_RSA_public_decrypt(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding);
+static int pk11_RSA_private_decrypt(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding);
+static int pk11_RSA_init(RSA *rsa);
+static int pk11_RSA_finish(RSA *rsa);
+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
+ unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
+#if OPENSSL_VERSION_NUMBER < 0x10000000L
+static int pk11_RSA_verify(int dtype, const unsigned char *m,
+ unsigned int m_len, unsigned char *sigbuf, unsigned int siglen,
+static int pk11_RSA_verify(int dtype, const unsigned char *m,
+ unsigned int m_len, const unsigned char *sigbuf, unsigned int siglen,
+EVP_PKEY *pk11_load_privkey(ENGINE*, const char *privkey_file,
+ UI_METHOD *ui_method, void *callback_data);
+EVP_PKEY *pk11_load_pubkey(ENGINE*, const char *pubkey_file,
+ UI_METHOD *ui_method, void *callback_data);
+static int pk11_RSA_public_encrypt_low(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa);
+static int pk11_RSA_private_encrypt_low(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa);
+static int pk11_RSA_public_decrypt_low(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa);
+static int pk11_RSA_private_decrypt_low(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa);
+static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA* rsa, RSA** key_ptr,
+ BIGNUM **rsa_n_num, BIGNUM **rsa_e_num, CK_SESSION_HANDLE session);
+static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA* rsa, RSA** key_ptr,
+ BIGNUM **rsa_d_num, BIGNUM **rsa_n_num, BIGNUM **rsa_e_num,
+ CK_SESSION_HANDLE session);
+static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa);
+static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa);
+static int pk11_DSA_init(DSA *dsa);
+static int pk11_DSA_finish(DSA *dsa);
+static DSA_SIG *pk11_dsa_do_sign(const unsigned char *dgst, int dlen,
+static int pk11_dsa_do_verify(const unsigned char *dgst, int dgst_len,
+ DSA_SIG *sig, DSA *dsa);
+static CK_OBJECT_HANDLE pk11_get_public_dsa_key(DSA* dsa, DSA **key_ptr,
+ BIGNUM **dsa_pub_num, CK_SESSION_HANDLE session);
+static CK_OBJECT_HANDLE pk11_get_private_dsa_key(DSA* dsa, DSA **key_ptr,
+ BIGNUM **dsa_priv_num, CK_SESSION_HANDLE session);
+static int check_new_dsa_key_pub(PK11_SESSION *sp, DSA *dsa);
+static int check_new_dsa_key_priv(PK11_SESSION *sp, DSA *dsa);
+static int pk11_DH_init(DH *dh);
+static int pk11_DH_finish(DH *dh);
+static int pk11_DH_generate_key(DH *dh);
+static int pk11_DH_compute_key(unsigned char *key,
+ const BIGNUM *pub_key, DH *dh);
+static CK_OBJECT_HANDLE pk11_get_dh_key(DH* dh, DH **key_ptr,
+ BIGNUM **priv_key, CK_SESSION_HANDLE session);
+static int check_new_dh_key(PK11_SESSION *sp, DH *dh);
+static int find_one_object(PK11_OPTYPE op, CK_SESSION_HANDLE s,
+ CK_ATTRIBUTE_PTR ptempl, CK_ULONG nattr, CK_OBJECT_HANDLE_PTR pkey);
+static int init_template_value(BIGNUM *bn, CK_VOID_PTR *pValue,
+static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn);
+static int pk11_token_login(CK_SESSION_HANDLE session, CK_BBOOL *login_done,
+/* Read mode string to be used for fopen() */
+static char *read_mode_flags = "rF";
+static char *read_mode_flags = "r";
+ * manipulation. If active list operation fails, unlock (if locked), set error
+ * variable and jump to the specified label.
+#define KEY_HANDLE_REFHOLD(key_handle, alg_type, unlock, var, label) \
+ if (pk11_active_add(key_handle, alg_type) < 0) \
+ UNLOCK_OBJSTORE(alg_type); \
+ * Find active list entry according to object handle and return pointer to the
+ * entry otherwise return NULL.
+ * This function presumes it is called with lock protecting the active list
+static PK11_active *pk11_active_find(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
+ for (entry = active_list[type]; entry != NULL; entry = entry->next)
+ * Search for an entry in the active list using PKCS#11 object handle as a
+ * search key and return refcnt of the
found/created entry or -1 in case of
+ * This function presumes it is called with lock protecting the active list
+pk11_active_add(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
+ PK11_active *entry = NULL;
+ if (h == CK_INVALID_HANDLE)
+ PK11err(PK11_F_ACTIVE_ADD, PK11_R_INVALID_HANDLE);
+ /* search for entry in the active list */
+ if ((entry = pk11_active_find(h, type)) != NULL)
+ /* not found, create new entry and add it to the list */
+ entry = OPENSSL_malloc(sizeof (PK11_active));
+ PK11err(PK11_F_ACTIVE_ADD, PK11_R_MALLOC_FAILURE);
+ /* connect the newly created entry to the list */
+ if (active_list[type] == NULL)
+ active_list[type] = entry;
+ else /* make the entry first in the list */
+ entry->next = active_list[type];
+ active_list[type]->prev = entry;
+ active_list[type] = entry;
+ return (entry->refcnt);
+ * Remove active list entry from the list and free it.
+ * This function presumes it is called with lock protecting the active list
+pk11_active_remove(PK11_active *entry, PK11_OPTYPE type)
+ PK11_active *prev_entry;
+ /* remove the entry from the list and free it */
+ if ((prev_entry = entry->prev) != NULL)
+ prev_entry->next = entry->next;
+ if (entry->next != NULL)
+ entry->next->prev = prev_entry;
+ active_list[type] = entry->next;
+ /* we were the first but not the only one */
+ if (entry->next != NULL)
+ entry->next->prev = NULL;
+ entry->h = CK_INVALID_HANDLE;
+/* Free all entries from the active list. */
+pk11_free_active_list(PK11_OPTYPE type)
+ /* only for asymmetric types since only they have C_Find* locks. */
+ /* see find_lock array definition for more info on object locking */
+ while ((entry = active_list[type]) != NULL)
+ pk11_active_remove(entry, type);
+ * Search for active list entry associated with given PKCS#11 object handle,
+ * decrement its refcnt and if it drops to 0, disconnect the entry and free it.
+ * Return 1 if the PKCS#11 object associated with the entry has no references,
+ * return 0 if there is at least one reference, -1 on error.
+ * This function presumes it is called with lock protecting the active list
+pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
+ PK11_active *entry = NULL;
+ if ((entry = pk11_active_find(h, type)) == NULL)
+ PK11err(PK11_F_ACTIVE_DELETE, PK11_R_INVALID_HANDLE);
+ OPENSSL_assert(entry->refcnt > 0);
+ if (entry->refcnt == 0)
+ pk11_active_remove(entry, type);
+/* Our internal RSA_METHOD that we provide pointers to */
+static RSA_METHOD pk11_rsa =
+ pk11_RSA_public_encrypt, /* rsa_pub_encrypt */
+ pk11_RSA_public_decrypt, /* rsa_pub_decrypt */
+ pk11_RSA_private_encrypt, /* rsa_priv_encrypt */
+ pk11_RSA_private_decrypt, /* rsa_priv_decrypt */
+ NULL, /* rsa_mod_exp */
+ pk11_RSA_init, /* init */
+ pk11_RSA_finish, /* finish */
+ RSA_FLAG_SIGN_VER, /* flags */
+ pk11_RSA_sign, /* rsa_sign */
+ pk11_RSA_verify /* rsa_verify */
+/* Our internal DSA_METHOD that we provide pointers to */
+static DSA_METHOD pk11_dsa =
+ pk11_dsa_do_sign, /* dsa_do_sign */
+ NULL, /* dsa_sign_setup */
+ pk11_dsa_do_verify, /* dsa_do_verify */
+ NULL, /* dsa_mod_exp */
+ pk11_DSA_init, /* init */
+ pk11_DSA_finish, /* finish */
+ * PKCS #11 V2.20, section 11.2 specifies that the number of bytes needed for
+ * output buffer may somewhat exceed the precise number of bytes needed, but
+ * should not exceed it by a large amount. That may be caused, for example, by
+ * rounding it up to multiple of X in the underlying bignum library. 8 should be
+#define DH_BUF_RESERVE 8
+/* Our internal DH_METHOD that we provide pointers to */
+static DH_METHOD pk11_dh =
+ pk11_DH_generate_key, /* generate_key */
+ pk11_DH_compute_key, /* compute_key */
+ pk11_DH_init, /* init */
+ pk11_DH_finish, /* finish */
+ NULL /* generate_params */
+/* Size of an SSL signature: MD5+SHA1 */
+#define SSL_SIG_LENGTH 36
+/* Lengths of DSA data and signature */
+#define DSA_SIGNATURE_LEN 40
+static CK_BBOOL mytrue = TRUE;
+static CK_BBOOL myfalse = FALSE;
+ * Similiar to OpenSSL to take advantage of the paddings. The goal is to
+ * support all paddings in this engine although PK11 library does not
+ * support all the paddings used in OpenSSL.
+ * The input errors should have been checked in the padding functions.
+static int pk11_RSA_public_encrypt(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding)
+ int i, num = 0, r = -1;
+ unsigned char *buf = NULL;
+ num = BN_num_bytes(rsa->n);
+ if ((buf = (unsigned char *)OPENSSL_malloc(num)) == NULL)
+ RSAerr(PK11_F_RSA_PUB_ENC, PK11_R_MALLOC_FAILURE);
+ case RSA_PKCS1_PADDING:
+ i = RSA_padding_add_PKCS1_type_2(buf, num, from, flen);
+ case RSA_PKCS1_OAEP_PADDING:
+ i = RSA_padding_add_PKCS1_OAEP(buf, num, from, flen, NULL, 0);
+ case RSA_SSLV23_PADDING:
+ i = RSA_padding_add_SSLv23(buf, num, from, flen);
+ i = RSA_padding_add_none(buf, num, from, flen);
+ RSAerr(PK11_F_RSA_PUB_ENC, PK11_R_UNKNOWN_PADDING_TYPE);
+ /* PK11 functions are called here */
+ r = pk11_RSA_public_encrypt_low(num, buf, to, rsa);
+ OPENSSL_cleanse(buf, num);
+ * Similar to Openssl to take advantage of the paddings. The input errors
+ * should be catched in the padding functions
+static int pk11_RSA_private_encrypt(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding)
+ int i, num = 0, r = -1;
+ unsigned char *buf = NULL;
+ num = BN_num_bytes(rsa->n);
+ if ((buf = (unsigned char *)OPENSSL_malloc(num)) == NULL)
+ RSAerr(PK11_F_RSA_PRIV_ENC, PK11_R_MALLOC_FAILURE);
+ case RSA_PKCS1_PADDING:
+ i = RSA_padding_add_PKCS1_type_1(buf, num, from, flen);
+ i = RSA_padding_add_none(buf, num, from, flen);
+ case RSA_SSLV23_PADDING:
+ RSAerr(PK11_F_RSA_PRIV_ENC, PK11_R_UNKNOWN_PADDING_TYPE);
+ /* PK11 functions are called here */
+ r = pk11_RSA_private_encrypt_low(num, buf, to, rsa);
+ OPENSSL_cleanse(buf, num);
+/* Similar to OpenSSL code. Input errors are also checked here */
+static int pk11_RSA_private_decrypt(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding)
+ int j, num = 0, r = -1;
+ unsigned char *buf = NULL;
+ num = BN_num_bytes(rsa->n);
+ if ((buf = (unsigned char *)OPENSSL_malloc(num)) == NULL)
+ RSAerr(PK11_F_RSA_PRIV_DEC, PK11_R_MALLOC_FAILURE);
+ * This check was for equality but PGP does evil things
+ * and chops off the top '0' bytes
+ RSAerr(PK11_F_RSA_PRIV_DEC,
+ PK11_R_DATA_GREATER_THAN_MOD_LEN);
+ /* make data into a big number */
+ if (BN_bin2bn(from, (int)flen, &f) == NULL)
+ if (BN_ucmp(&f, rsa->n) >= 0)
+ RSAerr(PK11_F_RSA_PRIV_DEC,
+ PK11_R_DATA_TOO_LARGE_FOR_MODULUS);
+ /* PK11 functions are called here */
+ r = pk11_RSA_private_decrypt_low(flen, from, buf, rsa);
+ * PK11 CKM_RSA_X_509 mechanism pads 0's at the beginning.
+ * Needs to skip these 0's paddings here.
+ for (j = 0; j < r; j++)
+ j = r - j; /* j is only used with no-padding mode */
+ case RSA_PKCS1_PADDING:
+ r = RSA_padding_check_PKCS1_type_2(to, num, p, j, num);
+ case RSA_PKCS1_OAEP_PADDING:
+ r = RSA_padding_check_PKCS1_OAEP(to, num, p, j, num, NULL, 0);
+ case RSA_SSLV23_PADDING:
+ r = RSA_padding_check_SSLv23(to, num, p, j, num);
+ r = RSA_padding_check_none(to, num, p, j, num);
+ RSAerr(PK11_F_RSA_PRIV_DEC, PK11_R_UNKNOWN_PADDING_TYPE);
+ RSAerr(PK11_F_RSA_PRIV_DEC, PK11_R_PADDING_CHECK_FAILED);
+ OPENSSL_cleanse(buf, num);
+/* Similar to OpenSSL code. Input errors are also checked here */
+static int pk11_RSA_public_decrypt(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding)
+ int i, num = 0, r = -1;
+ unsigned char *buf = NULL;
+ num = BN_num_bytes(rsa->n);
+ buf = (unsigned char *)OPENSSL_malloc(num);
+ RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_MALLOC_FAILURE);
+ * This check was for equality but PGP does evil things
+ * and chops off the top '0' bytes
+ RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_DATA_GREATER_THAN_MOD_LEN);
+ if (BN_bin2bn(from, flen, &f) == NULL)
+ if (BN_ucmp(&f, rsa->n) >= 0)
+ RSAerr(PK11_F_RSA_PUB_DEC,
+ PK11_R_DATA_TOO_LARGE_FOR_MODULUS);
+ /* PK11 functions are called here */
+ r = pk11_RSA_public_decrypt_low(flen, from, buf, rsa);
+ * PK11 CKM_RSA_X_509 mechanism pads 0's at the beginning.
+ * Needs to skip these 0's here
+ for (i = 0; i < r; i++)
+ i = r - i; /* i is only used with no-padding mode */
+ case RSA_PKCS1_PADDING:
+ r = RSA_padding_check_PKCS1_type_1(to, num, p, i, num);
+ r = RSA_padding_check_none(to, num, p, i, num);
+ RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_UNKNOWN_PADDING_TYPE);
+ RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_PADDING_CHECK_FAILED);
+ OPENSSL_cleanse(buf, num);
+ * This function implements RSA public encryption using C_EncryptInit and
+ * C_Encrypt pk11 interfaces. Note that the CKM_RSA_X_509 is used here.
+ * The calling function allocated sufficient memory in "to" to store results.
+static int pk11_RSA_public_encrypt_low(int flen,
+ const unsigned char *from, unsigned char *to, RSA *rsa)
+ CK_ULONG bytes_encrypted = flen;
+ CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
+ CK_MECHANISM *p_mech = &mech_rsa;
+ CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ (void) check_new_rsa_key_pub(sp, rsa);
+ h_pub_key = sp->opdata_rsa_pub_key;
+ if (h_pub_key == CK_INVALID_HANDLE)
+ h_pub_key = sp->opdata_rsa_pub_key =
+ pk11_get_public_rsa_key(rsa, &sp->opdata_rsa_pub,
+ &sp->opdata_rsa_n_num, &sp->opdata_rsa_e_num,
+ if (h_pub_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_EncryptInit(sp->session, p_mech,
+ PK11err_add_data(PK11_F_RSA_PUB_ENC_LOW,
+ PK11_R_ENCRYPTINIT, rv);
+ pk11_return_session(sp, OP_RSA);
+ rv = pFuncList->C_Encrypt(sp->session,
+ (unsigned char *)from, flen, to, &bytes_encrypted);
+ PK11err_add_data(PK11_F_RSA_PUB_ENC_LOW,
+ pk11_return_session(sp, OP_RSA);
+ retval = bytes_encrypted;
+ pk11_return_session(sp, OP_RSA);
+ * This function implements RSA private encryption using C_SignInit and
+ * C_Sign pk11 APIs. Note that CKM_RSA_X_509 is used here.
+ * The calling function allocated sufficient memory in "to" to store results.
+static int pk11_RSA_private_encrypt_low(int flen,
+ const unsigned char *from, unsigned char *to, RSA *rsa)
+ CK_ULONG ul_sig_len = flen;
+ CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
+ CK_MECHANISM *p_mech = &mech_rsa;
+ CK_OBJECT_HANDLE h_priv_key = CK_INVALID_HANDLE;
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ (void) check_new_rsa_key_priv(sp, rsa);
+ h_priv_key = sp->opdata_rsa_priv_key;
+ if (h_priv_key == CK_INVALID_HANDLE)
+ h_priv_key = sp->opdata_rsa_priv_key =
+ pk11_get_private_rsa_key(rsa, &sp->opdata_rsa_priv,
+ &sp->opdata_rsa_d_num, &sp->opdata_rsa_pn_num,
+ &sp->opdata_rsa_pe_num, sp->session);
+ if (h_priv_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_SignInit(sp->session, p_mech,
+ PK11err_add_data(PK11_F_RSA_PRIV_ENC_LOW,
+ pk11_return_session(sp, OP_RSA);
+ rv = pFuncList->C_Sign(sp->session,
+ (unsigned char *)from, flen, to, &ul_sig_len);
+ PK11err_add_data(PK11_F_RSA_PRIV_ENC_LOW, PK11_R_SIGN,
+ pk11_return_session(sp, OP_RSA);
+ pk11_return_session(sp, OP_RSA);
+ * This function implements RSA private decryption using C_DecryptInit and
+ * C_Decrypt pk11 APIs. Note that CKM_RSA_X_509 mechanism is used here.
+ * The calling function allocated sufficient memory in "to" to store results.
+static int pk11_RSA_private_decrypt_low(int flen,
+ const unsigned char *from, unsigned char *to, RSA *rsa)
+ CK_ULONG bytes_decrypted = flen;
+ CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
+ CK_MECHANISM *p_mech = &mech_rsa;
+ CK_OBJECT_HANDLE h_priv_key;
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ (void) check_new_rsa_key_priv(sp, rsa);
+ h_priv_key = sp->opdata_rsa_priv_key;
+ if (h_priv_key == CK_INVALID_HANDLE)
+ h_priv_key = sp->opdata_rsa_priv_key =
+ pk11_get_private_rsa_key(rsa, &sp->opdata_rsa_priv,
+ &sp->opdata_rsa_d_num, &sp->opdata_rsa_pn_num,
+ &sp->opdata_rsa_pe_num, sp->session);
+ if (h_priv_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_DecryptInit(sp->session, p_mech,
+ PK11err_add_data(PK11_F_RSA_PRIV_DEC_LOW,
+ PK11_R_DECRYPTINIT, rv);
+ pk11_return_session(sp, OP_RSA);
+ rv = pFuncList->C_Decrypt(sp->session,
+ (unsigned char *)from, flen, to, &bytes_decrypted);
+ PK11err_add_data(PK11_F_RSA_PRIV_DEC_LOW,
+ pk11_return_session(sp, OP_RSA);
+ retval = bytes_decrypted;
+ pk11_return_session(sp, OP_RSA);
+ * This function implements RSA public decryption using C_VerifyRecoverInit
+ * and C_VerifyRecover pk11 APIs. Note that CKM_RSA_X_509 is used here.
+ * The calling function allocated sufficient memory in "to" to store results.
+static int pk11_RSA_public_decrypt_low(int flen,
+ const unsigned char *from, unsigned char *to, RSA *rsa)
+ CK_ULONG bytes_decrypted = flen;
+ CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
+ CK_MECHANISM *p_mech = &mech_rsa;
+ CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ (void) check_new_rsa_key_pub(sp, rsa);
+ h_pub_key = sp->opdata_rsa_pub_key;
+ if (h_pub_key == CK_INVALID_HANDLE)
+ h_pub_key = sp->opdata_rsa_pub_key =
+ pk11_get_public_rsa_key(rsa, &sp->opdata_rsa_pub,
+ &sp->opdata_rsa_n_num, &sp->opdata_rsa_e_num,
+ if (h_pub_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_VerifyRecoverInit(sp->session,
+ PK11err_add_data(PK11_F_RSA_PUB_DEC_LOW,
+ PK11_R_VERIFYRECOVERINIT, rv);
+ pk11_return_session(sp, OP_RSA);
+ rv = pFuncList->C_VerifyRecover(sp->session,
+ (unsigned char *)from, flen, to, &bytes_decrypted);
+ PK11err_add_data(PK11_F_RSA_PUB_DEC_LOW,
+ PK11_R_VERIFYRECOVER, rv);
+ pk11_return_session(sp, OP_RSA);
+ retval = bytes_decrypted;
+ pk11_return_session(sp, OP_RSA);
+static int pk11_RSA_init(RSA *rsa)
+ * This flag in the RSA_METHOD enables the new rsa_sign,
+ * rsa_verify functions. See
rsa.h for details.
+ rsa->flags |= RSA_FLAG_SIGN_VER;
+static int pk11_RSA_finish(RSA *rsa)
+ * Since we are overloading OpenSSL's native RSA_eay_finish() we need
+ * to do the same as in the original function,
i.e. to free bignum
+ if (rsa->_method_mod_n != NULL)
+ BN_MONT_CTX_free(rsa->_method_mod_n);
+ if (rsa->_method_mod_p != NULL)
+ BN_MONT_CTX_free(rsa->_method_mod_p);
+ if (rsa->_method_mod_q != NULL)
+ BN_MONT_CTX_free(rsa->_method_mod_q);
+ * Standard engine interface function. Majority codes here are from
+ *
rsa/rsa_sign.c. We replaced the decrypt function call by C_Sign of PKCS#11.
+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
+ unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
+ unsigned char *p, *s = NULL;
+ ASN1_OCTET_STRING digest;
+ CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
+ CK_MECHANISM *p_mech = &mech_rsa;
+ CK_OBJECT_HANDLE h_priv_key;
+ PK11_SESSION *sp = NULL;
+ unsigned long ulsiglen;
+ /* Encode the digest */
+ /* Special case: SSL signature, just check the length */
+ if (type == NID_md5_sha1)
+ if (m_len != SSL_SIG_LENGTH)
+ PK11err(PK11_F_RSA_SIGN,
+ PK11_R_INVALID_MESSAGE_LENGTH);
+ s = (unsigned char *)m;
+ PK11err(PK11_F_RSA_SIGN,
+ PK11_R_UNKNOWN_ALGORITHM_TYPE);
+ PK11err(PK11_F_RSA_SIGN,
+ PK11_R_UNKNOWN_ASN1_OBJECT_ID);
+ i = i2d_X509_SIG(&sig, NULL);
+ if ((i - RSA_PKCS1_PADDING) > j)
+ PK11err(PK11_F_RSA_SIGN, PK11_R_DIGEST_TOO_BIG);
+ if (type != NID_md5_sha1)
+ s = (unsigned char *)OPENSSL_malloc((unsigned int)(j + 1));
+ PK11err(PK11_F_RSA_SIGN, PK11_R_MALLOC_FAILURE);
+ (void) i2d_X509_SIG(&sig, &p);
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ (void) check_new_rsa_key_priv(sp, rsa);
+ h_priv_key = sp->opdata_rsa_priv_key;
+ if (h_priv_key == CK_INVALID_HANDLE)
+ h_priv_key = sp->opdata_rsa_priv_key =
+ pk11_get_private_rsa_key((RSA *)rsa,
+ &sp->opdata_rsa_priv, &sp->opdata_rsa_d_num,
+ &sp->opdata_rsa_pn_num, &sp->opdata_rsa_pe_num,
+ if (h_priv_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
+ PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGNINIT, rv);
+ rv = pFuncList->C_Sign(sp->session, s, i, sigret,
+ (CK_ULONG_PTR) &ulsiglen);
+ PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGN, rv);
+ if ((type != NID_md5_sha1) && (s != NULL))
+ (void) memset(s, 0, (unsigned int)(j + 1));
+ pk11_return_session(sp, OP_RSA);
+#if OPENSSL_VERSION_NUMBER < 0x10000000L
+static int pk11_RSA_verify(int type, const unsigned char *m,
+ unsigned int m_len, unsigned char *sigbuf, unsigned int siglen,
+static int pk11_RSA_verify(int type, const unsigned char *m,
+ unsigned int m_len, const unsigned char *sigbuf, unsigned int siglen,
+ unsigned char *p, *s = NULL;
+ ASN1_OCTET_STRING digest;
+ CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
+ CK_MECHANISM *p_mech = &mech_rsa;
+ CK_OBJECT_HANDLE h_pub_key;
+ PK11_SESSION *sp = NULL;
+ /* Encode the digest */
+ /* Special case: SSL signature, just check the length */
+ if (type == NID_md5_sha1)
+ if (m_len != SSL_SIG_LENGTH)
+ PK11err(PK11_F_RSA_VERIFY,
+ PK11_R_INVALID_MESSAGE_LENGTH);
+ s = (unsigned char *)m;
+ PK11err(PK11_F_RSA_VERIFY,
+ PK11_R_UNKNOWN_ALGORITHM_TYPE);
+ PK11err(PK11_F_RSA_VERIFY,
+ PK11_R_UNKNOWN_ASN1_OBJECT_ID);
+ i = i2d_X509_SIG(&sig, NULL);
+ if ((i - RSA_PKCS1_PADDING) > j)
+ PK11err(PK11_F_RSA_VERIFY, PK11_R_DIGEST_TOO_BIG);
+ if (type != NID_md5_sha1)
+ s = (unsigned char *)OPENSSL_malloc((unsigned int)(j + 1));
+ PK11err(PK11_F_RSA_VERIFY, PK11_R_MALLOC_FAILURE);
+ (void) i2d_X509_SIG(&sig, &p);
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ (void) check_new_rsa_key_pub(sp, rsa);
+ h_pub_key = sp->opdata_rsa_pub_key;
+ if (h_pub_key == CK_INVALID_HANDLE)
+ h_pub_key = sp->opdata_rsa_pub_key =
+ pk11_get_public_rsa_key((RSA *)rsa, &sp->opdata_rsa_pub,
+ &sp->opdata_rsa_n_num, &sp->opdata_rsa_e_num,
+ if (h_pub_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_VerifyInit(sp->session, p_mech,
+ PK11err_add_data(PK11_F_RSA_VERIFY, PK11_R_VERIFYINIT,
+ rv = pFuncList->C_Verify(sp->session, s, i,
+ (CK_BYTE_PTR)sigbuf, (CK_ULONG)siglen);
+ PK11err_add_data(PK11_F_RSA_VERIFY, PK11_R_VERIFY, rv);
+ if ((type != NID_md5_sha1) && (s != NULL))
+ (void) memset(s, 0, (unsigned int)(j + 1));
+ pk11_return_session(sp, OP_RSA);
+static int hndidx_rsa = -1;
+ * Load RSA private key from a file or get its PKCS#11 handle if stored in the
+EVP_PKEY *pk11_load_privkey(ENGINE *e, const char *privkey_file,
+ UI_METHOD *ui_method, void *callback_data)
+ CK_OBJECT_HANDLE h_priv_key = CK_INVALID_HANDLE;
+ /* Anything else below is needed for the key by reference extension. */
+ CK_BBOOL is_token = TRUE;
+ CK_BBOOL rollback = FALSE;
+ CK_BYTE attr_data[2][MAXATTR];
+ CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY;
+ CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE; /* key in keystore */
+ /* we look for private keys only */
+ CK_ATTRIBUTE search_templ[] =
+ {CKA_TOKEN, &is_token, sizeof(is_token)},
+ {CKA_CLASS, &key_class, sizeof(key_class)},
+ * These public attributes are needed to initialize the OpenSSL RSA
+ * structure with something we can use to look up the key. Note that we
+ * never ask for private components.
+ CK_ATTRIBUTE get_templ[] =
+ {CKA_MODULUS, (void *)attr_data[0], MAXATTR}, /* n */
+ {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], MAXATTR}, /* e */
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
+ if (strstr(privkey_file, "pkcs11:") == privkey_file)
+ search_templ[2].pValue = strstr(privkey_file, ":") + 1;
+ search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
+ if (pk11_token_login(sp->session, &pk11_login_done,
+ /* see find_lock array definition
+ for more info on object locking */
+ * Now let's try to find the key in the token. It is a failure
+ if (find_one_object(OP_RSA, sp->session, search_templ, 3,
+ UNLOCK_OBJSTORE(OP_RSA);
+ hndidx_rsa = RSA_get_ex_new_index(0,
+ "pkcs11 RSA HSM key handle",
+ * We might have a cache hit which we could confirm
+ * according to the 'n'/'e' params, RSA public pointer
+ * as NULL, and non-NULL RSA private pointer. However,
+ * it is easier just to recreate everything. We expect
+ * the keys to be loaded once and used many times. We
+ * do not check the return value because even in case
+ * of failure the sp structure will have both key
+ * pointer and object handle cleaned and
+ * pk11_destroy_object() reports the failure to the
+ * OpenSSL error message buffer.
+ (void) pk11_destroy_rsa_object_priv(sp, FALSE);
+ sp->opdata_rsa_priv_key = ks_key;
+ /* This object shall not be deleted on a cache miss. */
+ sp->priv_persistent = CK_TRUE;
+ * Cache the RSA private structure pointer. We do not
+ * use it now for key-by-ref keys but let's do it for
+ if ((rsa = sp->opdata_rsa_priv = RSA_new_method(e)) == NULL)
+ UNLOCK_OBJSTORE(OP_RSA);
+ * Now we have to initialize an OpenSSL RSA structure,
+ * everything else is 0 or NULL.
+ rsa->flags = RSA_FLAG_SIGN_VER | RSA_FLAG_EXT_PKEY;
+ RSA_set_ex_data(rsa, hndidx_rsa, (void *) ks_key);
+ if ((rv = pFuncList->C_GetAttributeValue(sp->session, ks_key,
+ get_templ, 2)) != CKR_OK)
+ UNLOCK_OBJSTORE(OP_RSA);
+ PK11err_add_data(PK11_F_LOAD_PRIVKEY,
+ PK11_R_GETATTRIBUTVALUE, rv);
+ * We do not use pk11_get_private_rsa_key() here so we
+ * must take care of handle management ourselves.
+ KEY_HANDLE_REFHOLD(ks_key, OP_RSA, TRUE, rollback, err);
+ * Those are the sensitive components we do not want to export
+ * from the token at all: rsa->(d|p|q|dmp1|dmq1|iqmp).
+ attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
+ attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
+ * Must have 'n'/'e' components in the session structure as
+ * well. They serve as a public look-up key for the private key
+ attr_to_BN(&get_templ[0], attr_data[0],
+ &sp->opdata_rsa_pn_num);
+ attr_to_BN(&get_templ[1], attr_data[1],
+ &sp->opdata_rsa_pe_num);
+ UNLOCK_OBJSTORE(OP_RSA);
+ if ((pkey = EVP_PKEY_new()) == NULL)
+ if (EVP_PKEY_assign_RSA(pkey, rsa) == 0)
+ else if ((privkey = fopen(privkey_file, read_mode_flags)) != NULL)
+ pkey = PEM_read_PrivateKey(privkey, NULL, NULL, NULL);
+ (void) fclose(privkey);
+ rsa = EVP_PKEY_get1_RSA(pkey);
+ * This will always destroy the RSA
+ * object since we have a new RSA
+ (void) check_new_rsa_key_priv(sp, rsa);
+ sp->priv_persistent = CK_FALSE;
+ h_priv_key = sp->opdata_rsa_priv_key =
+ pk11_get_private_rsa_key(rsa,
+ &sp->opdata_rsa_pn_num,
+ &sp->opdata_rsa_pe_num, sp->session);
+ if (h_priv_key == CK_INVALID_HANDLE)
+ pk11_return_session(sp, OP_RSA);
+ pk11_return_session(sp, OP_RSA);
+ * Load RSA public key from a file or get its PKCS#11 handle if stored in the
+EVP_PKEY *pk11_load_pubkey(ENGINE *e, const char *pubkey_file,
+ UI_METHOD *ui_method, void *callback_data)
+ CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
+ /* Anything else below is needed for the key by reference extension. */
+ CK_BBOOL is_token = TRUE;
+ CK_BYTE attr_data[2][MAXATTR];
+ CK_OBJECT_CLASS key_class = CKO_PUBLIC_KEY;
+ CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE; /* key in keystore */
+ /* we look for public keys only */
+ CK_ATTRIBUTE search_templ[] =
+ {CKA_TOKEN, &is_token, sizeof(is_token)},
+ {CKA_CLASS, &key_class, sizeof(key_class)},
+ * These public attributes are needed to initialize OpenSSL RSA
+ * structure with something we can use to look up the key.
+ CK_ATTRIBUTE get_templ[] =
+ {CKA_MODULUS, (void *)attr_data[0], MAXATTR}, /* n */
+ {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], MAXATTR}, /* e */
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
+ if (strstr(pubkey_file, "pkcs11:") == pubkey_file)
+ search_templ[2].pValue = strstr(pubkey_file, ":") + 1;
+ search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
+ if (pk11_token_login(sp->session, &pk11_login_done,
+ /* see find_lock array definition
+ for more info on object locking */
+ * Now let's try to find the key in the token. It is a failure
+ if (find_one_object(OP_RSA, sp->session, search_templ, 3,
+ UNLOCK_OBJSTORE(OP_RSA);
+ * We load a new public key so we will create a new RSA
+ * structure. No cache hit is possible.
+ (void) pk11_destroy_rsa_object_pub(sp, FALSE);
+ sp->opdata_rsa_pub_key = ks_key;
+ /* This object shall not be deleted on a cache miss. */
+ sp->pub_persistent = CK_TRUE;
+ * Cache the RSA public structure pointer.
+ if ((rsa = sp->opdata_rsa_pub = RSA_new_method(e)) == NULL)
+ UNLOCK_OBJSTORE(OP_RSA);
+ * Now we have to initialize an OpenSSL RSA structure,
+ * everything else is 0 or NULL.
+ rsa->flags = RSA_FLAG_SIGN_VER;
+ if ((rv = pFuncList->C_GetAttributeValue(sp->session, ks_key,
+ get_templ, 2)) != CKR_OK)
+ UNLOCK_OBJSTORE(OP_RSA);
+ PK11err_add_data(PK11_F_LOAD_PUBKEY,
+ PK11_R_GETATTRIBUTVALUE, rv);
+ attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
+ attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
+ UNLOCK_OBJSTORE(OP_RSA);
+ if ((pkey = EVP_PKEY_new()) == NULL)
+ if (EVP_PKEY_assign_RSA(pkey, rsa) == 0)
+ * Create a session object from it so that when calling
+ * pk11_get_public_rsa_key() the next time, we can find it. The
+ * reason why we do that is that we cannot tell from the RSA
+ * structure (OpenSSL RSA structure does not have any room for
+ * additional data used by the engine, for example) if it bears
+ * a public key stored in the keystore or not so it's better if
+ * we always have a session key. Note that this is different
+ * from what we do for the private keystore objects but in that
+ * case, we can tell from the RSA structure that the keystore
+ * object is in play - the 'd' component is NULL in that case.
+ h_pub_key = sp->opdata_rsa_pub_key =
+ pk11_get_public_rsa_key(rsa,
+ &sp->opdata_rsa_pub, &sp->opdata_rsa_n_num,
+ &sp->opdata_rsa_e_num, sp->session);
+ if (h_pub_key == CK_INVALID_HANDLE)
+ else if ((pubkey = fopen(pubkey_file, read_mode_flags)) != NULL)
+ pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
+ rsa = EVP_PKEY_get1_RSA(pkey);
+ * This will always destroy the RSA
+ * object since we have a new RSA
+ (void) check_new_rsa_key_pub(sp, rsa);
+ sp->pub_persistent = CK_FALSE;
+ h_pub_key = sp->opdata_rsa_pub_key =
+ pk11_get_public_rsa_key(rsa,
+ &sp->opdata_rsa_pub, &sp->opdata_rsa_n_num,
+ &sp->opdata_rsa_e_num, sp->session);
+ if (h_pub_key == CK_INVALID_HANDLE)
+ pk11_return_session(sp, OP_RSA);
+ pk11_return_session(sp, OP_RSA);
+ * Create a public key object in a session from a given rsa structure.
+ * The *rsa_n_num and *rsa_e_num pointers are non-NULL for RSA public keys.
+static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA *rsa,
+ RSA **key_ptr, BIGNUM **rsa_n_num, BIGNUM **rsa_e_num,
+ CK_SESSION_HANDLE session)
+ CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+ CK_OBJECT_CLASS o_key = CKO_PUBLIC_KEY;
+ CK_KEY_TYPE k_type = CKK_RSA;
+ CK_ULONG ul_key_attr_count = 8;
+ CK_BBOOL rollback = FALSE;
+ CK_ATTRIBUTE a_key_template[] =
+ {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
+ {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
+ {CKA_TOKEN, &myfalse, sizeof (myfalse)},
+ {CKA_ENCRYPT, &mytrue, sizeof (mytrue)},
+ {CKA_VERIFY, &mytrue, sizeof (mytrue)},
+ {CKA_VERIFY_RECOVER, &mytrue, sizeof (mytrue)},
+ {CKA_MODULUS, (void *)NULL, 0},
+ {CKA_PUBLIC_EXPONENT, (void *)NULL, 0}
+ a_key_template[0].pValue = &o_key;
+ a_key_template[1].pValue = &k_type;
+ a_key_template[6].ulValueLen = BN_num_bytes(rsa->n);
+ a_key_template[6].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+ (size_t)a_key_template[6].ulValueLen);
+ if (a_key_template[6].pValue == NULL)
+ PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ BN_bn2bin(rsa->n, a_key_template[6].pValue);
+ a_key_template[7].ulValueLen = BN_num_bytes(rsa->e);
+ a_key_template[7].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+ (size_t)a_key_template[7].ulValueLen);
+ if (a_key_template[7].pValue == NULL)
+ PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ BN_bn2bin(rsa->e, a_key_template[7].pValue);
+ /* see find_lock array definition for more info on object locking */
+ rv = pFuncList->C_FindObjectsInit(session, a_key_template,
+ PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
+ PK11_R_FINDOBJECTSINIT, rv);
+ rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+ (void) pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
+ PK11_R_FINDOBJECTS, rv);
+ rv = pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
+ PK11_R_FINDOBJECTSFINAL, rv);
+ rv = pFuncList->C_CreateObject(session,
+ a_key_template, ul_key_attr_count, &h_key);
+ PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
+ PK11_R_CREATEOBJECT, rv);
+ if ((*rsa_n_num = BN_dup(rsa->n)) == NULL)
+ PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ if ((*rsa_e_num = BN_dup(rsa->e)) == NULL)
+ PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ /* LINTED: E_CONSTANT_CONDITION */
+ KEY_HANDLE_REFHOLD(h_key, OP_RSA, FALSE, rollback, err);
+ * We do not care about the return value from C_DestroyObject()
+ * since we are doing rollback.
+ (void) pFuncList->C_DestroyObject(session, h_key);
+ h_key = CK_INVALID_HANDLE;
+ UNLOCK_OBJSTORE(OP_RSA);
+ for (i = 6; i <= 7; i++)
+ if (a_key_template[i].pValue != NULL)
+ OPENSSL_free(a_key_template[i].pValue);
+ a_key_template[i].pValue = NULL;
+ * Create a private key object in the session from a given rsa structure.
+ * The *rsa_d_num pointer is non-NULL for RSA private keys.
+pk11_get_private_rsa_key(RSA *rsa, RSA **key_ptr, BIGNUM **rsa_d_num,
+ BIGNUM **rsa_n_num, BIGNUM **rsa_e_num, CK_SESSION_HANDLE session)
+ CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+ CK_OBJECT_CLASS o_key = CKO_PRIVATE_KEY;
+ CK_KEY_TYPE k_type = CKK_RSA;
+ CK_ULONG ul_key_attr_count = 14;
+ CK_BBOOL rollback = FALSE;
+ /* Both CKA_TOKEN and CKA_SENSITIVE have to be FALSE for session keys */
+ CK_ATTRIBUTE a_key_template[] =
+ {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
+ {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
+ {CKA_TOKEN, &myfalse, sizeof (myfalse)},
+ {CKA_SENSITIVE, &myfalse, sizeof (myfalse)},
+ {CKA_DECRYPT, &mytrue, sizeof (mytrue)},
+ {CKA_SIGN, &mytrue, sizeof (mytrue)},
+ {CKA_MODULUS, (void *)NULL, 0},
+ {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
+ {CKA_PRIVATE_EXPONENT, (void *)NULL, 0},
+ {CKA_PRIME_1, (void *)NULL, 0},
+ {CKA_PRIME_2, (void *)NULL, 0},
+ {CKA_EXPONENT_1, (void *)NULL, 0},
+ {CKA_EXPONENT_2, (void *)NULL, 0},
+ {CKA_COEFFICIENT, (void *)NULL, 0},
+ if ((rsa->flags & RSA_FLAG_EXT_PKEY) != 0) {
+ h_key = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, hndidx_rsa);
+ a_key_template[0].pValue = &o_key;
+ a_key_template[1].pValue = &k_type;
+ /* Put the private key components into the template */
+ if (init_template_value(rsa->n, &a_key_template[6].pValue,
+ &a_key_template[6].ulValueLen) == 0 ||
+ init_template_value(rsa->e, &a_key_template[7].pValue,
+ &a_key_template[7].ulValueLen) == 0 ||
+ init_template_value(rsa->d, &a_key_template[8].pValue,
+ &a_key_template[8].ulValueLen) == 0 ||
+ init_template_value(rsa->p, &a_key_template[9].pValue,
+ &a_key_template[9].ulValueLen) == 0 ||
+ init_template_value(rsa->q, &a_key_template[10].pValue,
+ &a_key_template[10].ulValueLen) == 0 ||
+ init_template_value(rsa->dmp1, &a_key_template[11].pValue,
+ &a_key_template[11].ulValueLen) == 0 ||
+ init_template_value(rsa->dmq1, &a_key_template[12].pValue,
+ &a_key_template[12].ulValueLen) == 0 ||
+ init_template_value(rsa->iqmp, &a_key_template[13].pValue,
+ &a_key_template[13].ulValueLen) == 0)
+ PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ /* see find_lock array definition for more info on object locking */
+ * We are getting the private key but the private 'd'
+ * component is NULL. That means this is key by reference RSA
+ * key. In that case, we can use only public components for
+ * searching for the private key handle.
+ * We will perform the search in the token, not in the existing
+ a_key_template[2].pValue = &mytrue;
+ rv = pFuncList->C_FindObjectsInit(session, a_key_template,
+ PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_FINDOBJECTSINIT, rv);
+ rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+ (void) pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_FINDOBJECTS, rv);
+ rv = pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_FINDOBJECTSFINAL, rv);
+ * We have an RSA structure with 'n'/'e' components
+ * only so we tried to find the private key in the
+ * keystore. If it was really a token key we have a
+ * problem. Note that for other key types we just
+ * create a new session key using the private
+ * components from the RSA structure.
+ PK11err(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_PRIV_KEY_NOT_FOUND);
+ rv = pFuncList->C_CreateObject(session,
+ a_key_template, ul_key_attr_count, &h_key);
+ PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_CREATEOBJECT, rv);
+ * When RSA keys by reference code is used, we never
+ * extract private components from the keystore. In
+ * that case 'd' was set to NULL and we expect the
+ * application to properly cope with that. It is
+ * documented in openssl(5). In general, if keys by
+ * reference are used we expect it to be used
+ * exclusively using the high level API and then there
+ * is no problem. If the application expects the
+ * private components to be read from the keystore
+ * then that is not a supported way of usage.
+ if (rsa->d != NULL && (*rsa_d_num = BN_dup(rsa->d)) == NULL)
+ PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ * For the key by reference code, we need public components as well
+ * since 'd' component is always NULL. For that reason, we always cache
+ * 'n'/'e' components as well.
+ *rsa_n_num = BN_dup(rsa->n);
+ *rsa_e_num = BN_dup(rsa->e);
+ /* LINTED: E_CONSTANT_CONDITION */
+ KEY_HANDLE_REFHOLD(h_key, OP_RSA, FALSE, rollback, err);
+ * We do not care about the return value from C_DestroyObject()
+ * since we are doing rollback.
+ (rsa->flags & RSA_FLAG_EXT_PKEY) == 0)
+ (void) pFuncList->C_DestroyObject(session, h_key);
+ h_key = CK_INVALID_HANDLE;
+ UNLOCK_OBJSTORE(OP_RSA);
+ * 6 to 13 entries in the key template are key components.
+ * They need to be freed upon exit or error.
+ for (i = 6; i <= 13; i++)
+ if (a_key_template[i].pValue != NULL)
+ (void) memset(a_key_template[i].pValue, 0,
+ a_key_template[i].ulValueLen);
+ OPENSSL_free(a_key_template[i].pValue);
+ a_key_template[i].pValue = NULL;
+ * Check for cache miss and clean the object pointer and handle
+ * in such case. Return 1 for cache hit, 0 for cache miss.
+static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa)
+ * Provide protection against RSA structure reuse by making the
+ * check for cache hit stronger. Only public components of RSA
+ * key matter here so it is sufficient to compare them with values
+ * cached in PK11_SESSION structure.
+ * We must check the handle as well since with key by reference, public
+ * components 'n'/'e' are cached in private keys as well. That means we
+ * could have a cache hit in a private key when looking for a public
+ * key. That would not work, you cannot have one PKCS#11 object for
+ * both data signing and verifying.
+ if ((sp->opdata_rsa_pub != rsa) ||
+ (BN_cmp(sp->opdata_rsa_n_num, rsa->n) != 0) ||
+ (BN_cmp(sp->opdata_rsa_e_num, rsa->e) != 0) ||
+ (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE))
+ * We do not check the return value because even in case of
+ * failure the sp structure will have both key pointer
+ * and object handle cleaned and pk11_destroy_object()
+ * reports the failure to the OpenSSL error message buffer.
+ (void) pk11_destroy_rsa_object_pub(sp, TRUE);
+ * Check for cache miss and clean the object pointer and handle
+ * in such case. Return 1 for cache hit, 0 for cache miss.
+static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa)
+ * Provide protection against RSA structure reuse by making
+ * the check for cache hit stronger. Comparing public exponent
+ * of RSA key with value cached in PK11_SESSION structure
+ * should be sufficient. Note that we want to compare the
+ * public component since with the keys by reference
+ * mechanism, private components are not in the RSA
+ * structure. Also, see check_new_rsa_key_pub() about why we
+ * compare the handle as well.
+ if ((sp->opdata_rsa_priv != rsa) ||
+ (BN_cmp(sp->opdata_rsa_pn_num, rsa->n) != 0) ||
+ (BN_cmp(sp->opdata_rsa_pe_num, rsa->e) != 0) ||
+ (sp->opdata_rsa_pn_num == NULL) ||
+ (sp->opdata_rsa_pe_num == NULL) ||
+ (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE))
+ * We do not check the return value because even in case of
+ * failure the sp structure will have both key pointer
+ * and object handle cleaned and pk11_destroy_object()
+ * reports the failure to the OpenSSL error message buffer.
+ (void) pk11_destroy_rsa_object_priv(sp, TRUE);
+/* The DSA function implementation */
+static int pk11_DSA_init(DSA *dsa)
+static int pk11_DSA_finish(DSA *dsa)
+pk11_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
+ BIGNUM *r = NULL, *s = NULL;
+ DSA_SIG *dsa_sig = NULL;
+ CK_MECHANISM Mechanism_dsa = {CKM_DSA, NULL, 0};
+ CK_MECHANISM *p_mech = &Mechanism_dsa;
+ CK_OBJECT_HANDLE h_priv_key;
+ * The signature is the concatenation of r and s,
+ * each is 20 bytes long
+ unsigned char sigret[DSA_SIGNATURE_LEN];
+ unsigned long siglen = DSA_SIGNATURE_LEN;
+ unsigned int siglen2 = DSA_SIGNATURE_LEN / 2;
+ PK11_SESSION *sp = NULL;
+ if ((dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))
+ PK11err(PK11_F_DSA_SIGN, PK11_R_MISSING_KEY_COMPONENT);
+ i = BN_num_bytes(dsa->q); /* should be 20 */
+ PK11err(PK11_F_DSA_SIGN, PK11_R_INVALID_SIGNATURE_LENGTH);
+ if ((sp = pk11_get_session(OP_DSA)) == NULL)
+ (void) check_new_dsa_key_priv(sp, dsa);
+ h_priv_key = sp->opdata_dsa_priv_key;
+ if (h_priv_key == CK_INVALID_HANDLE)
+ h_priv_key = sp->opdata_dsa_priv_key =
+ pk11_get_private_dsa_key((DSA *)dsa,
+ &sp->opdata_dsa_priv_num, sp->session);
+ if (h_priv_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
+ PK11err_add_data(PK11_F_DSA_SIGN, PK11_R_SIGNINIT, rv);
+ (void) memset(sigret, 0, siglen);
+ rv = pFuncList->C_Sign(sp->session,
+ (unsigned char*) dgst, dlen, sigret,
+ (CK_ULONG_PTR) &siglen);
+ PK11err_add_data(PK11_F_DSA_SIGN, PK11_R_SIGN, rv);
+ if ((s = BN_new()) == NULL)
+ PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
+ if ((r = BN_new()) == NULL)
+ PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
+ if ((dsa_sig = DSA_SIG_new()) == NULL)
+ PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
+ if (BN_bin2bn(sigret, siglen2, r) == NULL ||
+ BN_bin2bn(&sigret[siglen2], siglen2, s) == NULL)
+ PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
+ pk11_return_session(sp, OP_DSA);
+pk11_dsa_do_verify(const unsigned char *dgst, int dlen, DSA_SIG *sig,
+ CK_MECHANISM Mechanism_dsa = {CKM_DSA, NULL, 0};
+ CK_MECHANISM *p_mech = &Mechanism_dsa;
+ CK_OBJECT_HANDLE h_pub_key;
+ unsigned char sigbuf[DSA_SIGNATURE_LEN];
+ unsigned long siglen = DSA_SIGNATURE_LEN;
+ unsigned long siglen2 = DSA_SIGNATURE_LEN/2;
+ PK11_SESSION *sp = NULL;
+ if (BN_is_zero(sig->r) || sig->r->neg || BN_ucmp(sig->r, dsa->q) >= 0)
+ PK11err(PK11_F_DSA_VERIFY,
+ PK11_R_INVALID_DSA_SIGNATURE_R);
+ if (BN_is_zero(sig->s) || sig->s->neg || BN_ucmp(sig->s, dsa->q) >= 0)
+ PK11err(PK11_F_DSA_VERIFY,
+ PK11_R_INVALID_DSA_SIGNATURE_S);
+ i = BN_num_bytes(dsa->q); /* should be 20 */
+ PK11err(PK11_F_DSA_VERIFY,
+ PK11_R_INVALID_SIGNATURE_LENGTH);
+ if ((sp = pk11_get_session(OP_DSA)) == NULL)
+ (void) check_new_dsa_key_pub(sp, dsa);
+ h_pub_key = sp->opdata_dsa_pub_key;
+ if (h_pub_key == CK_INVALID_HANDLE)
+ h_pub_key = sp->opdata_dsa_pub_key =
+ pk11_get_public_dsa_key((DSA *)dsa, &sp->opdata_dsa_pub,
+ &sp->opdata_dsa_pub_num, sp->session);
+ if (h_pub_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_VerifyInit(sp->session, p_mech,
+ PK11err_add_data(PK11_F_DSA_VERIFY, PK11_R_VERIFYINIT,
+ * The representation of each of the two big numbers could
+ * be shorter than DSA_SIGNATURE_LEN/2 bytes so we need
+ * to act accordingly and shift if necessary.
+ (void) memset(sigbuf, 0, siglen);
+ BN_bn2bin(sig->r, sigbuf + siglen2 - BN_num_bytes(sig->r));
+ BN_bn2bin(sig->s, &sigbuf[siglen2] + siglen2 -
+ rv = pFuncList->C_Verify(sp->session,
+ (unsigned char *) dgst, dlen, sigbuf, (CK_ULONG)siglen);
+ PK11err_add_data(PK11_F_DSA_VERIFY, PK11_R_VERIFY, rv);
+ pk11_return_session(sp, OP_DSA);
+ * Create a public key object in a session from a given dsa structure.
+ * The *dsa_pub_num pointer is non-NULL for DSA public keys.
+static CK_OBJECT_HANDLE pk11_get_public_dsa_key(DSA* dsa,
+ DSA **key_ptr, BIGNUM **dsa_pub_num, CK_SESSION_HANDLE session)
+ CK_OBJECT_CLASS o_key = CKO_PUBLIC_KEY;
+ CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+ CK_KEY_TYPE k_type = CKK_DSA;
+ CK_ULONG ul_key_attr_count = 8;
+ CK_BBOOL rollback = FALSE;
+ CK_ATTRIBUTE a_key_template[] =
+ {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
+ {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
+ {CKA_TOKEN, &myfalse, sizeof (myfalse)},
+ {CKA_VERIFY, &mytrue, sizeof (mytrue)},
+ {CKA_PRIME, (void *)NULL, 0}, /* p */
+ {CKA_SUBPRIME, (void *)NULL, 0}, /* q */
+ {CKA_BASE, (void *)NULL, 0}, /* g */
+ {CKA_VALUE, (void *)NULL, 0} /* pub_key - y */
+ a_key_template[0].pValue = &o_key;
+ a_key_template[1].pValue = &k_type;
+ if (init_template_value(dsa->p, &a_key_template[4].pValue,
+ &a_key_template[4].ulValueLen) == 0 ||
+ init_template_value(dsa->q, &a_key_template[5].pValue,
+ &a_key_template[5].ulValueLen) == 0 ||
+ init_template_value(dsa->g, &a_key_template[6].pValue,
+ &a_key_template[6].ulValueLen) == 0 ||
+ init_template_value(dsa->pub_key, &a_key_template[7].pValue,
+ &a_key_template[7].ulValueLen) == 0)
+ PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_MALLOC_FAILURE);
+ /* see find_lock array definition for more info on object locking */
+ rv = pFuncList->C_FindObjectsInit(session, a_key_template,
+ PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
+ PK11_R_FINDOBJECTSINIT, rv);
+ rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+ (void) pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
+ PK11_R_FINDOBJECTS, rv);
+ rv = pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
+ PK11_R_FINDOBJECTSFINAL, rv);
+ rv = pFuncList->C_CreateObject(session,
+ a_key_template, ul_key_attr_count, &h_key);
+ PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
+ PK11_R_CREATEOBJECT, rv);
+ if (dsa_pub_num != NULL)
+ if ((*dsa_pub_num = BN_dup(dsa->pub_key)) == NULL)
+ PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_MALLOC_FAILURE);
+ /* LINTED: E_CONSTANT_CONDITION */
+ KEY_HANDLE_REFHOLD(h_key, OP_DSA, FALSE, rollback, err);
+ * We do not care about the return value from C_DestroyObject()
+ * since we are doing rollback.
+ (void) pFuncList->C_DestroyObject(session, h_key);
+ h_key = CK_INVALID_HANDLE;
+ UNLOCK_OBJSTORE(OP_DSA);
+ for (i = 4; i <= 7; i++)
+ if (a_key_template[i].pValue != NULL)
+ OPENSSL_free(a_key_template[i].pValue);
+ a_key_template[i].pValue = NULL;
+ * Create a private key object in the session from a given dsa structure
+ * The *dsa_priv_num pointer is non-NULL for DSA private keys.
+static CK_OBJECT_HANDLE pk11_get_private_dsa_key(DSA* dsa,
+ DSA **key_ptr, BIGNUM **dsa_priv_num, CK_SESSION_HANDLE session)
+ CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+ CK_OBJECT_CLASS o_key = CKO_PRIVATE_KEY;
+ CK_KEY_TYPE k_type = CKK_DSA;
+ CK_ULONG ul_key_attr_count = 9;
+ CK_BBOOL rollback = FALSE;
+ /* Both CKA_TOKEN and CKA_SENSITIVE have to be FALSE for session keys */
+ CK_ATTRIBUTE a_key_template[] =
+ {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
+ {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
+ {CKA_TOKEN, &myfalse, sizeof (myfalse)},
+ {CKA_SENSITIVE, &myfalse, sizeof (myfalse)},
+ {CKA_SIGN, &mytrue, sizeof (mytrue)},
+ {CKA_PRIME, (void *)NULL, 0}, /* p */
+ {CKA_SUBPRIME, (void *)NULL, 0}, /* q */
+ {CKA_BASE, (void *)NULL, 0}, /* g */
+ {CKA_VALUE, (void *)NULL, 0} /* priv_key - x */
+ a_key_template[0].pValue = &o_key;
+ a_key_template[1].pValue = &k_type;
+ /* Put the private key components into the template */
+ if (init_template_value(dsa->p, &a_key_template[5].pValue,
+ &a_key_template[5].ulValueLen) == 0 ||
+ init_template_value(dsa->q, &a_key_template[6].pValue,
+ &a_key_template[6].ulValueLen) == 0 ||
+ init_template_value(dsa->g, &a_key_template[7].pValue,
+ &a_key_template[7].ulValueLen) == 0 ||
+ init_template_value(dsa->priv_key, &a_key_template[8].pValue,
+ &a_key_template[8].ulValueLen) == 0)
+ PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_MALLOC_FAILURE);
+ /* see find_lock array definition for more info on object locking */
+ rv = pFuncList->C_FindObjectsInit(session, a_key_template,
+ PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
+ PK11_R_FINDOBJECTSINIT, rv);
+ rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+ (void) pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
+ PK11_R_FINDOBJECTS, rv);
+ rv = pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
+ PK11_R_FINDOBJECTSFINAL, rv);
+ rv = pFuncList->C_CreateObject(session,
+ a_key_template, ul_key_attr_count, &h_key);
+ PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
+ PK11_R_CREATEOBJECT, rv);
+ if (dsa_priv_num != NULL)
+ if ((*dsa_priv_num = BN_dup(dsa->priv_key)) == NULL)
+ PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_MALLOC_FAILURE);
+ /* LINTED: E_CONSTANT_CONDITION */
+ KEY_HANDLE_REFHOLD(h_key, OP_DSA, FALSE, rollback, err);
+ * We do not care about the return value from C_DestroyObject()
+ * since we are doing rollback.
+ (void) pFuncList->C_DestroyObject(session, h_key);
+ h_key = CK_INVALID_HANDLE;
+ UNLOCK_OBJSTORE(OP_DSA);
+ * 5 to 8 entries in the key template are key components.
+ * They need to be freed apon exit or error.
+ for (i = 5; i <= 8; i++)
+ if (a_key_template[i].pValue != NULL)
+ (void) memset(a_key_template[i].pValue, 0,
+ a_key_template[i].ulValueLen);
+ OPENSSL_free(a_key_template[i].pValue);
+ a_key_template[i].pValue = NULL;
+ * Check for cache miss and clean the object pointer and handle
+ * in such case. Return 1 for cache hit, 0 for cache miss.
+static int check_new_dsa_key_pub(PK11_SESSION *sp, DSA *dsa)
+ * Provide protection against DSA structure reuse by making the
+ * check for cache hit stronger. Only public key component of DSA
+ * key matters here so it is sufficient to compare it with value
+ * cached in PK11_SESSION structure.
+ if ((sp->opdata_dsa_pub != dsa) ||
+ (BN_cmp(sp->opdata_dsa_pub_num, dsa->pub_key) != 0))
+ * We do not check the return value because even in case of
+ * failure the sp structure will have both key pointer
+ * and object handle cleaned and pk11_destroy_object()
+ * reports the failure to the OpenSSL error message buffer.
+ (void) pk11_destroy_dsa_object_pub(sp, TRUE);
+ * Check for cache miss and clean the object pointer and handle
+ * in such case. Return 1 for cache hit, 0 for cache miss.
+static int check_new_dsa_key_priv(PK11_SESSION *sp, DSA *dsa)
+ * Provide protection against DSA structure reuse by making the
+ * check for cache hit stronger. Only private key component of DSA
+ * key matters here so it is sufficient to compare it with value
+ * cached in PK11_SESSION structure.
+ if ((sp->opdata_dsa_priv != dsa) ||
+ (BN_cmp(sp->opdata_dsa_priv_num, dsa->priv_key) != 0))
+ * We do not check the return value because even in case of
+ * failure the sp structure will have both key pointer
+ * and object handle cleaned and pk11_destroy_object()
+ * reports the failure to the OpenSSL error message buffer.
+ (void) pk11_destroy_dsa_object_priv(sp, TRUE);
+/* The DH function implementation */
+static int pk11_DH_init(DH *dh)
+static int pk11_DH_finish(DH *dh)
+ * Generate DH key-pair.
+ * Warning: Unlike OpenSSL's DH_generate_key(3) we ignore dh->priv_key
+ * and override it even if it is set. OpenSSL does not touch dh->priv_key
+ * if set and just computes dh->pub_key. It looks like PKCS#11 standard
+ * is not capable of providing this functionality. This could be a problem
+ * for applications relying on OpenSSL's semantics.
+static int pk11_DH_generate_key(DH *dh)
+ int reuse_mem_len = 0, ret = 0;
+ PK11_SESSION *sp = NULL;
+ CK_MECHANISM mechanism = {CKM_DH_PKCS_KEY_PAIR_GEN, NULL_PTR, 0};
+ CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
+ CK_OBJECT_HANDLE h_priv_key = CK_INVALID_HANDLE;
+ CK_ULONG ul_pub_key_attr_count = 3;
+ CK_ATTRIBUTE pub_key_template[] =
+ {CKA_PRIVATE, &myfalse, sizeof (myfalse)},
+ {CKA_PRIME, (void *)NULL, 0},
+ {CKA_BASE, (void *)NULL, 0}
+ CK_ULONG ul_priv_key_attr_count = 3;
+ CK_ATTRIBUTE priv_key_template[] =
+ {CKA_PRIVATE, &myfalse, sizeof (myfalse)},
+ {CKA_SENSITIVE, &myfalse, sizeof (myfalse)},
+ {CKA_DERIVE, &mytrue, sizeof (mytrue)}
+ CK_ULONG pub_key_attr_result_count = 1;
+ CK_ATTRIBUTE pub_key_result[] =
+ {CKA_VALUE, (void *)NULL, 0}
+ CK_ULONG priv_key_attr_result_count = 1;
+ CK_ATTRIBUTE priv_key_result[] =
+ {CKA_VALUE, (void *)NULL, 0}
+ pub_key_template[1].ulValueLen = BN_num_bytes(dh->p);
+ if (pub_key_template[1].ulValueLen > 0)
+ * We must not increase ulValueLen by DH_BUF_RESERVE since that
+ * could cause the same rounding problem. See definition of
+ * DH_BUF_RESERVE above.
+ pub_key_template[1].pValue =
+ OPENSSL_malloc(pub_key_template[1].ulValueLen +
+ if (pub_key_template[1].pValue == NULL)
+ PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
+ i = BN_bn2bin(dh->p, pub_key_template[1].pValue);
+ pub_key_template[2].ulValueLen = BN_num_bytes(dh->g);
+ if (pub_key_template[2].ulValueLen > 0)
+ pub_key_template[2].pValue =
+ OPENSSL_malloc(pub_key_template[2].ulValueLen +
+ if (pub_key_template[2].pValue == NULL)
+ PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
+ i = BN_bn2bin(dh->g, pub_key_template[2].pValue);
+ * Note: we are only using PK11_SESSION structure for getting
+ * a session handle. The objects created in this function are
+ * destroyed before return and thus not cached.
+ if ((sp = pk11_get_session(OP_DH)) == NULL)
+ rv = pFuncList->C_GenerateKeyPair(sp->session,
+ ul_priv_key_attr_count,
+ PK11err_add_data(PK11_F_DH_GEN_KEY, PK11_R_GEN_KEY, rv);
+ * Reuse the larger memory allocated. We know the larger memory
+ * should be sufficient for reuse.
+ if (pub_key_template[1].ulValueLen > pub_key_template[2].ulValueLen)
+ reuse_mem = pub_key_template[1].pValue;
+ reuse_mem_len = pub_key_template[1].ulValueLen + DH_BUF_RESERVE;
+ reuse_mem = pub_key_template[2].pValue;
+ reuse_mem_len = pub_key_template[2].ulValueLen + DH_BUF_RESERVE;
+ rv = pFuncList->C_GetAttributeValue(sp->session, h_pub_key,
+ pub_key_result, pub_key_attr_result_count);
+ rv1 = pFuncList->C_GetAttributeValue(sp->session, h_priv_key,
+ priv_key_result, priv_key_attr_result_count);
+ if (rv != CKR_OK || rv1 != CKR_OK)
+ rv = (rv != CKR_OK) ? rv : rv1;
+ PK11err_add_data(PK11_F_DH_GEN_KEY,
+ PK11_R_GETATTRIBUTVALUE, rv);
+ if (((CK_LONG) pub_key_result[0].ulValueLen) <= 0 ||
+ ((CK_LONG) priv_key_result[0].ulValueLen) <= 0)
+ PK11err(PK11_F_DH_GEN_KEY, PK11_R_GETATTRIBUTVALUE);
+ /* Reuse the memory allocated */
+ pub_key_result[0].pValue = reuse_mem;
+ pub_key_result[0].ulValueLen = reuse_mem_len;
+ rv = pFuncList->C_GetAttributeValue(sp->session, h_pub_key,
+ pub_key_result, pub_key_attr_result_count);
+ PK11err_add_data(PK11_F_DH_GEN_KEY,
+ PK11_R_GETATTRIBUTVALUE, rv);
+ if (pub_key_result[0].type == CKA_VALUE)
+ if (dh->pub_key == NULL)
+ if ((dh->pub_key = BN_new()) == NULL)
+ PK11err(PK11_F_DH_GEN_KEY,
+ PK11_R_MALLOC_FAILURE);
+ dh->pub_key = BN_bin2bn(pub_key_result[0].pValue,
+ pub_key_result[0].ulValueLen, dh->pub_key);
+ if (dh->pub_key == NULL)
+ PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
+ /* Reuse the memory allocated */
+ priv_key_result[0].pValue = reuse_mem;
+ priv_key_result[0].ulValueLen = reuse_mem_len;
+ rv = pFuncList->C_GetAttributeValue(sp->session, h_priv_key,
+ priv_key_result, priv_key_attr_result_count);
+ PK11err_add_data(PK11_F_DH_GEN_KEY,
+ PK11_R_GETATTRIBUTVALUE, rv);
+ if (priv_key_result[0].type == CKA_VALUE)
+ if (dh->priv_key == NULL)
+ if ((dh->priv_key = BN_new()) == NULL)
+ PK11err(PK11_F_DH_GEN_KEY,
+ PK11_R_MALLOC_FAILURE);
+ dh->priv_key = BN_bin2bn(priv_key_result[0].pValue,
+ priv_key_result[0].ulValueLen, dh->priv_key);
+ if (dh->priv_key == NULL)
+ PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
+ if (h_pub_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_DestroyObject(sp->session, h_pub_key);
+ PK11err_add_data(PK11_F_DH_GEN_KEY,
+ PK11_R_DESTROYOBJECT, rv);
+ if (h_priv_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_DestroyObject(sp->session, h_priv_key);
+ PK11err_add_data(PK11_F_DH_GEN_KEY,
+ PK11_R_DESTROYOBJECT, rv);
+ for (i = 1; i <= 2; i++)
+ if (pub_key_template[i].pValue != NULL)
+ OPENSSL_free(pub_key_template[i].pValue);
+ pub_key_template[i].pValue = NULL;
+ pk11_return_session(sp, OP_DH);
+static int pk11_DH_compute_key(unsigned char *key, const BIGNUM *pub_key,
+ CK_MECHANISM mechanism = {CKM_DH_PKCS_DERIVE, NULL_PTR, 0};
+ CK_OBJECT_CLASS key_class = CKO_SECRET_KEY;
+ CK_KEY_TYPE key_type = CKK_GENERIC_SECRET;
+ CK_OBJECT_HANDLE h_derived_key = CK_INVALID_HANDLE;
+ CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+ CK_ULONG ul_priv_key_attr_count = 3;
+ CK_ATTRIBUTE priv_key_template[] =
+ {CKA_CLASS, (void*) NULL, sizeof (key_class)},
+ {CKA_KEY_TYPE, (void*) NULL, sizeof (key_type)},
+ {CKA_VALUE_LEN, &seclen, sizeof (seclen)},
+ CK_ULONG priv_key_attr_result_count = 1;
+ CK_ATTRIBUTE priv_key_result[] =
+ {CKA_VALUE, (void *)NULL, 0}
+ PK11_SESSION *sp = NULL;
+ if (dh->priv_key == NULL)
+ priv_key_template[0].pValue = &key_class;
+ priv_key_template[1].pValue = &key_type;
+ seclen = BN_num_bytes(dh->p);
+ if ((sp = pk11_get_session(OP_DH)) == NULL)
+ PK11err(PK11_F_DH_COMP_KEY, PK11_R_MALLOC_FAILURE);
+ (void) check_new_dh_key(sp, dh);
+ h_key = sp->opdata_dh_key;
+ if (h_key == CK_INVALID_HANDLE)
+ h_key = sp->opdata_dh_key =
+ pk11_get_dh_key((DH*) dh, &sp->opdata_dh,
+ &sp->opdata_dh_priv_num, sp->session);
+ if (h_key == CK_INVALID_HANDLE)
+ PK11err(PK11_F_DH_COMP_KEY, PK11_R_CREATEOBJECT);
+ rv = pFuncList->C_DeriveKey(sp->session,
+ ul_priv_key_attr_count,
+ PK11err_add_data(PK11_F_DH_COMP_KEY, PK11_R_DERIVEKEY, rv);
+ rv = pFuncList->C_GetAttributeValue(sp->session, h_derived_key,
+ priv_key_result, priv_key_attr_result_count);
+ PK11err_add_data(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE,
+ if (((CK_LONG) priv_key_result[0].ulValueLen) <= 0)
+ PK11err(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE);
+ priv_key_result[0].pValue =
+ OPENSSL_malloc(priv_key_result[0].ulValueLen);
+ if (!priv_key_result[0].pValue)
+ PK11err(PK11_F_DH_COMP_KEY, PK11_R_MALLOC_FAILURE);
+ rv = pFuncList->C_GetAttributeValue(sp->session, h_derived_key,
+ priv_key_result, priv_key_attr_result_count);
+ PK11err_add_data(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE,
+ * OpenSSL allocates the output buffer 'key' which is the same
+ * length of the public key. It is long enough for the derived key
+ if (priv_key_result[0].type == CKA_VALUE)
+ * CKM_DH_PKCS_DERIVE mechanism is not supposed to strip
+ * leading zeros from a computed shared secret. However,
+ * OpenSSL always did it so we must do the same here. The
+ * vagueness of the spec regarding leading zero bytes was
+ * finally cleared with TLS 1.1 (RFC 4346) saying that leading
+ * zeros are stripped before the computed data is used as the
+ for (i = 0; i < priv_key_result[0].ulValueLen; ++i)
+ if (((char *)priv_key_result[0].pValue)[i] != 0)
+ (void) memcpy(key, ((char *)priv_key_result[0].pValue) + i,
+ priv_key_result[0].ulValueLen - i);
+ ret = priv_key_result[0].ulValueLen - i;
+ if (h_derived_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_DestroyObject(sp->session, h_derived_key);
+ PK11err_add_data(PK11_F_DH_COMP_KEY,
+ PK11_R_DESTROYOBJECT, rv);
+ if (priv_key_result[0].pValue)
+ OPENSSL_free(priv_key_result[0].pValue);
+ priv_key_result[0].pValue = NULL;
+ pk11_return_session(sp, OP_DH);
+static CK_OBJECT_HANDLE pk11_get_dh_key(DH* dh,
+ DH **key_ptr, BIGNUM **dh_priv_num, CK_SESSION_HANDLE session)
+ CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+ CK_OBJECT_CLASS class = CKO_PRIVATE_KEY;
+ CK_KEY_TYPE key_type = CKK_DH;
+ CK_BBOOL rollback = FALSE;
+ CK_ULONG ul_key_attr_count = 7;
+ CK_ATTRIBUTE key_template[] =
+ {CKA_CLASS, (void*) NULL, sizeof (class)},
+ {CKA_KEY_TYPE, (void*) NULL, sizeof (key_type)},
+ {CKA_DERIVE, &mytrue, sizeof (mytrue)},
+ {CKA_PRIVATE, &myfalse, sizeof (myfalse)},
+ {CKA_PRIME, (void *) NULL, 0},
+ {CKA_BASE, (void *) NULL, 0},
+ {CKA_VALUE, (void *) NULL, 0},
+ key_template[0].pValue = &class;
+ key_template[1].pValue = &key_type;
+ key_template[4].ulValueLen = BN_num_bytes(dh->p);
+ key_template[4].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+ (size_t)key_template[4].ulValueLen);
+ if (key_template[4].pValue == NULL)
+ PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
+ BN_bn2bin(dh->p, key_template[4].pValue);
+ key_template[5].ulValueLen = BN_num_bytes(dh->g);
+ key_template[5].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+ (size_t)key_template[5].ulValueLen);
+ if (key_template[5].pValue == NULL)
+ PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
+ BN_bn2bin(dh->g, key_template[5].pValue);
+ key_template[6].ulValueLen = BN_num_bytes(dh->priv_key);
+ key_template[6].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+ (size_t)key_template[6].ulValueLen);
+ if (key_template[6].pValue == NULL)
+ PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
+ BN_bn2bin(dh->priv_key, key_template[6].pValue);
+ /* see find_lock array definition for more info on object locking */
+ rv = pFuncList->C_FindObjectsInit(session, key_template,
+ PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTSINIT, rv);
+ rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+ (void) pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTS, rv);
+ rv = pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTSFINAL,
+ rv = pFuncList->C_CreateObject(session,
+ key_template, ul_key_attr_count, &h_key);
+ PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_CREATEOBJECT,
+ if (dh_priv_num != NULL)
+ if ((*dh_priv_num = BN_dup(dh->priv_key)) == NULL)
+ PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
+ /* LINTED: E_CONSTANT_CONDITION */
+ KEY_HANDLE_REFHOLD(h_key, OP_DH, FALSE, rollback, err);
+ * We do not care about the return value from C_DestroyObject()
+ * since we are doing rollback.
+ (void) pFuncList->C_DestroyObject(session, h_key);
+ h_key = CK_INVALID_HANDLE;
+ UNLOCK_OBJSTORE(OP_DH);
+ for (i = 4; i <= 6; i++)
+ if (key_template[i].pValue != NULL)
+ OPENSSL_free(key_template[i].pValue);
+ key_template[i].pValue = NULL;
+ * Check for cache miss and clean the object pointer and handle
+ * in such case. Return 1 for cache hit, 0 for cache miss.
+ * Note: we rely on pk11_destroy_dh_key_objects() to set sp->opdata_dh
+ * to CK_INVALID_HANDLE even when it fails to destroy the object.
+static int check_new_dh_key(PK11_SESSION *sp, DH *dh)
+ * Provide protection against DH structure reuse by making the
+ * check for cache hit stronger. Private key component of DH key
+ * is unique so it is sufficient to compare it with value cached
+ * in PK11_SESSION structure.
+ if ((sp->opdata_dh != dh) ||
+ (BN_cmp(sp->opdata_dh_priv_num, dh->priv_key) != 0))
+ * We do not check the return value because even in case of
+ * failure the sp structure will have both key pointer
+ * and object handle cleaned and pk11_destroy_object()
+ * reports the failure to the OpenSSL error message buffer.
+ (void) pk11_destroy_dh_object(sp, TRUE);
+ * Local function to simplify key template population
+ * Return 0 -- error, 1 -- no error
+init_template_value(BIGNUM *bn, CK_VOID_PTR *p_value,
+ CK_ULONG *ul_value_len)
+ * This function can be used on non-initialized BIGNUMs. It is
+ * easier to check that here than individually in the callers.
+ len = BN_num_bytes(bn);
+ if (bn == NULL || len == 0)
+ *p_value = (CK_VOID_PTR)OPENSSL_malloc((size_t)*ul_value_len);
+ BN_bn2bin(bn, *p_value);
+attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn)
+ if (attr->ulValueLen > 0)
+ *bn = BN_bin2bn(attr_data, attr->ulValueLen, NULL);
+ * Find one object in the token. It is an error if we can not find the
+ * object or if we find more objects based on the template we got.
+ * Assume object store locked.
+ * 0 no object or more than 1 object found
+find_one_object(PK11_OPTYPE op, CK_SESSION_HANDLE s,
+ CK_ATTRIBUTE_PTR ptempl, CK_ULONG nattr, CK_OBJECT_HANDLE_PTR pkey)
+ if ((rv = pFuncList->C_FindObjectsInit(s, ptempl, nattr)) != CKR_OK)
+ PK11err_add_data(PK11_F_FIND_ONE_OBJECT,
+ PK11_R_FINDOBJECTSINIT, rv);
+ rv = pFuncList->C_FindObjects(s, pkey, 1, &objcnt);
+ (void) pFuncList->C_FindObjectsFinal(s);
+ PK11err_add_data(PK11_F_FIND_ONE_OBJECT, PK11_R_FINDOBJECTS,
+ (void) pFuncList->C_FindObjectsFinal(s);
+ PK11err(PK11_F_FIND_ONE_OBJECT,
+ PK11_R_MORE_THAN_ONE_OBJECT_FOUND);
+ PK11err(PK11_F_FIND_ONE_OBJECT, PK11_R_NO_OBJECT_FOUND);
+static int pk11_get_pin(void);
+ /* The getpassphrase() function is not MT safe. */
+ OPENSSL_assert(pthread_mutex_lock(token_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ pin = getpassphrase("Enter PIN: ");
+ PK11err(PK11_F_GET_PIN, PK11_R_COULD_NOT_READ_PIN);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ pk11_pin = BUF_strdup(pin);
+ PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_MALLOC_FAILURE);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ memset(pin, 0, strlen(pin));
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ * Log in to the keystore if we are supposed to do that at all. Take care of
+ * reading and caching the PIN etc. Log in only once even when called from
+pk11_token_login(CK_SESSION_HANDLE session, CK_BBOOL *login_done,
+ /* doesn't work on the AEP Keyper??? */
+ if ((pubkey_token_flags & CKF_TOKEN_INITIALIZED) == 0)
+ PK11err(PK11_F_TOKEN_LOGIN,
+ PK11_R_TOKEN_NOT_INITIALIZED);
+ * If login is required or needed but the PIN has not been
+ * even initialized we can bail out right now. Note that we
+ * are supposed to always log in if we are going to access
+ * private keys. However, we may need to log in even for
+ * accessing public keys in case that the CKF_LOGIN_REQUIRED
+ if (((pubkey_token_flags & CKF_LOGIN_REQUIRED) ||
+ (is_private == CK_TRUE)) &&
+ (~pubkey_token_flags & CKF_USER_PIN_INITIALIZED))
+ PK11err(PK11_F_TOKEN_LOGIN, PK11_R_TOKEN_PIN_NOT_SET);
+ * Note on locking: it is possible that more than one thread
+ * gets into pk11_get_pin() so we must deal with that. We
+ * cannot avoid it since we cannot guard fork() in there with
+ * a lock because we could end up in a dead lock in the
+ * child. Why? Remember we are in a multithreaded environment
+ * so we must lock all mutexes in the prefork function to
+ * avoid a situation in which a thread that did not call
+ * fork() held a lock, making future unlocking impossible. We
+ * lock right before C_Login().
+ if ((pubkey_token_flags & CKF_LOGIN_REQUIRED) ||
+ (is_private == CK_TRUE))
+ if (*login_done == CK_FALSE)
+ if ((pk11_pin == NULL) && (pk11_get_pin() == 0))
+ PK11err(PK11_F_TOKEN_LOGIN,
+ PK11_R_TOKEN_PIN_NOT_PROVIDED);
+ * Note that what we are logging into is the keystore from
+ * pubkey_SLOTID because we work with OP_RSA session type here.
+ * That also means that we can work with only one keystore in
+ * We must make sure we do not try to login more than once.
+ * Also, see the comment above on locking strategy.
+ OPENSSL_assert(pthread_mutex_lock(token_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ if (*login_done == CK_FALSE)
+ if ((rv = pFuncList->C_Login(session,
+ CKU_USER, (CK_UTF8CHAR*)pk11_pin,
+ strlen(pk11_pin))) != CKR_OK)
+ PK11err_add_data(PK11_F_TOKEN_LOGIN,
+ PK11_R_TOKEN_LOGIN_FAILED, rv);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ * If token does not require login we take it as the
+ memset(pk11_pin, 0, strlen(pk11_pin));
+ OPENSSL_free((void*)pk11_pin);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ * Log in to the keystore in the child if we were logged in in the
+ * parent. There are similarities in the code with pk11_token_login()
+ * but still it is quite different so we need a separate function for
+ * Note that this function is called under the locked session mutex when fork is
+ * detected. That means that C_Login() will be called from the child just once.
+pk11_token_relogin(CK_SESSION_HANDLE session)
+ if ((pk11_pin == NULL) && (pk11_get_pin() == 0))
+ OPENSSL_assert(pthread_mutex_lock(token_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ if ((rv = pFuncList->C_Login(session, CKU_USER,
+ (CK_UTF8CHAR_PTR)pk11_pin, strlen(pk11_pin))) != CKR_OK)
+ PK11err_add_data(PK11_F_TOKEN_RELOGIN,
+ PK11_R_TOKEN_LOGIN_FAILED, rv);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+#ifdef OPENSSL_SYS_WIN32
+char *getpassphrase(const char *prompt)
+ h = GetStdHandle(STD_INPUT_HANDLE);
+ FlushConsoleInputBuffer(h);
+ GetConsoleMode(h, &mode);
+ SetConsoleMode(h, ENABLE_PROCESSED_INPUT);
+ for (cnt = 0; cnt < sizeof(buf) - 1; cnt++)
+ ReadFile(h, buf + cnt, 1, &cc, NULL);
+ SetConsoleMode(h, mode);
+#endif /* OPENSSL_SYS_WIN32 */
+#endif /* OPENSSL_NO_HW_PK11CA */
+#endif /* OPENSSL_NO_HW_PK11 */
+#endif /* OPENSSL_NO_HW */
+#define token_lock pk11ca_token_lock
+#define find_lock pk11ca_find_lock
+#define active_list pk11ca_active_list
+#define pubkey_token_flags pk11ca_pubkey_token_flags
+#define pubkey_SLOTID pk11ca_pubkey_SLOTID
+#define ERR_pk11_error ERR_pk11ca_error
+#define PK11err_add_data PK11CAerr_add_data
+#define pk11_get_session pk11ca_get_session
+#define pk11_return_session pk11ca_return_session
+#define pk11_active_add pk11ca_active_add
+#define pk11_active_delete pk11ca_active_delete
+#define pk11_active_remove pk11ca_active_remove
+#define pk11_free_active_list pk11ca_free_active_list
+#define pk11_destroy_rsa_key_objects pk11ca_destroy_rsa_key_objects
+#define pk11_destroy_rsa_object_pub pk11ca_destroy_rsa_object_pub
+#define pk11_destroy_rsa_object_priv pk11ca_destroy_rsa_object_priv
+#define pk11_load_privkey pk11ca_load_privkey
+#define pk11_load_pubkey pk11ca_load_pubkey
+#define PK11_RSA PK11CA_RSA
+#define pk11_destroy_dsa_key_objects pk11ca_destroy_dsa_key_objects
+#define pk11_destroy_dsa_object_pub pk11ca_destroy_dsa_object_pub
+#define pk11_destroy_dsa_object_priv pk11ca_destroy_dsa_object_priv
+#define PK11_DSA PK11CA_DSA
+#define pk11_destroy_dh_key_objects pk11ca_destroy_dh_key_objects
+#define pk11_destroy_dh_object pk11ca_destroy_dh_object
+#define PK11_DH PK11CA_DH
+#define pk11_token_relogin pk11ca_token_relogin
+#define pFuncList pk11ca_pFuncList
+#define pk11_pin pk11ca_pin
+#define ENGINE_load_pk11 ENGINE_load_pk11ca
+ * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
+ * This product includes software developed by the OpenSSL Project for
+ * ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project. All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation
and/or other materials provided with the
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * licensing@OpenSSL.org.
+ * 5. Products derived from this software may not be called "OpenSSL"
+ * nor may "OpenSSL" appear in their names without prior written
+ * permission of the OpenSSL Project.
+ * 6. Redistributions of any form whatsoever must retain the following
+ * "This product includes software developed by the OpenSSL Project
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com). This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+/* Modified to keep only RNG and RSA Sign */
+#ifdef OPENSSL_SYS_WIN32
+#define getpid() GetCurrentProcessId()
+#define CK_DEFINE_FUNCTION(returnType, name) \
+ returnType __declspec(dllexport) name
+#define CK_DECLARE_FUNCTION(returnType, name) \
+ returnType __declspec(dllimport) name
+#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ returnType __declspec(dllimport) (* name)
+/* for pthread error check on Linuxes */
+#ifndef OPENSSL_NO_HW_PK11
+#ifndef OPENSSL_NO_HW_PK11SO
+/* label for debug messages printed on stderr */
+#define PK11_DBG "PKCS#11 ENGINE DEBUG"
+/* prints a lot of debug messages on stderr about slot selection process */
+/*#undef DEBUG_SLOT_SELECTION */
+#ifdef OPENSSL_SYS_WIN32
+#pragma pack(push, cryptoki, 1)
+#pragma pack(pop, cryptoki)
+ * We use this lock to prevent multiple C_Login()s, guard getpassphrase(),
+ * uri_struct manipulation, and static token info. All of that is used by the
+ * RSA keys by reference feature.
+pthread_mutex_t *token_lock;
+/* PKCS#11 session caches and their locks for all operation types */
+static PK11_CACHE session_cache[OP_MAX];
+ * We cache the flags so that we do not have to run C_GetTokenInfo() again when
+ * logging into the token.
+CK_FLAGS pubkey_token_flags;
+ * As stated in v2.20, 11.7 Object Management Function, in section for
+ * C_FindObjectsInit(), at most one search operation may be active at a given
+ * time in a given session. Therefore, C_Find{,Init,Final}Objects() should be
+ * grouped together to form one atomic search operation. This is already
+ * ensured by the property of unique PKCS#11 session handle used for each
+ * This is however not the biggest concern - maintaining consistency of the
+ * underlying object store is more important. The same section of the spec also
+ * says that one thread can be in the middle of a search operation while another
+ * thread destroys the object matching the search template which would result in
+ * invalid handle returned from the search operation.
+ * Hence, the following locks are used for both protection of the object stores.
+ * They are also used for active list protection.
+pthread_mutex_t *find_lock[OP_MAX] = { NULL };
+ * lists of asymmetric key handles which are active (referenced by at least one
+ * PK11_SESSION structure, either held by a thread or present in free_session
+ * list) for given algorithm type
+PK11_active *active_list[OP_MAX] = { NULL };
+ * Create all secret key objects in a global session so that they are available
+ * to use for other sessions. These other sessions may be opened or closed
+ * without losing the secret key objects.
+static CK_SESSION_HANDLE global_session = CK_INVALID_HANDLE;
+/* ENGINE level stuff */
+static int pk11_init(ENGINE *e);
+static int pk11_library_init(ENGINE *e);
+static int pk11_finish(ENGINE *e);
+static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void));
+static int pk11_destroy(ENGINE *e);
+static void pk11_rand_seed(const void *buf, int num);
+static void pk11_rand_add(const void *buf, int num, double add_entropy);
+static void pk11_rand_cleanup(void);
+static int pk11_rand_bytes(unsigned char *buf, int num);
+static int pk11_rand_status(void);
+/* These functions are also used in other files */
+PK11_SESSION *pk11_get_session(PK11_OPTYPE optype);
+void pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype);
+/* active list manipulation functions used in this file */
+extern int pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type);
+extern void pk11_free_active_list(PK11_OPTYPE type);
+int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
+int pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
+int pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
+/* Local helper functions */
+static int pk11_free_all_sessions(void);
+static int pk11_free_session_list(PK11_OPTYPE optype);
+static int pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype);
+static int pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh,
+static const char *get_PK11_LIBNAME(void);
+static void free_PK11_LIBNAME(void);
+static long set_PK11_LIBNAME(const char *name);
+static int pk11_choose_slots(int *any_slot_found);
+static int pk11_init_all_locks(void);
+static void pk11_free_all_locks(void);
+#define TRY_OBJ_DESTROY(sp, obj_hdl, retval, uselock, alg_type, priv) \
+ LOCK_OBJSTORE(alg_type); \
+ if (pk11_active_delete(obj_hdl, alg_type) == 1) \
+ retval = pk11_destroy_object(sp->session, obj_hdl, \
+ priv ? sp->priv_persistent : sp->pub_persistent); \
+ UNLOCK_OBJSTORE(alg_type); \
+static CK_BBOOL pk11_have_rsa = CK_FALSE;
+static CK_BBOOL pk11_have_random = CK_FALSE;
+ * Initialization function. Sets up various PKCS#11 library components.
+ * The definitions for control commands specific to this engine
+#define PK11_CMD_SO_PATH ENGINE_CMD_BASE
+#define PK11_CMD_PIN (ENGINE_CMD_BASE+1)
+#define PK11_CMD_SLOT (ENGINE_CMD_BASE+2)
+static const ENGINE_CMD_DEFN pk11_cmd_defns[] =
+ "Specifies the path to the 'pkcs#11' shared library",
+ "Specifies the pin code",
+ "Specifies the slot (default is auto select)",
+ ENGINE_CMD_FLAG_NUMERIC,
+static RAND_METHOD pk11_random =
+/* Constants used when creating the ENGINE */
+#ifdef OPENSSL_NO_HW_PK11CA
+#error "can't load both crypto-accelerator and sign-only PKCS#11 engines"
+static const char *engine_pk11_id = "pkcs11";
+static const char *engine_pk11_name = "PKCS #11 engine support (sign only)";
+CK_FUNCTION_LIST_PTR pFuncList = NULL;
+static const char PK11_GET_FUNCTION_LIST[] = "C_GetFunctionList";
+ * This is a static string constant for the DSO file name and the function
+ * symbol names to bind to. We set it in the Configure script based on whether
+ * this is 32 or 64 bit build.
+static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;
+/* Needed in
hw_pk11_pub.c as well so that's why it is not static. */
+CK_SLOT_ID pubkey_SLOTID = 0;
+static CK_SLOT_ID rand_SLOTID = 0;
+static CK_SLOT_ID SLOTID = 0;
+static CK_BBOOL pk11_library_initialized = FALSE;
+static CK_BBOOL pk11_atfork_initialized = FALSE;
+static int pk11_pid = 0;
+static DSO *pk11_dso = NULL;
+/* allocate and initialize all locks used by the engine itself */
+static int pk11_init_all_locks(void)
+ pthread_mutexattr_t attr;
+ if (pthread_mutexattr_init(&attr) != 0)
+ PK11err(PK11_F_INIT_ALL_LOCKS, 100);
+ if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK) != 0)
+ PK11err(PK11_F_INIT_ALL_LOCKS, 101);
+ if ((token_lock = OPENSSL_malloc(sizeof (pthread_mutex_t))) == NULL)
+ (void) pthread_mutex_init(token_lock, &attr);
+ find_lock[OP_RSA] = OPENSSL_malloc(sizeof (pthread_mutex_t));
+ if (find_lock[OP_RSA] == NULL)
+ (void) pthread_mutex_init(find_lock[OP_RSA], &attr);
+ for (type = 0; type < OP_MAX; type++)
+ session_cache[type].lock =
+ OPENSSL_malloc(sizeof (pthread_mutex_t));
+ if (session_cache[type].lock == NULL)
+ (void) pthread_mutex_init(session_cache[type].lock, &attr);
+ PK11err(PK11_F_INIT_ALL_LOCKS, PK11_R_MALLOC_FAILURE);
+static void pk11_free_all_locks(void)
+ if (token_lock != NULL)
+ (void) pthread_mutex_destroy(token_lock);
+ OPENSSL_free(token_lock);
+ if (find_lock[OP_RSA] != NULL)
+ (void) pthread_mutex_destroy(find_lock[OP_RSA]);
+ OPENSSL_free(find_lock[OP_RSA]);
+ find_lock[OP_RSA] = NULL;
+ for (type = 0; type < OP_MAX; type++)
+ if (session_cache[type].lock != NULL)
+ (void) pthread_mutex_destroy(session_cache[type].lock);
+ OPENSSL_free(session_cache[type].lock);
+ session_cache[type].lock = NULL;
+ * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
+static int bind_pk11(ENGINE *e)
+ if (!pk11_library_initialized)
+ if (!pk11_library_init(e))
+ if (!ENGINE_set_id(e, engine_pk11_id) ||
+ !ENGINE_set_name(e, engine_pk11_name))
+ if (pk11_have_rsa == CK_TRUE)
+ if (!ENGINE_set_RSA(e, PK11_RSA()) ||
+ !ENGINE_set_load_privkey_function(e, pk11_load_privkey) ||
+ !ENGINE_set_load_pubkey_function(e, pk11_load_pubkey))
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: registered RSA\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ if (!ENGINE_set_RAND(e, &pk11_random))
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: registered random\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ if (!ENGINE_set_init_function(e, pk11_init) ||
+ !ENGINE_set_destroy_function(e, pk11_destroy) ||
+ !ENGINE_set_finish_function(e, pk11_finish) ||
+ !ENGINE_set_ctrl_function(e, pk11_ctrl) ||
+ !ENGINE_set_cmd_defns(e, pk11_cmd_defns))
+ /* Ensure the pk11 error handling is set up */
+ ERR_load_pk11_strings();
+/* Dynamic engine support is disabled at a higher level for Solaris */
+#ifdef ENGINE_DYNAMIC_SUPPORT
+#error "dynamic engine not supported"
+static int bind_helper(ENGINE *e, const char *id)
+ if (id && (strcmp(id, engine_pk11_id) != 0))
+IMPLEMENT_DYNAMIC_CHECK_FN()
+IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
+static ENGINE *engine_pk11(void)
+ ENGINE *ret = ENGINE_new();
+ * Do not use dynamic PKCS#11 library on Solaris due to
+ * security reasons. We will link it in statically.
+ /* Attempt to load PKCS#11 library */
+ pk11_dso = DSO_load(NULL, get_PK11_LIBNAME(), NULL, 0);
+ PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
+ e_pk11 = engine_pk11();
+ * At this point, the pk11 shared library is either dynamically
+ * loaded or statically linked in. So, initialize the pk11
+ * library before calling ENGINE_set_default since the latter
+ * needs cipher and digest algorithm information
+ if (!pk11_library_init(e_pk11))
+#endif /* ENGINE_DYNAMIC_SUPPORT */
+ * These are the static string constants for the DSO file name and
+ * the function symbol names to bind to.
+static const char *PK11_LIBNAME = NULL;
+static const char *get_PK11_LIBNAME(void)
+ return (def_PK11_LIBNAME);
+static void free_PK11_LIBNAME(void)
+ OPENSSL_free((void*)PK11_LIBNAME);
+static long set_PK11_LIBNAME(const char *name)
+ return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
+/* acquire all engine specific mutexes before fork */
+static void pk11_fork_prepare(void)
+ if (!pk11_library_initialized)
+ OPENSSL_assert(pthread_mutex_lock(token_lock) == 0);
+ for (i = 0; i < OP_MAX; i++)
+ OPENSSL_assert(pthread_mutex_lock(session_cache[i].lock) == 0);
+/* release all engine specific mutexes */
+static void pk11_fork_parent(void)
+ if (!pk11_library_initialized)
+ for (i = OP_MAX - 1; i >= 0; i--)
+ OPENSSL_assert(pthread_mutex_unlock(session_cache[i].lock) == 0);
+ UNLOCK_OBJSTORE(OP_RSA);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ * same situation as in parent - we need to unlock all locks to make them
+ * accessible to all threads.
+static void pk11_fork_child(void)
+ if (!pk11_library_initialized)
+ for (i = OP_MAX - 1; i >= 0; i--)
+ OPENSSL_assert(pthread_mutex_unlock(session_cache[i].lock) == 0);
+ UNLOCK_OBJSTORE(OP_RSA);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+/* Initialization function for the pk11 engine */
+static int pk11_init(ENGINE *e)
+ return (pk11_library_init(e));
+static CK_C_INITIALIZE_ARGS pk11_init_args =
+ NULL_PTR, /* CreateMutex */
+ NULL_PTR, /* DestroyMutex */
+ NULL_PTR, /* LockMutex */
+ NULL_PTR, /* UnlockMutex */
+ CKF_OS_LOCKING_OK, /* flags */
+ NULL_PTR, /* pReserved */
+ * Initialization function. Sets up various PKCS#11 library components.
+ * It selects a slot based on predefined critiera. In the process, it also
+ * count how many ciphers and digests to support. Since the cipher and
+ * digest information is needed when setting default engine, this function
+ * needs to be called before calling ENGINE_set_default.
+static int pk11_library_init(ENGINE *e)
+ CK_C_GetFunctionList p;
+#ifndef OPENSSL_SYS_WIN32
+ struct sigaction sigint_act, sigterm_act, sighup_act;
+ * pk11_library_initialized is set to 0 in pk11_finish() which
+ * is called from ENGINE_finish(). However, if there is still
+ * at least one existing functional reference to the engine
+ * (see engine(3) for more information), pk11_finish() is
+ * skipped. For example, this can happen if an application
+ * forgets to clear one cipher context. In case of a fork()
+ * when the application is finishing the engine so that it can
+ * be reinitialized in the child, forgotten functional
+ * reference causes pk11_library_initialized to stay 1. In
+ * that case we need the PID check so that we properly
+ * initialize the engine again.
+ if (pk11_library_initialized)
+ if (pk11_pid == getpid())
+ global_session = CK_INVALID_HANDLE;
+ * free the locks first to prevent memory leak in case
+ * the application calls fork() without finishing the
+ PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
+ /* get the C_GetFunctionList function from the loaded library */
+ p = (CK_C_GetFunctionList)DSO_bind_func(pk11_dso,
+ PK11_GET_FUNCTION_LIST);
+ PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
+ /* get the full function list from the loaded library */
+ PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE, rv);
+#ifndef OPENSSL_SYS_WIN32
+ /* Not all PKCS#11 library are signal safe! */
+ (void) memset(&sigint_act, 0, sizeof(sigint_act));
+ (void) memset(&sigterm_act, 0, sizeof(sigterm_act));
+ (void) memset(&sighup_act, 0, sizeof(sighup_act));
+ (void) sigaction(SIGINT, NULL, &sigint_act);
+ (void) sigaction(SIGTERM, NULL, &sigterm_act);
+ (void) sigaction(SIGHUP, NULL, &sighup_act);
+ rv = pFuncList->C_Initialize((CK_VOID_PTR)&pk11_init_args);
+#ifndef OPENSSL_SYS_WIN32
+ (void) sigaction(SIGINT, &sigint_act, NULL);
+ (void) sigaction(SIGTERM, &sigterm_act, NULL);
+ (void) sigaction(SIGHUP, &sighup_act, NULL);
+ if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
+ PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE, rv);
+ rv = pFuncList->C_GetInfo(&info);
+ PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_GETINFO, rv);
+ if (pk11_choose_slots(&any_slot_found) == 0)
+ * The library we use, set in def_PK11_LIBNAME, may not offer any
+ * slot(s). In that case, we must not proceed but we must not return an
+ * error. The reason is that applications that try to set up the PKCS#11
+ * engine don't exit on error during the engine initialization just
+ * because no slot was present.
+ if (any_slot_found == 0)
+ if (global_session == CK_INVALID_HANDLE)
+ /* Open the global_session for the new process */
+ rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+ NULL_PTR, NULL_PTR, &global_session);
+ PK11err_add_data(PK11_F_LIBRARY_INIT,
+ PK11_R_OPENSESSION, rv);
+ pk11_library_initialized = TRUE;
+ * if initialization of the locks fails pk11_init_all_locks()
+ if (!pk11_init_all_locks())
+ for (i = 0; i < OP_MAX; i++)
+ session_cache[i].head = NULL;
+ * initialize active lists. We only use active lists
+ * for asymmetric ciphers.
+ for (i = 0; i < OP_MAX; i++)
+ if (!pk11_atfork_initialized)
+ if (pthread_atfork(pk11_fork_prepare, pk11_fork_parent,
+ PK11err(PK11_F_LIBRARY_INIT, PK11_R_ATFORK_FAILED);
+ pk11_atfork_initialized = TRUE;
+/* Destructor (complements the "ENGINE_pk11()" constructor) */
+static int pk11_destroy(ENGINE *e)
+ ERR_unload_pk11_strings();
+ memset(pk11_pin, 0, strlen(pk11_pin));
+ OPENSSL_free((void*)pk11_pin);
+ * Termination function to clean up the session, the token, and the pk11
+static int pk11_finish(ENGINE *e)
+ memset(pk11_pin, 0, strlen(pk11_pin));
+ OPENSSL_free((void*)pk11_pin);
+ PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
+ OPENSSL_assert(pFuncList != NULL);
+ if (pk11_free_all_sessions() == 0)
+ /* free all active lists */
+ for (i = 0; i < OP_MAX; i++)
+ pk11_free_active_list(i);
+ pFuncList->C_CloseSession(global_session);
+ global_session = CK_INVALID_HANDLE;
+ * Since we are part of a library (
libcrypto.so), calling this function
+ * may have side-effects.
+ pFuncList->C_Finalize(NULL);
+ if (!DSO_free(pk11_dso))
+ PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
+ pk11_library_initialized = FALSE;
+ * There is no way how to unregister atfork handlers (other than
+ * unloading the library) so we just free the locks. For this reason
+ * the atfork handlers check if the engine is initialized and bail out
+ * immediately if not. This is necessary in case a process finishes
+ * the engine before calling fork().
+/* Standard engine interface function to set the dynamic library path */
+static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
+ int initialized = ((pk11_dso == NULL) ? 0 : 1);
+ PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
+ PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
+ return (set_PK11_LIBNAME((const char *)p));
+ memset(pk11_pin, 0, strlen(pk11_pin));
+ OPENSSL_free((void*)pk11_pin);
+ PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
+ pk11_pin = BUF_strdup(p);
+ PK11err(PK11_F_GET_SESSION, PK11_R_MALLOC_FAILURE);
+ SLOTID = (CK_SLOT_ID)i;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: slot set\n", PK11_DBG);
+ PK11err(PK11_F_CTRL, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
+/* Required function by the engine random interface. It does nothing here */
+static void pk11_rand_cleanup(void)
+static void pk11_rand_add(const void *buf, int num, double add)
+ if ((sp = pk11_get_session(OP_RAND)) == NULL)
+ * Ignore any errors (
e.g. CKR_RANDOM_SEED_NOT_SUPPORTED) since
+ * the calling functions do not care anyway
+ pFuncList->C_SeedRandom(sp->session, (unsigned char *) buf, num);
+ pk11_return_session(sp, OP_RAND);
+static void pk11_rand_seed(const void *buf, int num)
+ pk11_rand_add(buf, num, 0);
+static int pk11_rand_bytes(unsigned char *buf, int num)
+ if ((sp = pk11_get_session(OP_RAND)) == NULL)
+ rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
+ PK11err_add_data(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM, rv);
+ pk11_return_session(sp, OP_RAND);
+ pk11_return_session(sp, OP_RAND);
+/* Required function by the engine random interface. It does nothing here */
+static int pk11_rand_status(void)
+/* Free all BIGNUM structures from PK11_SESSION. */
+static void pk11_free_nums(PK11_SESSION *sp, PK11_OPTYPE optype)
+ if (sp->opdata_rsa_n_num != NULL)
+ BN_free(sp->opdata_rsa_n_num);
+ sp->opdata_rsa_n_num = NULL;
+ if (sp->opdata_rsa_e_num != NULL)
+ BN_free(sp->opdata_rsa_e_num);
+ sp->opdata_rsa_e_num = NULL;
+ if (sp->opdata_rsa_pn_num != NULL)
+ BN_free(sp->opdata_rsa_pn_num);
+ sp->opdata_rsa_pn_num = NULL;
+ if (sp->opdata_rsa_pe_num != NULL)
+ BN_free(sp->opdata_rsa_pe_num);
+ sp->opdata_rsa_pe_num = NULL;
+ if (sp->opdata_rsa_d_num != NULL)
+ BN_free(sp->opdata_rsa_d_num);
+ sp->opdata_rsa_d_num = NULL;
+ * Get new PK11_SESSION structure ready for use. Every process must have
+ * its own freelist of PK11_SESSION structures so handle fork() here
+ * by destroying the old and creating new freelist.
+ * The returned PK11_SESSION structure is disconnected from the freelist.
+pk11_get_session(PK11_OPTYPE optype)
+ PK11_SESSION *sp = NULL, *sp1, *freelist;
+ pthread_mutex_t *freelist_lock = NULL;
+ freelist_lock = session_cache[optype].lock;
+ PK11err(PK11_F_GET_SESSION,
+ PK11_R_INVALID_OPERATION_TYPE);
+ OPENSSL_assert(pthread_mutex_lock(freelist_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ * Will use it to find out if we forked. We cannot use the PID field in
+ * the session structure because we could get a newly allocated session
+ * here, with no PID information.
+ freelist = session_cache[optype].head;
+ * If the free list is empty, allocate new unitialized (filled
+ * with zeroes) PK11_SESSION structure otherwise return first
+ * structure from the freelist.
+ if ((sp = OPENSSL_malloc(sizeof (PK11_SESSION))) == NULL)
+ PK11err(PK11_F_GET_SESSION,
+ PK11_R_MALLOC_FAILURE);
+ (void) memset(sp, 0, sizeof (PK11_SESSION));
+ * It is a new session so it will look like a cache miss to the
+ * code below. So, we must not try to to destroy its members so
+ sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
+ * Check whether we have forked. In that case, we must get rid of all
+ * inherited sessions and start allocating new ones.
+ if (pid != (new_pid = getpid()))
+ * We are a new process and thus need to free any inherited
+ * PK11_SESSION objects aside from the first session (sp) which
+ * is the only PK11_SESSION structure we will reuse (for the
+ while ((sp1 = freelist) != NULL)
+ * NOTE: we do not want to call pk11_free_all_sessions()
+ * here because it would close underlying PKCS#11
+ * sessions and destroy all objects.
+ pk11_free_nums(sp1, optype);
+ /* we have to free the active list as well. */
+ pk11_free_active_list(optype);
+ /* Initialize the process */
+ rv = pFuncList->C_Initialize((CK_VOID_PTR)&pk11_init_args);
+ if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
+ PK11err_add_data(PK11_F_GET_SESSION, PK11_R_INITIALIZE,
+ * Choose slot here since the slot table is different on this
+ * process. If we are here then we must have found at least one
+ * usable slot before so we don't need to check any_slot_found.
+ * See pk11_library_init()'s usage of this function for more
+ if (pk11_choose_slots(NULL) == 0)
+ /* Open the global_session for the new process */
+ rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+ NULL_PTR, NULL_PTR, &global_session);
+ PK11err_add_data(PK11_F_GET_SESSION, PK11_R_OPENSESSION,
+ * It is an inherited session from our parent so it needs
+ if (pk11_setup_session(sp, optype) == 0)
+ if (pk11_token_relogin(sp->session) == 0)
+ * We will keep the session in the cache list and let
+ * the caller cope with the situation.
+ /* It is a new session and needs initialization. */
+ if (pk11_setup_session(sp, optype) == 0)
+ /* set new head for the list of PK11_SESSION objects */
+ session_cache[optype].head = freelist;
+ OPENSSL_assert(pthread_mutex_unlock(freelist_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype)
+ pthread_mutex_t *freelist_lock;
+ PK11_SESSION *freelist;
+ * If this is a session from the parent it will be taken care of and
+ * freed in pk11_get_session() as part of the post-fork clean up the
+ * next time we will ask for a new session.
+ if (sp == NULL || sp->pid != getpid())
+ freelist_lock = session_cache[optype].lock;
+ PK11err(PK11_F_RETURN_SESSION,
+ PK11_R_INVALID_OPERATION_TYPE);
+ OPENSSL_assert(pthread_mutex_lock(freelist_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ freelist = session_cache[optype].head;
+ session_cache[optype].head = sp;
+ OPENSSL_assert(pthread_mutex_unlock(freelist_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+/* Destroy all objects. This function is called when the engine is finished */
+static int pk11_free_all_sessions()
+ (void) pk11_destroy_rsa_key_objects(NULL);
+ * We try to release as much as we can but any error means that we will
+ for (type = 0; type < OP_MAX; type++)
+ if (pk11_free_session_list(type) == 0)
+ * Destroy session structures from the linked list specified. Free as many
+ * sessions as possible but any failure in C_CloseSession() means that we
+ * return an error on return.
+static int pk11_free_session_list(PK11_OPTYPE optype)
+ PK11_SESSION *sp = NULL;
+ PK11_SESSION *freelist = NULL;
+ pid_t mypid = getpid();
+ pthread_mutex_t *freelist_lock;
+ freelist_lock = session_cache[optype].lock;
+ PK11err(PK11_F_FREE_ALL_SESSIONS,
+ PK11_R_INVALID_OPERATION_TYPE);
+ OPENSSL_assert(pthread_mutex_lock(freelist_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ freelist = session_cache[optype].head;
+ while ((sp = freelist) != NULL)
+ if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
+ rv = pFuncList->C_CloseSession(sp->session);
+ PK11err_add_data(PK11_F_FREE_ALL_SESSIONS,
+ PK11_R_CLOSESESSION, rv);
+ pk11_free_nums(sp, optype);
+ OPENSSL_assert(pthread_mutex_unlock(freelist_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype)
+ myslot = pubkey_SLOTID;
+ PK11err(PK11_F_SETUP_SESSION,
+ PK11_R_INVALID_OPERATION_TYPE);
+ sp->session = CK_INVALID_HANDLE;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: myslot=%d optype=%d\n", PK11_DBG, myslot, optype);
+#endif /* DEBUG_SLOT_SELECTION */
+ rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
+ NULL_PTR, NULL_PTR, &sp->session);
+ if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
+ * We are probably a child process so force the
+ * reinitialize of the session
+ pk11_library_initialized = FALSE;
+ if (!pk11_library_init(NULL))
+ rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
+ NULL_PTR, NULL_PTR, &sp->session);
+ PK11err_add_data(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION, rv);
+ sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_pub = NULL;
+ sp->opdata_rsa_n_num = NULL;
+ sp->opdata_rsa_e_num = NULL;
+ sp->opdata_rsa_priv = NULL;
+ sp->opdata_rsa_pn_num = NULL;
+ sp->opdata_rsa_pe_num = NULL;
+ sp->opdata_rsa_d_num = NULL;
+ * We always initialize the session as containing a non-persistent
+ * object. The key load functions set it to persistent if that is so.
+ sp->pub_persistent = CK_FALSE;
+ sp->priv_persistent = CK_FALSE;
+/* Destroy RSA public key from single session. */
+pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
+ if (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE)
+ TRY_OBJ_DESTROY(sp, sp->opdata_rsa_pub_key,
+ ret, uselock, OP_RSA, CK_FALSE);
+ sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_pub = NULL;
+ if (sp->opdata_rsa_n_num != NULL)
+ BN_free(sp->opdata_rsa_n_num);
+ sp->opdata_rsa_n_num = NULL;
+ if (sp->opdata_rsa_e_num != NULL)
+ BN_free(sp->opdata_rsa_e_num);
+ sp->opdata_rsa_e_num = NULL;
+/* Destroy RSA private key from single session. */
+pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
+ if (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE)
+ TRY_OBJ_DESTROY(sp, sp->opdata_rsa_priv_key,
+ ret, uselock, OP_RSA, CK_TRUE);
+ sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
+ sp->opdata_rsa_priv = NULL;
+ if (sp->opdata_rsa_d_num != NULL)
+ BN_free(sp->opdata_rsa_d_num);
+ sp->opdata_rsa_d_num = NULL;
+ * For the RSA key by reference code, public components 'n'/'e'
+ * are the key components we use to check for the cache hit. We
+ * must free those as well.
+ if (sp->opdata_rsa_pn_num != NULL)
+ BN_free(sp->opdata_rsa_pn_num);
+ sp->opdata_rsa_pn_num = NULL;
+ if (sp->opdata_rsa_pe_num != NULL)
+ BN_free(sp->opdata_rsa_pe_num);
+ sp->opdata_rsa_pe_num = NULL;
+ * Destroy RSA key object wrapper. If session is NULL, try to destroy all
+ * objects in the free list.
+pk11_destroy_rsa_key_objects(PK11_SESSION *session)
+ PK11_SESSION *sp = NULL;
+ PK11_SESSION *local_free_session;
+ CK_BBOOL uselock = TRUE;
+ local_free_session = session;
+ OPENSSL_assert(pthread_mutex_lock(session_cache[OP_RSA].lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ local_free_session = session_cache[OP_RSA].head;
+ * go through the list of sessions and delete key objects
+ while ((sp = local_free_session) != NULL)
+ local_free_session = sp->next;
+ * Do not terminate list traversal if one of the
+ * destroy operations fails.
+ if (pk11_destroy_rsa_object_pub(sp, uselock) == 0)
+ if (pk11_destroy_rsa_object_priv(sp, uselock) == 0)
+ OPENSSL_assert(pthread_mutex_unlock(session_cache[OP_RSA].lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh,
+ * We never try to destroy persistent objects which are the objects
+ * stored in the keystore. Also, we always use read-only sessions so
+ * C_DestroyObject() would be returning CKR_SESSION_READ_ONLY here.
+ if (persistent == CK_TRUE)
+ rv = pFuncList->C_DestroyObject(session, oh);
+ PK11err_add_data(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT,
+ * Public key mechanisms optionally supported
+ * The first slot that supports at least one of those mechanisms is chosen as a
+ * The output of this function is a set of global variables indicating which
+ * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
+ * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
+ * variables carry information about which slot was chosen for (a) public key
+ * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
+pk11_choose_slots(int *any_slot_found)
+ CK_SLOT_ID_PTR pSlotList = NULL_PTR;
+ CK_ULONG ulSlotCount = 0;
+ CK_MECHANISM_INFO mech_info;
+ CK_TOKEN_INFO token_info;
+ CK_SLOT_ID best_slot_sofar = 0;
+ CK_BBOOL found_candidate_slot = CK_FALSE;
+ CK_SLOT_ID current_slot = 0;
+ /* let's initialize the output parameter */
+ if (any_slot_found != NULL)
+ /* Get slot list for memory allocation */
+ rv = pFuncList->C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount);
+ PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
+ /* it's not an error if we didn't find any providers */
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: no crypto providers found\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
+ PK11err(PK11_F_CHOOSE_SLOT, PK11_R_MALLOC_FAILURE);
+ /* Get the slot list for processing */
+ rv = pFuncList->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount);
+ PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
+ OPENSSL_free(pSlotList);
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: provider: %s\n", PK11_DBG, def_PK11_LIBNAME);
+ fprintf(stderr, "%s: number of slots: %d\n", PK11_DBG, ulSlotCount);
+ fprintf(stderr, "%s: == checking rand slots ==\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ for (i = 0; i < ulSlotCount; i++)
+ current_slot = pSlotList[i];
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
+#endif /* DEBUG_SLOT_SELECTION */
+ /* Check if slot has random support. */
+ rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
+#ifdef DEBUG_SLOT_SELECTION
+#endif /* DEBUG_SLOT_SELECTION */
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: this token has CKF_RNG flag\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ pk11_have_random = CK_TRUE;
+ rand_SLOTID = current_slot;
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: == checking pubkey slots ==\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ pubkey_SLOTID = pSlotList[0];
+ for (i = 0; i < ulSlotCount; i++)
+ CK_BBOOL slot_has_rsa = CK_FALSE;
+ current_slot = pSlotList[i];
+#ifdef DEBUG_SLOT_SELECTION
+ fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
+#endif /* DEBUG_SLOT_SELECTION */
+ rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
+#ifdef DEBUG_SLOT_SELECTION
+#endif /* DEBUG_SLOT_SELECTION */
+ * Check if this slot is capable of signing with CKM_RSA_PKCS.
+ rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS,
+ slot_has_rsa = CK_TRUE;
+ if (!found_candidate_slot && slot_has_rsa)
+#ifdef DEBUG_SLOT_SELECTION
+ "%s: potential slot: %d\n", PK11_DBG, current_slot);
+#endif /* DEBUG_SLOT_SELECTION */
+ best_slot_sofar = current_slot;
+ pk11_have_rsa = slot_has_rsa;
+ found_candidate_slot = CK_TRUE;
+ * Cache the flags for later use. We might
+ * need those if RSA keys by reference feature
+#ifdef DEBUG_SLOT_SELECTION
+ "%s: setting found_candidate_slot to CK_TRUE\n",
+ "%s: best so far slot: %d\n", PK11_DBG,
+ fprintf(stderr, "%s: pubkey flags changed to "
+ "%lu.\n", PK11_DBG, pubkey_token_flags);
+ "%s: no rsa\n", PK11_DBG);
+#endif /* DEBUG_SLOT_SELECTION */
+ if (found_candidate_slot == CK_TRUE)
+ pubkey_SLOTID = best_slot_sofar;
+ /*SLOTID = pSlotList[0];*/
+#ifdef DEBUG_SLOT_SELECTION
+ "%s: chosen pubkey slot: %d\n", PK11_DBG, pubkey_SLOTID);
+ "%s: chosen rand slot: %d\n", PK11_DBG, rand_SLOTID);
+ "%s: pk11_have_rsa %d\n", PK11_DBG, pk11_have_rsa);
+ "%s: pk11_have_random %d\n", PK11_DBG, pk11_have_random);
+#endif /* DEBUG_SLOT_SELECTION */
+ OPENSSL_free(pSlotList);
+ if (any_slot_found != NULL)
+#endif /* OPENSSL_NO_HW_PK11SO */
+#endif /* OPENSSL_NO_HW_PK11 */
+#endif /* OPENSSL_NO_HW */
+#define token_lock pk11so_token_lock
+#define find_lock pk11so_find_lock
+#define active_list pk11so_active_list
+#define pubkey_token_flags pk11so_pubkey_token_flags
+#define pubkey_SLOTID pk11so_pubkey_SLOTID
+#define ERR_pk11_error ERR_pk11so_error
+#define PK11err_add_data PK11SOerr_add_data
+#define pk11_get_session pk11so_get_session
+#define pk11_return_session pk11so_return_session
+#define pk11_active_add pk11so_active_add
+#define pk11_active_delete pk11so_active_delete
+#define pk11_active_remove pk11so_active_remove
+#define pk11_free_active_list pk11so_free_active_list
+#define pk11_destroy_rsa_key_objects pk11so_destroy_rsa_key_objects
+#define pk11_destroy_rsa_object_pub pk11so_destroy_rsa_object_pub
+#define pk11_destroy_rsa_object_priv pk11so_destroy_rsa_object_priv
+#define pk11_load_privkey pk11so_load_privkey
+#define pk11_load_pubkey pk11so_load_pubkey
+#define PK11_RSA PK11SO_RSA
+#define pk11_destroy_dsa_key_objects pk11so_destroy_dsa_key_objects
+#define pk11_destroy_dsa_object_pub pk11so_destroy_dsa_object_pub
+#define pk11_destroy_dsa_object_priv pk11so_destroy_dsa_object_priv
+#define PK11_DSA PK11SO_DSA
+#define pk11_destroy_dh_key_objects pk11so_destroy_dh_key_objects
+#define pk11_destroy_dh_object pk11so_destroy_dh_object
+#define PK11_DH PK11SO_DH
+#define pk11_token_relogin pk11so_token_relogin
+#define pFuncList pk11so_pFuncList
+#define pk11_pin pk11so_pin
+#define ENGINE_load_pk11 ENGINE_load_pk11so
+ * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
+ * This product includes software developed by the OpenSSL Project for
+ * ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project. All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation
and/or other materials provided with the
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * licensing@OpenSSL.org.
+ * 5. Products derived from this software may not be called "OpenSSL"
+ * nor may "OpenSSL" appear in their names without prior written
+ * permission of the OpenSSL Project.
+ * 6. Redistributions of any form whatsoever must retain the following
+ * "This product includes software developed by the OpenSSL Project
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com). This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+/* Modified to keep only RNG and RSA Sign */
+#ifdef OPENSSL_SYS_WIN32
+#define HAVE_GETPASSPHRASE
+static char *getpassphrase(const char *prompt);
+#define CK_DEFINE_FUNCTION(returnType, name) \
+ returnType __declspec(dllexport) name
+#define CK_DECLARE_FUNCTION(returnType, name) \
+ returnType __declspec(dllimport) name
+#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ returnType __declspec(dllimport) (* name)
+#ifndef OPENSSL_NO_HW_PK11
+#ifndef OPENSSL_NO_HW_PK11SO
+#ifdef OPENSSL_SYS_WIN32
+#pragma pack(push, cryptoki, 1)
+#pragma pack(pop, cryptoki)
+static CK_BBOOL pk11_login_done = CK_FALSE;
+extern CK_SLOT_ID pubkey_SLOTID;
+extern pthread_mutex_t *token_lock;
+#if !(defined(HAVE_GETPASSPHRASE) || (defined (__SVR4) && defined (__sun)))
+#define getpassphrase(x) getpass(x)
+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
+ unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
+EVP_PKEY *pk11_load_privkey(ENGINE*, const char *privkey_file,
+ UI_METHOD *ui_method, void *callback_data);
+EVP_PKEY *pk11_load_pubkey(ENGINE*, const char *pubkey_file,
+ UI_METHOD *ui_method, void *callback_data);
+static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA* rsa, RSA** key_ptr,
+ BIGNUM **rsa_n_num, BIGNUM **rsa_e_num, CK_SESSION_HANDLE session);
+static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA* rsa, RSA** key_ptr,
+ BIGNUM **rsa_d_num, BIGNUM **rsa_n_num, BIGNUM **rsa_e_num,
+ CK_SESSION_HANDLE session);
+static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa);
+static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa);
+static int find_one_object(PK11_OPTYPE op, CK_SESSION_HANDLE s,
+ CK_ATTRIBUTE_PTR ptempl, CK_ULONG nattr, CK_OBJECT_HANDLE_PTR pkey);
+static int init_template_value(BIGNUM *bn, CK_VOID_PTR *pValue,
+static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn);
+static int pk11_token_login(CK_SESSION_HANDLE session, CK_BBOOL *login_done,
+/* Read mode string to be used for fopen() */
+static char *read_mode_flags = "rF";
+static char *read_mode_flags = "r";
+ * manipulation. If active list operation fails, unlock (if locked), set error
+ * variable and jump to the specified label.
+#define KEY_HANDLE_REFHOLD(key_handle, alg_type, unlock, var, label) \
+ if (pk11_active_add(key_handle, alg_type) < 0) \
+ UNLOCK_OBJSTORE(alg_type); \
+ * Find active list entry according to object handle and return pointer to the
+ * entry otherwise return NULL.
+ * This function presumes it is called with lock protecting the active list
+static PK11_active *pk11_active_find(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
+ for (entry = active_list[type]; entry != NULL; entry = entry->next)
+ * Search for an entry in the active list using PKCS#11 object handle as a
+ * search key and return refcnt of the
found/created entry or -1 in case of
+ * This function presumes it is called with lock protecting the active list
+pk11_active_add(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
+ PK11_active *entry = NULL;
+ if (h == CK_INVALID_HANDLE)
+ PK11err(PK11_F_ACTIVE_ADD, PK11_R_INVALID_HANDLE);
+ /* search for entry in the active list */
+ if ((entry = pk11_active_find(h, type)) != NULL)
+ /* not found, create new entry and add it to the list */
+ entry = OPENSSL_malloc(sizeof (PK11_active));
+ PK11err(PK11_F_ACTIVE_ADD, PK11_R_MALLOC_FAILURE);
+ /* connect the newly created entry to the list */
+ if (active_list[type] == NULL)
+ active_list[type] = entry;
+ else /* make the entry first in the list */
+ entry->next = active_list[type];
+ active_list[type]->prev = entry;
+ active_list[type] = entry;
+ return (entry->refcnt);
+ * Remove active list entry from the list and free it.
+ * This function presumes it is called with lock protecting the active list
+pk11_active_remove(PK11_active *entry, PK11_OPTYPE type)
+ PK11_active *prev_entry;
+ /* remove the entry from the list and free it */
+ if ((prev_entry = entry->prev) != NULL)
+ prev_entry->next = entry->next;
+ if (entry->next != NULL)
+ entry->next->prev = prev_entry;
+ active_list[type] = entry->next;
+ /* we were the first but not the only one */
+ if (entry->next != NULL)
+ entry->next->prev = NULL;
+ entry->h = CK_INVALID_HANDLE;
+/* Free all entries from the active list. */
+pk11_free_active_list(PK11_OPTYPE type)
+ /* only for asymmetric types since only they have C_Find* locks. */
+ /* see find_lock array definition for more info on object locking */
+ while ((entry = active_list[type]) != NULL)
+ pk11_active_remove(entry, type);
+ * Search for active list entry associated with given PKCS#11 object handle,
+ * decrement its refcnt and if it drops to 0, disconnect the entry and free it.
+ * Return 1 if the PKCS#11 object associated with the entry has no references,
+ * return 0 if there is at least one reference, -1 on error.
+ * This function presumes it is called with lock protecting the active list
+pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
+ PK11_active *entry = NULL;
+ if ((entry = pk11_active_find(h, type)) == NULL)
+ PK11err(PK11_F_ACTIVE_DELETE, PK11_R_INVALID_HANDLE);
+ OPENSSL_assert(entry->refcnt > 0);
+ if (entry->refcnt == 0)
+ pk11_active_remove(entry, type);
+/* Our internal RSA_METHOD that we provide pointers to */
+static RSA_METHOD pk11_rsa;
+ rsa = RSA_PKCS1_SSLeay();
+ memcpy(&pk11_rsa, rsa, sizeof(*rsa));
+/* Size of an SSL signature: MD5+SHA1 */
+#define SSL_SIG_LENGTH 36
+static CK_BBOOL mytrue = TRUE;
+static CK_BBOOL myfalse = FALSE;
+ * Standard engine interface function. Majority codes here are from
+ *
rsa/rsa_sign.c. We replaced the decrypt function call by C_Sign of PKCS#11.
+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
+ unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
+ unsigned char *p, *s = NULL;
+ ASN1_OCTET_STRING digest;
+ CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
+ CK_MECHANISM *p_mech = &mech_rsa;
+ CK_OBJECT_HANDLE h_priv_key;
+ PK11_SESSION *sp = NULL;
+ unsigned long ulsiglen;
+ /* Encode the digest */
+ /* Special case: SSL signature, just check the length */
+ if (type == NID_md5_sha1)
+ if (m_len != SSL_SIG_LENGTH)
+ PK11err(PK11_F_RSA_SIGN,
+ PK11_R_INVALID_MESSAGE_LENGTH);
+ s = (unsigned char *)m;
+ PK11err(PK11_F_RSA_SIGN,
+ PK11_R_UNKNOWN_ALGORITHM_TYPE);
+ PK11err(PK11_F_RSA_SIGN,
+ PK11_R_UNKNOWN_ASN1_OBJECT_ID);
+ i = i2d_X509_SIG(&sig, NULL);
+ if ((i - RSA_PKCS1_PADDING) > j)
+ PK11err(PK11_F_RSA_SIGN, PK11_R_DIGEST_TOO_BIG);
+ if (type != NID_md5_sha1)
+ s = (unsigned char *)OPENSSL_malloc((unsigned int)(j + 1));
+ PK11err(PK11_F_RSA_SIGN, PK11_R_MALLOC_FAILURE);
+ (void) i2d_X509_SIG(&sig, &p);
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ (void) check_new_rsa_key_priv(sp, rsa);
+ h_priv_key = sp->opdata_rsa_priv_key;
+ if (h_priv_key == CK_INVALID_HANDLE)
+ h_priv_key = sp->opdata_rsa_priv_key =
+ pk11_get_private_rsa_key((RSA *)rsa,
+ &sp->opdata_rsa_priv, &sp->opdata_rsa_d_num,
+ &sp->opdata_rsa_pn_num, &sp->opdata_rsa_pe_num,
+ if (h_priv_key != CK_INVALID_HANDLE)
+ rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
+ PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGNINIT, rv);
+ rv = pFuncList->C_Sign(sp->session, s, i, sigret,
+ (CK_ULONG_PTR) &ulsiglen);
+ PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGN, rv);
+ if ((type != NID_md5_sha1) && (s != NULL))
+ (void) memset(s, 0, (unsigned int)(j + 1));
+ pk11_return_session(sp, OP_RSA);
+static int hndidx_rsa = -1;
+ * Load RSA private key from a file or get its PKCS#11 handle if stored in the
+EVP_PKEY *pk11_load_privkey(ENGINE *e, const char *privkey_file,
+ UI_METHOD *ui_method, void *callback_data)
+ CK_OBJECT_HANDLE h_priv_key = CK_INVALID_HANDLE;
+ /* Anything else below is needed for the key by reference extension. */
+ CK_BBOOL is_token = TRUE;
+ CK_BBOOL rollback = FALSE;
+ CK_BYTE attr_data[2][MAXATTR];
+ CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY;
+ CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE; /* key in keystore */
+ /* we look for private keys only */
+ CK_ATTRIBUTE search_templ[] =
+ {CKA_TOKEN, &is_token, sizeof(is_token)},
+ {CKA_CLASS, &key_class, sizeof(key_class)},
+ * These public attributes are needed to initialize the OpenSSL RSA
+ * structure with something we can use to look up the key. Note that we
+ * never ask for private components.
+ CK_ATTRIBUTE get_templ[] =
+ {CKA_MODULUS, (void *)attr_data[0], MAXATTR}, /* n */
+ {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], MAXATTR}, /* e */
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
+ if (strstr(privkey_file, "pkcs11:") == privkey_file)
+ search_templ[2].pValue = strstr(privkey_file, ":") + 1;
+ search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
+ if (pk11_token_login(sp->session, &pk11_login_done,
+ /* see find_lock array definition
+ for more info on object locking */
+ * Now let's try to find the key in the token. It is a failure
+ if (find_one_object(OP_RSA, sp->session, search_templ, 3,
+ UNLOCK_OBJSTORE(OP_RSA);
+ hndidx_rsa = RSA_get_ex_new_index(0,
+ "pkcs11 RSA HSM key handle",
+ * We might have a cache hit which we could confirm
+ * according to the 'n'/'e' params, RSA public pointer
+ * as NULL, and non-NULL RSA private pointer. However,
+ * it is easier just to recreate everything. We expect
+ * the keys to be loaded once and used many times. We
+ * do not check the return value because even in case
+ * of failure the sp structure will have both key
+ * pointer and object handle cleaned and
+ * pk11_destroy_object() reports the failure to the
+ * OpenSSL error message buffer.
+ (void) pk11_destroy_rsa_object_priv(sp, FALSE);
+ sp->opdata_rsa_priv_key = ks_key;
+ /* This object shall not be deleted on a cache miss. */
+ sp->priv_persistent = CK_TRUE;
+ * Cache the RSA private structure pointer. We do not
+ * use it now for key-by-ref keys but let's do it for
+ if ((rsa = sp->opdata_rsa_priv = RSA_new_method(e)) == NULL)
+ UNLOCK_OBJSTORE(OP_RSA);
+ * Now we have to initialize an OpenSSL RSA structure,
+ * everything else is 0 or NULL.
+ rsa->flags = RSA_FLAG_SIGN_VER | RSA_FLAG_EXT_PKEY;
+ RSA_set_ex_data(rsa, hndidx_rsa, (void *) ks_key);
+ if ((rv = pFuncList->C_GetAttributeValue(sp->session, ks_key,
+ get_templ, 2)) != CKR_OK)
+ UNLOCK_OBJSTORE(OP_RSA);
+ PK11err_add_data(PK11_F_LOAD_PRIVKEY,
+ PK11_R_GETATTRIBUTVALUE, rv);
+ * We do not use pk11_get_private_rsa_key() here so we
+ * must take care of handle management ourselves.
+ KEY_HANDLE_REFHOLD(ks_key, OP_RSA, TRUE, rollback, err);
+ * Those are the sensitive components we do not want to export
+ * from the token at all: rsa->(d|p|q|dmp1|dmq1|iqmp).
+ attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
+ attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
+ * Must have 'n'/'e' components in the session structure as
+ * well. They serve as a public look-up key for the private key
+ attr_to_BN(&get_templ[0], attr_data[0],
+ &sp->opdata_rsa_pn_num);
+ attr_to_BN(&get_templ[1], attr_data[1],
+ &sp->opdata_rsa_pe_num);
+ UNLOCK_OBJSTORE(OP_RSA);
+ if ((pkey = EVP_PKEY_new()) == NULL)
+ if (EVP_PKEY_assign_RSA(pkey, rsa) == 0)
+ else if ((privkey = fopen(privkey_file, read_mode_flags)) != NULL)
+ pkey = PEM_read_PrivateKey(privkey, NULL, NULL, NULL);
+ (void) fclose(privkey);
+ rsa = EVP_PKEY_get1_RSA(pkey);
+ * This will always destroy the RSA
+ * object since we have a new RSA
+ (void) check_new_rsa_key_priv(sp, rsa);
+ sp->priv_persistent = CK_FALSE;
+ h_priv_key = sp->opdata_rsa_priv_key =
+ pk11_get_private_rsa_key(rsa,
+ &sp->opdata_rsa_pn_num,
+ &sp->opdata_rsa_pe_num, sp->session);
+ if (h_priv_key == CK_INVALID_HANDLE)
+ pk11_return_session(sp, OP_RSA);
+ pk11_return_session(sp, OP_RSA);
+ * Load RSA public key from a file or get its PKCS#11 handle if stored in the
+EVP_PKEY *pk11_load_pubkey(ENGINE *e, const char *pubkey_file,
+ UI_METHOD *ui_method, void *callback_data)
+ CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
+ /* Anything else below is needed for the key by reference extension. */
+ CK_BBOOL is_token = TRUE;
+ CK_BYTE attr_data[2][MAXATTR];
+ CK_OBJECT_CLASS key_class = CKO_PUBLIC_KEY;
+ CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE; /* key in keystore */
+ /* we look for public keys only */
+ CK_ATTRIBUTE search_templ[] =
+ {CKA_TOKEN, &is_token, sizeof(is_token)},
+ {CKA_CLASS, &key_class, sizeof(key_class)},
+ * These public attributes are needed to initialize OpenSSL RSA
+ * structure with something we can use to look up the key.
+ CK_ATTRIBUTE get_templ[] =
+ {CKA_MODULUS, (void *)attr_data[0], MAXATTR}, /* n */
+ {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], MAXATTR}, /* e */
+ if ((sp = pk11_get_session(OP_RSA)) == NULL)
+ * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
+ if (strstr(pubkey_file, "pkcs11:") == pubkey_file)
+ search_templ[2].pValue = strstr(pubkey_file, ":") + 1;
+ search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
+ if (pk11_token_login(sp->session, &pk11_login_done,
+ /* see find_lock array definition
+ for more info on object locking */
+ * Now let's try to find the key in the token. It is a failure
+ if (find_one_object(OP_RSA, sp->session, search_templ, 3,
+ UNLOCK_OBJSTORE(OP_RSA);
+ * We load a new public key so we will create a new RSA
+ * structure. No cache hit is possible.
+ (void) pk11_destroy_rsa_object_pub(sp, FALSE);
+ sp->opdata_rsa_pub_key = ks_key;
+ /* This object shall not be deleted on a cache miss. */
+ sp->pub_persistent = CK_TRUE;
+ * Cache the RSA public structure pointer.
+ if ((rsa = sp->opdata_rsa_pub = RSA_new_method(e)) == NULL)
+ UNLOCK_OBJSTORE(OP_RSA);
+ * Now we have to initialize an OpenSSL RSA structure,
+ * everything else is 0 or NULL.
+ rsa->flags = RSA_FLAG_SIGN_VER;
+ if ((rv = pFuncList->C_GetAttributeValue(sp->session, ks_key,
+ get_templ, 2)) != CKR_OK)
+ UNLOCK_OBJSTORE(OP_RSA);
+ PK11err_add_data(PK11_F_LOAD_PUBKEY,
+ PK11_R_GETATTRIBUTVALUE, rv);
+ attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
+ attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
+ UNLOCK_OBJSTORE(OP_RSA);
+ if ((pkey = EVP_PKEY_new()) == NULL)
+ if (EVP_PKEY_assign_RSA(pkey, rsa) == 0)
+ * Create a session object from it so that when calling
+ * pk11_get_public_rsa_key() the next time, we can find it. The
+ * reason why we do that is that we cannot tell from the RSA
+ * structure (OpenSSL RSA structure does not have any room for
+ * additional data used by the engine, for example) if it bears
+ * a public key stored in the keystore or not so it's better if
+ * we always have a session key. Note that this is different
+ * from what we do for the private keystore objects but in that
+ * case, we can tell from the RSA structure that the keystore
+ * object is in play - the 'd' component is NULL in that case.
+ h_pub_key = sp->opdata_rsa_pub_key =
+ pk11_get_public_rsa_key(rsa,
+ &sp->opdata_rsa_pub, &sp->opdata_rsa_n_num,
+ &sp->opdata_rsa_e_num, sp->session);
+ if (h_pub_key == CK_INVALID_HANDLE)
+ else if ((pubkey = fopen(pubkey_file, read_mode_flags)) != NULL)
+ pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
+ rsa = EVP_PKEY_get1_RSA(pkey);
+ * This will always destroy the RSA
+ * object since we have a new RSA
+ (void) check_new_rsa_key_pub(sp, rsa);
+ sp->pub_persistent = CK_FALSE;
+ h_pub_key = sp->opdata_rsa_pub_key =
+ pk11_get_public_rsa_key(rsa,
+ &sp->opdata_rsa_pub, &sp->opdata_rsa_n_num,
+ &sp->opdata_rsa_e_num, sp->session);
+ if (h_pub_key == CK_INVALID_HANDLE)
+ pk11_return_session(sp, OP_RSA);
+ pk11_return_session(sp, OP_RSA);
+ * Create a public key object in a session from a given rsa structure.
+ * The *rsa_n_num and *rsa_e_num pointers are non-NULL for RSA public keys.
+static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA *rsa,
+ RSA **key_ptr, BIGNUM **rsa_n_num, BIGNUM **rsa_e_num,
+ CK_SESSION_HANDLE session)
+ CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+ CK_OBJECT_CLASS o_key = CKO_PUBLIC_KEY;
+ CK_KEY_TYPE k_type = CKK_RSA;
+ CK_ULONG ul_key_attr_count = 8;
+ CK_BBOOL rollback = FALSE;
+ CK_ATTRIBUTE a_key_template[] =
+ {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
+ {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
+ {CKA_TOKEN, &myfalse, sizeof (myfalse)},
+ {CKA_ENCRYPT, &mytrue, sizeof (mytrue)},
+ {CKA_VERIFY, &mytrue, sizeof (mytrue)},
+ {CKA_VERIFY_RECOVER, &mytrue, sizeof (mytrue)},
+ {CKA_MODULUS, (void *)NULL, 0},
+ {CKA_PUBLIC_EXPONENT, (void *)NULL, 0}
+ a_key_template[0].pValue = &o_key;
+ a_key_template[1].pValue = &k_type;
+ a_key_template[6].ulValueLen = BN_num_bytes(rsa->n);
+ a_key_template[6].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+ (size_t)a_key_template[6].ulValueLen);
+ if (a_key_template[6].pValue == NULL)
+ PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ BN_bn2bin(rsa->n, a_key_template[6].pValue);
+ a_key_template[7].ulValueLen = BN_num_bytes(rsa->e);
+ a_key_template[7].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+ (size_t)a_key_template[7].ulValueLen);
+ if (a_key_template[7].pValue == NULL)
+ PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ BN_bn2bin(rsa->e, a_key_template[7].pValue);
+ /* see find_lock array definition for more info on object locking */
+ rv = pFuncList->C_FindObjectsInit(session, a_key_template,
+ PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
+ PK11_R_FINDOBJECTSINIT, rv);
+ rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+ (void) pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
+ PK11_R_FINDOBJECTS, rv);
+ rv = pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
+ PK11_R_FINDOBJECTSFINAL, rv);
+ rv = pFuncList->C_CreateObject(session,
+ a_key_template, ul_key_attr_count, &h_key);
+ PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
+ PK11_R_CREATEOBJECT, rv);
+ if ((*rsa_n_num = BN_dup(rsa->n)) == NULL)
+ PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ if ((*rsa_e_num = BN_dup(rsa->e)) == NULL)
+ PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ /* LINTED: E_CONSTANT_CONDITION */
+ KEY_HANDLE_REFHOLD(h_key, OP_RSA, FALSE, rollback, err);
+ * We do not care about the return value from C_DestroyObject()
+ * since we are doing rollback.
+ (void) pFuncList->C_DestroyObject(session, h_key);
+ h_key = CK_INVALID_HANDLE;
+ UNLOCK_OBJSTORE(OP_RSA);
+ for (i = 6; i <= 7; i++)
+ if (a_key_template[i].pValue != NULL)
+ OPENSSL_free(a_key_template[i].pValue);
+ a_key_template[i].pValue = NULL;
+ * Create a private key object in the session from a given rsa structure.
+ * The *rsa_d_num pointer is non-NULL for RSA private keys.
+pk11_get_private_rsa_key(RSA *rsa, RSA **key_ptr, BIGNUM **rsa_d_num,
+ BIGNUM **rsa_n_num, BIGNUM **rsa_e_num, CK_SESSION_HANDLE session)
+ CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+ CK_OBJECT_CLASS o_key = CKO_PRIVATE_KEY;
+ CK_KEY_TYPE k_type = CKK_RSA;
+ CK_ULONG ul_key_attr_count = 14;
+ CK_BBOOL rollback = FALSE;
+ /* Both CKA_TOKEN and CKA_SENSITIVE have to be FALSE for session keys */
+ CK_ATTRIBUTE a_key_template[] =
+ {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
+ {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
+ {CKA_TOKEN, &myfalse, sizeof (myfalse)},
+ {CKA_SENSITIVE, &myfalse, sizeof (myfalse)},
+ {CKA_DECRYPT, &mytrue, sizeof (mytrue)},
+ {CKA_SIGN, &mytrue, sizeof (mytrue)},
+ {CKA_MODULUS, (void *)NULL, 0},
+ {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
+ {CKA_PRIVATE_EXPONENT, (void *)NULL, 0},
+ {CKA_PRIME_1, (void *)NULL, 0},
+ {CKA_PRIME_2, (void *)NULL, 0},
+ {CKA_EXPONENT_1, (void *)NULL, 0},
+ {CKA_EXPONENT_2, (void *)NULL, 0},
+ {CKA_COEFFICIENT, (void *)NULL, 0},
+ if ((rsa->flags & RSA_FLAG_EXT_PKEY) != 0) {
+ h_key = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, hndidx_rsa);
+ a_key_template[0].pValue = &o_key;
+ a_key_template[1].pValue = &k_type;
+ /* Put the private key components into the template */
+ if (init_template_value(rsa->n, &a_key_template[6].pValue,
+ &a_key_template[6].ulValueLen) == 0 ||
+ init_template_value(rsa->e, &a_key_template[7].pValue,
+ &a_key_template[7].ulValueLen) == 0 ||
+ init_template_value(rsa->d, &a_key_template[8].pValue,
+ &a_key_template[8].ulValueLen) == 0 ||
+ init_template_value(rsa->p, &a_key_template[9].pValue,
+ &a_key_template[9].ulValueLen) == 0 ||
+ init_template_value(rsa->q, &a_key_template[10].pValue,
+ &a_key_template[10].ulValueLen) == 0 ||
+ init_template_value(rsa->dmp1, &a_key_template[11].pValue,
+ &a_key_template[11].ulValueLen) == 0 ||
+ init_template_value(rsa->dmq1, &a_key_template[12].pValue,
+ &a_key_template[12].ulValueLen) == 0 ||
+ init_template_value(rsa->iqmp, &a_key_template[13].pValue,
+ &a_key_template[13].ulValueLen) == 0)
+ PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ /* see find_lock array definition for more info on object locking */
+ * We are getting the private key but the private 'd'
+ * component is NULL. That means this is key by reference RSA
+ * key. In that case, we can use only public components for
+ * searching for the private key handle.
+ * We will perform the search in the token, not in the existing
+ a_key_template[2].pValue = &mytrue;
+ rv = pFuncList->C_FindObjectsInit(session, a_key_template,
+ PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_FINDOBJECTSINIT, rv);
+ rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+ (void) pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_FINDOBJECTS, rv);
+ rv = pFuncList->C_FindObjectsFinal(session);
+ PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_FINDOBJECTSFINAL, rv);
+ * We have an RSA structure with 'n'/'e' components
+ * only so we tried to find the private key in the
+ * keystore. If it was really a token key we have a
+ * problem. Note that for other key types we just
+ * create a new session key using the private
+ * components from the RSA structure.
+ PK11err(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_PRIV_KEY_NOT_FOUND);
+ rv = pFuncList->C_CreateObject(session,
+ a_key_template, ul_key_attr_count, &h_key);
+ PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
+ PK11_R_CREATEOBJECT, rv);
+ * When RSA keys by reference code is used, we never
+ * extract private components from the keystore. In
+ * that case 'd' was set to NULL and we expect the
+ * application to properly cope with that. It is
+ * documented in openssl(5). In general, if keys by
+ * reference are used we expect it to be used
+ * exclusively using the high level API and then there
+ * is no problem. If the application expects the
+ * private components to be read from the keystore
+ * then that is not a supported way of usage.
+ if (rsa->d != NULL && (*rsa_d_num = BN_dup(rsa->d)) == NULL)
+ PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
+ * For the key by reference code, we need public components as well
+ * since 'd' component is always NULL. For that reason, we always cache
+ * 'n'/'e' components as well.
+ *rsa_n_num = BN_dup(rsa->n);
+ *rsa_e_num = BN_dup(rsa->e);
+ /* LINTED: E_CONSTANT_CONDITION */
+ KEY_HANDLE_REFHOLD(h_key, OP_RSA, FALSE, rollback, err);
+ * We do not care about the return value from C_DestroyObject()
+ * since we are doing rollback.
+ (rsa->flags & RSA_FLAG_EXT_PKEY) == 0)
+ (void) pFuncList->C_DestroyObject(session, h_key);
+ h_key = CK_INVALID_HANDLE;
+ UNLOCK_OBJSTORE(OP_RSA);
+ * 6 to 13 entries in the key template are key components.
+ * They need to be freed upon exit or error.
+ for (i = 6; i <= 13; i++)
+ if (a_key_template[i].pValue != NULL)
+ (void) memset(a_key_template[i].pValue, 0,
+ a_key_template[i].ulValueLen);
+ OPENSSL_free(a_key_template[i].pValue);
+ a_key_template[i].pValue = NULL;
+ * Check for cache miss and clean the object pointer and handle
+ * in such case. Return 1 for cache hit, 0 for cache miss.
+static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa)
+ * Provide protection against RSA structure reuse by making the
+ * check for cache hit stronger. Only public components of RSA
+ * key matter here so it is sufficient to compare them with values
+ * cached in PK11_SESSION structure.
+ * We must check the handle as well since with key by reference, public
+ * components 'n'/'e' are cached in private keys as well. That means we
+ * could have a cache hit in a private key when looking for a public
+ * key. That would not work, you cannot have one PKCS#11 object for
+ * both data signing and verifying.
+ if ((sp->opdata_rsa_pub != rsa) ||
+ (BN_cmp(sp->opdata_rsa_n_num, rsa->n) != 0) ||
+ (BN_cmp(sp->opdata_rsa_e_num, rsa->e) != 0) ||
+ (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE))
+ * We do not check the return value because even in case of
+ * failure the sp structure will have both key pointer
+ * and object handle cleaned and pk11_destroy_object()
+ * reports the failure to the OpenSSL error message buffer.
+ (void) pk11_destroy_rsa_object_pub(sp, TRUE);
+ * Check for cache miss and clean the object pointer and handle
+ * in such case. Return 1 for cache hit, 0 for cache miss.
+static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa)
+ * Provide protection against RSA structure reuse by making
+ * the check for cache hit stronger. Comparing public exponent
+ * of RSA key with value cached in PK11_SESSION structure
+ * should be sufficient. Note that we want to compare the
+ * public component since with the keys by reference
+ * mechanism, private components are not in the RSA
+ * structure. Also, see check_new_rsa_key_pub() about why we
+ * compare the handle as well.
+ if ((sp->opdata_rsa_priv != rsa) ||
+ (BN_cmp(sp->opdata_rsa_pn_num, rsa->n) != 0) ||
+ (BN_cmp(sp->opdata_rsa_pe_num, rsa->e) != 0) ||
+ (sp->opdata_rsa_pn_num == NULL) ||
+ (sp->opdata_rsa_pe_num == NULL) ||
+ (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE))
+ * We do not check the return value because even in case of
+ * failure the sp structure will have both key pointer
+ * and object handle cleaned and pk11_destroy_object()
+ * reports the failure to the OpenSSL error message buffer.
+ (void) pk11_destroy_rsa_object_priv(sp, TRUE);
+ * Local function to simplify key template population
+ * Return 0 -- error, 1 -- no error
+init_template_value(BIGNUM *bn, CK_VOID_PTR *p_value,
+ CK_ULONG *ul_value_len)
+ * This function can be used on non-initialized BIGNUMs. It is
+ * easier to check that here than individually in the callers.
+ len = BN_num_bytes(bn);
+ if (bn == NULL || len == 0)
+ *p_value = (CK_VOID_PTR)OPENSSL_malloc((size_t)*ul_value_len);
+ BN_bn2bin(bn, *p_value);
+attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn)
+ if (attr->ulValueLen > 0)
+ *bn = BN_bin2bn(attr_data, attr->ulValueLen, NULL);
+ * Find one object in the token. It is an error if we can not find the
+ * object or if we find more objects based on the template we got.
+ * Assume object store locked.
+ * 0 no object or more than 1 object found
+find_one_object(PK11_OPTYPE op, CK_SESSION_HANDLE s,
+ CK_ATTRIBUTE_PTR ptempl, CK_ULONG nattr, CK_OBJECT_HANDLE_PTR pkey)
+ if ((rv = pFuncList->C_FindObjectsInit(s, ptempl, nattr)) != CKR_OK)
+ PK11err_add_data(PK11_F_FIND_ONE_OBJECT,
+ PK11_R_FINDOBJECTSINIT, rv);
+ rv = pFuncList->C_FindObjects(s, pkey, 1, &objcnt);
+ (void) pFuncList->C_FindObjectsFinal(s);
+ PK11err_add_data(PK11_F_FIND_ONE_OBJECT, PK11_R_FINDOBJECTS,
+ (void) pFuncList->C_FindObjectsFinal(s);
+ PK11err(PK11_F_FIND_ONE_OBJECT,
+ PK11_R_MORE_THAN_ONE_OBJECT_FOUND);
+ PK11err(PK11_F_FIND_ONE_OBJECT, PK11_R_NO_OBJECT_FOUND);
+static int pk11_get_pin(void);
+ /* The getpassphrase() function is not MT safe. */
+ OPENSSL_assert(pthread_mutex_lock(token_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ pin = getpassphrase("Enter PIN: ");
+ PK11err(PK11_F_GET_PIN, PK11_R_COULD_NOT_READ_PIN);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ pk11_pin = BUF_strdup(pin);
+ PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_MALLOC_FAILURE);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ memset(pin, 0, strlen(pin));
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ * Log in to the keystore if we are supposed to do that at all. Take care of
+ * reading and caching the PIN etc. Log in only once even when called from
+pk11_token_login(CK_SESSION_HANDLE session, CK_BBOOL *login_done,
+ /* doesn't work on the AEP Keyper??? */
+ if ((pubkey_token_flags & CKF_TOKEN_INITIALIZED) == 0)
+ PK11err(PK11_F_TOKEN_LOGIN,
+ PK11_R_TOKEN_NOT_INITIALIZED);
+ * If login is required or needed but the PIN has not been
+ * even initialized we can bail out right now. Note that we
+ * are supposed to always log in if we are going to access
+ * private keys. However, we may need to log in even for
+ * accessing public keys in case that the CKF_LOGIN_REQUIRED
+ if (((pubkey_token_flags & CKF_LOGIN_REQUIRED) ||
+ (is_private == CK_TRUE)) &&
+ (~pubkey_token_flags & CKF_USER_PIN_INITIALIZED))
+ PK11err(PK11_F_TOKEN_LOGIN, PK11_R_TOKEN_PIN_NOT_SET);
+ * Note on locking: it is possible that more than one thread
+ * gets into pk11_get_pin() so we must deal with that. We
+ * cannot avoid it since we cannot guard fork() in there with
+ * a lock because we could end up in a dead lock in the
+ * child. Why? Remember we are in a multithreaded environment
+ * so we must lock all mutexes in the prefork function to
+ * avoid a situation in which a thread that did not call
+ * fork() held a lock, making future unlocking impossible. We
+ * lock right before C_Login().
+ if ((pubkey_token_flags & CKF_LOGIN_REQUIRED) ||
+ (is_private == CK_TRUE))
+ if (*login_done == CK_FALSE)
+ if ((pk11_pin == NULL) && (pk11_get_pin() == 0))
+ PK11err(PK11_F_TOKEN_LOGIN,
+ PK11_R_TOKEN_PIN_NOT_PROVIDED);
+ * Note that what we are logging into is the keystore from
+ * pubkey_SLOTID because we work with OP_RSA session type here.
+ * That also means that we can work with only one keystore in
+ * We must make sure we do not try to login more than once.
+ * Also, see the comment above on locking strategy.
+ OPENSSL_assert(pthread_mutex_lock(token_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ if (*login_done == CK_FALSE)
+ if ((rv = pFuncList->C_Login(session,
+ CKU_USER, (CK_UTF8CHAR*)pk11_pin,
+ strlen(pk11_pin))) != CKR_OK)
+ PK11err_add_data(PK11_F_TOKEN_LOGIN,
+ PK11_R_TOKEN_LOGIN_FAILED, rv);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ * If token does not require login we take it as the
+ memset(pk11_pin, 0, strlen(pk11_pin));
+ OPENSSL_free((void*)pk11_pin);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ * Log in to the keystore in the child if we were logged in in the
+ * parent. There are similarities in the code with pk11_token_login()
+ * but still it is quite different so we need a separate function for
+ * Note that this function is called under the locked session mutex when fork is
+ * detected. That means that C_Login() will be called from the child just once.
+pk11_token_relogin(CK_SESSION_HANDLE session)
+ if ((pk11_pin == NULL) && (pk11_get_pin() == 0))
+ OPENSSL_assert(pthread_mutex_lock(token_lock) == 0);
+ CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+ if ((rv = pFuncList->C_Login(session, CKU_USER,
+ (CK_UTF8CHAR_PTR)pk11_pin, strlen(pk11_pin))) != CKR_OK)
+ PK11err_add_data(PK11_F_TOKEN_RELOGIN,
+ PK11_R_TOKEN_LOGIN_FAILED, rv);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+ OPENSSL_assert(pthread_mutex_unlock(token_lock) == 0);
+ CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+#ifdef OPENSSL_SYS_WIN32
+char *getpassphrase(const char *prompt)
+ h = GetStdHandle(STD_INPUT_HANDLE);
+ FlushConsoleInputBuffer(h);
+ GetConsoleMode(h, &mode);
+ SetConsoleMode(h, ENABLE_PROCESSED_INPUT);
+ for (cnt = 0; cnt < sizeof(buf) - 1; cnt++)
+ ReadFile(h, buf + cnt, 1, &cc, NULL);
+ SetConsoleMode(h, mode);
+#endif /* OPENSSL_SYS_WIN32 */
+#endif /* OPENSSL_NO_HW_PK11SO */
+#endif /* OPENSSL_NO_HW_PK11 */
+#endif /* OPENSSL_NO_HW */
+/*
pkcs11.h include file for PKCS #11. */
+/* $Revision: 1.1.1.1 $ */
+/* License to copy and use this software is granted provided that it is
+ * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
+ * (Cryptoki)" in all material mentioning or referencing this software.
+ * License is also granted to make and use derivative works provided that
+ * such works are identified as "derived from the RSA Security Inc. PKCS #11
+ * Cryptographic Token Interface (Cryptoki)" in all material mentioning or
+ * referencing the derived work.
+ * RSA Security Inc. makes no representations concerning either the
+ * merchantability of this software or the suitability of this software for
+ * any particular purpose. It is provided "as is" without express or implied
+ * warranty of any kind.
+ * itself), 6 platform-specific macros must be defined. These
+ * macros are described below, and typical definitions for them
+ * are also given. Be advised that these definitions can depend
+ * on both the platform and the compiler used (and possibly also
+ * on whether a Cryptoki library is linked statically or
+ * In addition to defining these 6 macros, the packing convention
+ * for Cryptoki structures should be set. The Cryptoki
+ * convention on packing is that structures should be 1-byte
+ * If you're using Microsoft Developer Studio 5.0 to produce
+ * Win32 stuff, this might be done by using the following
+ * #pragma pack(push, cryptoki, 1)
+ * and using the following preprocessor directive after including
+ * #pragma pack(pop, cryptoki)
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to produce Win16 stuff, this might be done by using
+ * the following preprocessor directive before including
+ * In a UNIX environment, you're on your own for this. You might
+ * not need to do (or be able to do!) anything.
+ * 1. CK_PTR: The indirection string for making a pointer to an
+ * object. It can be used like this:
+ * typedef CK_BYTE CK_PTR CK_BYTE_PTR;
+ * If you're using Microsoft Developer Studio 5.0 to produce
+ * Win32 stuff, it might be defined by:
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to produce Win16 stuff, it might be defined by:
+ * In a typical UNIX environment, it might be defined by:
+ * 2. CK_DEFINE_FUNCTION(returnType, name): A macro which makes
+ * an exportable Cryptoki library function definition out of a
+ * return type and a function name. It should be used in the
+ * following fashion to define the exposed Cryptoki functions in
+ * CK_DEFINE_FUNCTION(CK_RV, C_Initialize)(
+ * CK_VOID_PTR pReserved
+ * If you're using Microsoft Developer Studio 5.0 to define a
+ * function in a Win32 Cryptoki .dll, it might be defined by:
+ * #define CK_DEFINE_FUNCTION(returnType, name) \
+ * returnType __declspec(dllexport) name
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to define a function in a Win16 Cryptoki .dll, it
+ * #define CK_DEFINE_FUNCTION(returnType, name) \
+ * returnType __export _far _pascal name
+ * In a UNIX environment, it might be defined by:
+ * #define CK_DEFINE_FUNCTION(returnType, name) \
+ * 3. CK_DECLARE_FUNCTION(returnType, name): A macro which makes
+ * an importable Cryptoki library function declaration out of a
+ * return type and a function name. It should be used in the
+ * extern CK_DECLARE_FUNCTION(CK_RV, C_Initialize)(
+ * CK_VOID_PTR pReserved
+ * If you're using Microsoft Developer Studio 5.0 to declare a
+ * function in a Win32 Cryptoki .dll, it might be defined by:
+ * #define CK_DECLARE_FUNCTION(returnType, name) \
+ * returnType __declspec(dllimport) name
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to declare a function in a Win16 Cryptoki .dll, it
+ * #define CK_DECLARE_FUNCTION(returnType, name) \
+ * returnType __export _far _pascal name
+ * In a UNIX environment, it might be defined by:
+ * #define CK_DECLARE_FUNCTION(returnType, name) \
+ * 4. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro
+ * which makes a Cryptoki API function pointer declaration or
+ * function pointer type declaration out of a return type and a
+ * function name. It should be used in the following fashion:
+ * // Define funcPtr to be a pointer to a Cryptoki API function
+ * // taking arguments args and returning CK_RV.
+ * CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtr)(args);
+ * // Define funcPtrType to be the type of a pointer to a
+ * // Cryptoki API function taking arguments args and returning
+ * // CK_RV, and then define funcPtr to be a variable of type
+ * typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtrType)(args);
+ * If you're using Microsoft Developer Studio 5.0 to access
+ * functions in a Win32 Cryptoki .dll, in might be defined by:
+ * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ * returnType __declspec(dllimport) (* name)
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to access functions in a Win16 Cryptoki .dll, it might
+ * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ * returnType __export _far _pascal (* name)
+ * In a UNIX environment, it might be defined by:
+ * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ * 5. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes
+ * a function pointer type for an application callback out of
+ * a return type for the callback and a name for the callback.
+ * It should be used in the following fashion:
+ * CK_CALLBACK_FUNCTION(CK_RV, myCallback)(args);
+ * to declare a function pointer, myCallback, to a callback
+ * which takes arguments args and returns a CK_RV. It can also
+ * typedef CK_CALLBACK_FUNCTION(CK_RV, myCallbackType)(args);
+ * myCallbackType myCallback;
+ * If you're using Microsoft Developer Studio 5.0 to do Win32
+ * Cryptoki development, it might be defined by:
+ * #define CK_CALLBACK_FUNCTION(returnType, name) \
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to do Win16 development, it might be defined by:
+ * #define CK_CALLBACK_FUNCTION(returnType, name) \
+ * returnType _far _pascal (* name)
+ * In a UNIX environment, it might be defined by:
+ * #define CK_CALLBACK_FUNCTION(returnType, name) \
+ * 6. NULL_PTR: This macro is the value of a NULL pointer.
+ * In any
ANSI/ISO C environment (and in many others as well),
+ * this should best be defined by
+/* All the various Cryptoki types and #define'd values are in the
+#define __PASTE(x,y) x##y
+/* ==============================================================
+ * Define the "extern" form of all the entry points.
+ * ==============================================================
+#define CK_NEED_ARG_LIST 1
+#define CK_PKCS11_FUNCTION_INFO(name) \
+ extern CK_DECLARE_FUNCTION(CK_RV, name)
+/*
pkcs11f.h has all the information about the Cryptoki
+ * function prototypes. */
+#undef CK_PKCS11_FUNCTION_INFO
+/* ==============================================================
+ * Define the typedef form of all the entry points. That is, for
+ * each Cryptoki function C_XXX, define a type CK_C_XXX which is
+ * a pointer to that kind of function.
+ * ==============================================================
+#define CK_NEED_ARG_LIST 1
+#define CK_PKCS11_FUNCTION_INFO(name) \
+ typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name))
+/*
pkcs11f.h has all the information about the Cryptoki
+ * function prototypes. */
+#undef CK_PKCS11_FUNCTION_INFO
+/* ==============================================================
+ * Define structed vector of entry points. A CK_FUNCTION_LIST
+ * contains a CK_VERSION indicating a library's Cryptoki version
+ * and then a whole slew of function pointers to the routines in
+ * the library. This type was declared, but not defined, in
+ * ==============================================================
+#define CK_PKCS11_FUNCTION_INFO(name) \
+ __PASTE(CK_,name) name;
+struct CK_FUNCTION_LIST {
+ CK_VERSION version; /* Cryptoki version */
+/* Pile all the function pointers into the CK_FUNCTION_LIST. */
+/*
pkcs11f.h has all the information about the Cryptoki
+ * function prototypes. */
+#undef CK_PKCS11_FUNCTION_INFO
+/* $Revision: 1.1.1.1 $ */
+/* License to copy and use this software is granted provided that it is
+ * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
+ * (Cryptoki)" in all material mentioning or referencing this software.
+ * License is also granted to make and use derivative works provided that
+ * such works are identified as "derived from the RSA Security Inc. PKCS #11
+ * Cryptographic Token Interface (Cryptoki)" in all material mentioning or
+ * referencing the derived work.
+ * RSA Security Inc. makes no representations concerning either the
+ * merchantability of this software or the suitability of this software for
+ * any particular purpose. It is provided "as is" without express or implied
+ * warranty of any kind.
+/* This header file contains pretty much everything about all the */
+/* Cryptoki function prototypes. Because this information is */
+/* used for more than just declaring function prototypes, the */
+/* order of the functions appearing herein is important, and */
+/* should not be altered. */
+/* C_Initialize initializes the Cryptoki library. */
+CK_PKCS11_FUNCTION_INFO(C_Initialize)
+ CK_VOID_PTR pInitArgs /* if this is not NULL_PTR, it gets
+ * cast to CK_C_INITIALIZE_ARGS_PTR
+/* C_Finalize indicates that an application is done with the
+CK_PKCS11_FUNCTION_INFO(C_Finalize)
+ CK_VOID_PTR pReserved /* reserved. Should be NULL_PTR */
+/* C_GetInfo returns general information about Cryptoki. */
+CK_PKCS11_FUNCTION_INFO(C_GetInfo)
+ CK_INFO_PTR pInfo /* location that receives information */
+/* C_GetFunctionList returns the function list. */
+CK_PKCS11_FUNCTION_INFO(C_GetFunctionList)
+ CK_FUNCTION_LIST_PTR_PTR ppFunctionList /* receives pointer to
+/* Slot and token management */
+/* C_GetSlotList obtains a list of slots in the system. */
+CK_PKCS11_FUNCTION_INFO(C_GetSlotList)
+ CK_BBOOL tokenPresent, /* only slots with tokens? */
+ CK_SLOT_ID_PTR pSlotList, /* receives array of slot IDs */
+ CK_ULONG_PTR pulCount /* receives number of slots */
+/* C_GetSlotInfo obtains information about a particular slot in
+CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo)
+ CK_SLOT_ID slotID, /* the ID of the slot */
+ CK_SLOT_INFO_PTR pInfo /* receives the slot information */
+/* C_GetTokenInfo obtains information about a particular token
+CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo)
+ CK_SLOT_ID slotID, /* ID of the token's slot */
+ CK_TOKEN_INFO_PTR pInfo /* receives the token information */
+/* C_GetMechanismList obtains a list of mechanism types
+ * supported by a token. */
+CK_PKCS11_FUNCTION_INFO(C_GetMechanismList)
+ CK_SLOT_ID slotID, /* ID of token's slot */
+ CK_MECHANISM_TYPE_PTR pMechanismList, /* gets mech. array */
+ CK_ULONG_PTR pulCount /* gets # of mechs. */
+/* C_GetMechanismInfo obtains information about a particular
+ * mechanism possibly supported by a token. */
+CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo)
+ CK_SLOT_ID slotID, /* ID of the token's slot */
+ CK_MECHANISM_TYPE type, /* type of mechanism */
+ CK_MECHANISM_INFO_PTR pInfo /* receives mechanism info */
+/* C_InitToken initializes a token. */
+CK_PKCS11_FUNCTION_INFO(C_InitToken)
+/* pLabel changed from CK_CHAR_PTR to CK_UTF8CHAR_PTR for v2.10 */
+ CK_SLOT_ID slotID, /* ID of the token's slot */
+ CK_UTF8CHAR_PTR pPin, /* the SO's initial PIN */
+ CK_ULONG ulPinLen, /* length in bytes of the PIN */
+ CK_UTF8CHAR_PTR pLabel /* 32-byte token label (blank padded) */
+/* C_InitPIN initializes the normal user's PIN. */
+CK_PKCS11_FUNCTION_INFO(C_InitPIN)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_UTF8CHAR_PTR pPin, /* the normal user's PIN */
+ CK_ULONG ulPinLen /* length in bytes of the PIN */
+/* C_SetPIN modifies the PIN of the user who is logged in. */
+CK_PKCS11_FUNCTION_INFO(C_SetPIN)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_UTF8CHAR_PTR pOldPin, /* the old PIN */
+ CK_ULONG ulOldLen, /* length of the old PIN */
+ CK_UTF8CHAR_PTR pNewPin, /* the new PIN */
+ CK_ULONG ulNewLen /* length of the new PIN */
+/* Session management */
+/* C_OpenSession opens a session between an application and a
+CK_PKCS11_FUNCTION_INFO(C_OpenSession)
+ CK_SLOT_ID slotID, /* the slot's ID */
+ CK_FLAGS flags, /* from CK_SESSION_INFO */
+ CK_VOID_PTR pApplication, /* passed to callback */
+ CK_NOTIFY Notify, /* callback function */
+ CK_SESSION_HANDLE_PTR phSession /* gets session handle */
+/* C_CloseSession closes a session between an application and a
+CK_PKCS11_FUNCTION_INFO(C_CloseSession)
+ CK_SESSION_HANDLE hSession /* the session's handle */
+/* C_CloseAllSessions closes all sessions with a token. */
+CK_PKCS11_FUNCTION_INFO(C_CloseAllSessions)
+ CK_SLOT_ID slotID /* the token's slot */
+/* C_GetSessionInfo obtains information about the session. */
+CK_PKCS11_FUNCTION_INFO(C_GetSessionInfo)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_SESSION_INFO_PTR pInfo /* receives session info */
+/* C_GetOperationState obtains the state of the cryptographic operation
+CK_PKCS11_FUNCTION_INFO(C_GetOperationState)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pOperationState, /* gets state */
+ CK_ULONG_PTR pulOperationStateLen /* gets state length */
+/* C_SetOperationState restores the state of the cryptographic
+ * operation in a session. */
+CK_PKCS11_FUNCTION_INFO(C_SetOperationState)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pOperationState, /* holds state */
+ CK_ULONG ulOperationStateLen, /* holds state length */
+ CK_OBJECT_HANDLE hAuthenticationKey /*
sign/verify key */
+/* C_Login logs a user into a token. */
+CK_PKCS11_FUNCTION_INFO(C_Login)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_USER_TYPE userType, /* the user type */
+ CK_UTF8CHAR_PTR pPin, /* the user's PIN */
+ CK_ULONG ulPinLen /* the length of the PIN */
+/* C_Logout logs a user out from a token. */
+CK_PKCS11_FUNCTION_INFO(C_Logout)
+ CK_SESSION_HANDLE hSession /* the session's handle */
+/* C_CreateObject creates a new object. */
+CK_PKCS11_FUNCTION_INFO(C_CreateObject)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_ATTRIBUTE_PTR pTemplate, /* the object's template */
+ CK_ULONG ulCount, /* attributes in template */
+ CK_OBJECT_HANDLE_PTR phObject /* gets new object's handle. */
+/* C_CopyObject copies an object, creating a new object for the
+CK_PKCS11_FUNCTION_INFO(C_CopyObject)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_OBJECT_HANDLE hObject, /* the object's handle */
+ CK_ATTRIBUTE_PTR pTemplate, /* template for new object */
+ CK_ULONG ulCount, /* attributes in template */
+ CK_OBJECT_HANDLE_PTR phNewObject /* receives handle of copy */
+/* C_DestroyObject destroys an object. */
+CK_PKCS11_FUNCTION_INFO(C_DestroyObject)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_OBJECT_HANDLE hObject /* the object's handle */
+/* C_GetObjectSize gets the size of an object in bytes. */
+CK_PKCS11_FUNCTION_INFO(C_GetObjectSize)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_OBJECT_HANDLE hObject, /* the object's handle */
+ CK_ULONG_PTR pulSize /* receives size of object */
+/* C_GetAttributeValue obtains the value of one or more object
+CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_OBJECT_HANDLE hObject, /* the object's handle */
+ CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs; gets vals */
+ CK_ULONG ulCount /* attributes in template */
+/* C_SetAttributeValue modifies the value of one or more object
+CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_OBJECT_HANDLE hObject, /* the object's handle */
+ CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs and values */
+ CK_ULONG ulCount /* attributes in template */
+/* C_FindObjectsInit initializes a search for token and session
+ * objects that match a template. */
+CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_ATTRIBUTE_PTR pTemplate, /* attribute values to match */
+ CK_ULONG ulCount /* attrs in search template */
+/* C_FindObjects continues a search for token and session
+ * objects that match a template, obtaining additional object
+CK_PKCS11_FUNCTION_INFO(C_FindObjects)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_OBJECT_HANDLE_PTR phObject, /* gets obj. handles */
+ CK_ULONG ulMaxObjectCount, /* max handles to get */
+ CK_ULONG_PTR pulObjectCount /* actual # returned */
+/* C_FindObjectsFinal finishes a search for token and session
+CK_PKCS11_FUNCTION_INFO(C_FindObjectsFinal)
+ CK_SESSION_HANDLE hSession /* the session's handle */
+/* Encryption and decryption */
+/* C_EncryptInit initializes an encryption operation. */
+CK_PKCS11_FUNCTION_INFO(C_EncryptInit)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_MECHANISM_PTR pMechanism, /* the encryption mechanism */
+ CK_OBJECT_HANDLE hKey /* handle of encryption key */
+/* C_Encrypt encrypts single-part data. */
+CK_PKCS11_FUNCTION_INFO(C_Encrypt)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pData, /* the plaintext data */
+ CK_ULONG ulDataLen, /* bytes of plaintext */
+ CK_BYTE_PTR pEncryptedData, /* gets ciphertext */
+ CK_ULONG_PTR pulEncryptedDataLen /* gets c-text size */
+/* C_EncryptUpdate continues a multiple-part encryption
+CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pPart, /* the plaintext data */
+ CK_ULONG ulPartLen, /* plaintext data len */
+ CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */
+ CK_ULONG_PTR pulEncryptedPartLen /* gets c-text size */
+/* C_EncryptFinal finishes a multiple-part encryption
+CK_PKCS11_FUNCTION_INFO(C_EncryptFinal)
+ CK_SESSION_HANDLE hSession, /* session handle */
+ CK_BYTE_PTR pLastEncryptedPart, /* last c-text */
+ CK_ULONG_PTR pulLastEncryptedPartLen /* gets last size */
+/* C_DecryptInit initializes a decryption operation. */
+CK_PKCS11_FUNCTION_INFO(C_DecryptInit)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_MECHANISM_PTR pMechanism, /* the decryption mechanism */
+ CK_OBJECT_HANDLE hKey /* handle of decryption key */
+/* C_Decrypt decrypts encrypted data in a single part. */
+CK_PKCS11_FUNCTION_INFO(C_Decrypt)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pEncryptedData, /* ciphertext */
+ CK_ULONG ulEncryptedDataLen, /* ciphertext length */
+ CK_BYTE_PTR pData, /* gets plaintext */
+ CK_ULONG_PTR pulDataLen /* gets p-text size */
+/* C_DecryptUpdate continues a multiple-part decryption
+CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pEncryptedPart, /* encrypted data */
+ CK_ULONG ulEncryptedPartLen, /* input length */
+ CK_BYTE_PTR pPart, /* gets plaintext */
+ CK_ULONG_PTR pulPartLen /* p-text size */
+/* C_DecryptFinal finishes a multiple-part decryption
+CK_PKCS11_FUNCTION_INFO(C_DecryptFinal)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pLastPart, /* gets plaintext */
+ CK_ULONG_PTR pulLastPartLen /* p-text size */
+/* C_DigestInit initializes a message-digesting operation. */
+CK_PKCS11_FUNCTION_INFO(C_DigestInit)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_MECHANISM_PTR pMechanism /* the digesting mechanism */
+/* C_Digest digests data in a single part. */
+CK_PKCS11_FUNCTION_INFO(C_Digest)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pData, /* data to be digested */
+ CK_ULONG ulDataLen, /* bytes of data to digest */
+ CK_BYTE_PTR pDigest, /* gets the message digest */
+ CK_ULONG_PTR pulDigestLen /* gets digest length */
+/* C_DigestUpdate continues a multiple-part message-digesting
+CK_PKCS11_FUNCTION_INFO(C_DigestUpdate)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pPart, /* data to be digested */
+ CK_ULONG ulPartLen /* bytes of data to be digested */
+/* C_DigestKey continues a multi-part message-digesting
+ * operation, by digesting the value of a secret key as part of
+ * the data already digested. */
+CK_PKCS11_FUNCTION_INFO(C_DigestKey)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_OBJECT_HANDLE hKey /* secret key to digest */
+/* C_DigestFinal finishes a multiple-part message-digesting
+CK_PKCS11_FUNCTION_INFO(C_DigestFinal)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pDigest, /* gets the message digest */
+ CK_ULONG_PTR pulDigestLen /* gets byte count of digest */
+/* Signing and MACing */
+/* C_SignInit initializes a signature (private key encryption)
+ * operation, where the signature is (will be) an appendix to
+ * the data, and plaintext cannot be recovered from the
+CK_PKCS11_FUNCTION_INFO(C_SignInit)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_MECHANISM_PTR pMechanism, /* the signature mechanism */
+ CK_OBJECT_HANDLE hKey /* handle of signature key */
+/* C_Sign signs (encrypts with private key) data in a single
+ * part, where the signature is (will be) an appendix to the
+ * data, and plaintext cannot be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_Sign)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pData, /* the data to sign */
+ CK_ULONG ulDataLen, /* count of bytes to sign */
+ CK_BYTE_PTR pSignature, /* gets the signature */
+ CK_ULONG_PTR pulSignatureLen /* gets signature length */
+/* C_SignUpdate continues a multiple-part signature operation,
+ * where the signature is (will be) an appendix to the data,
+ * and plaintext cannot be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_SignUpdate)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pPart, /* the data to sign */
+ CK_ULONG ulPartLen /* count of bytes to sign */
+/* C_SignFinal finishes a multiple-part signature operation,
+ * returning the signature. */
+CK_PKCS11_FUNCTION_INFO(C_SignFinal)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pSignature, /* gets the signature */
+ CK_ULONG_PTR pulSignatureLen /* gets signature length */
+/* C_SignRecoverInit initializes a signature operation, where
+ * the data can be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_MECHANISM_PTR pMechanism, /* the signature mechanism */
+ CK_OBJECT_HANDLE hKey /* handle of the signature key */
+/* C_SignRecover signs data in a single operation, where the
+ * data can be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_SignRecover)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pData, /* the data to sign */
+ CK_ULONG ulDataLen, /* count of bytes to sign */
+ CK_BYTE_PTR pSignature, /* gets the signature */
+ CK_ULONG_PTR pulSignatureLen /* gets signature length */
+/* Verifying signatures and MACs */
+/* C_VerifyInit initializes a verification operation, where the
+ * signature is an appendix to the data, and plaintext cannot
+ * cannot be recovered from the signature (
e.g. DSA). */
+CK_PKCS11_FUNCTION_INFO(C_VerifyInit)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_MECHANISM_PTR pMechanism, /* the verification mechanism */
+ CK_OBJECT_HANDLE hKey /* verification key */
+/* C_Verify verifies a signature in a single-part operation,
+ * where the signature is an appendix to the data, and plaintext
+ * cannot be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_Verify)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pData, /* signed data */
+ CK_ULONG ulDataLen, /* length of signed data */
+ CK_BYTE_PTR pSignature, /* signature */
+ CK_ULONG ulSignatureLen /* signature length*/
+/* C_VerifyUpdate continues a multiple-part verification
+ * operation, where the signature is an appendix to the data,
+ * and plaintext cannot be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pPart, /* signed data */
+ CK_ULONG ulPartLen /* length of signed data */
+/* C_VerifyFinal finishes a multiple-part verification
+ * operation, checking the signature. */
+CK_PKCS11_FUNCTION_INFO(C_VerifyFinal)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pSignature, /* signature to verify */
+ CK_ULONG ulSignatureLen /* signature length */
+/* C_VerifyRecoverInit initializes a signature verification
+ * operation, where the data is recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_MECHANISM_PTR pMechanism, /* the verification mechanism */
+ CK_OBJECT_HANDLE hKey /* verification key */
+/* C_VerifyRecover verifies a signature in a single-part
+ * operation, where the data is recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_VerifyRecover)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pSignature, /* signature to verify */
+ CK_ULONG ulSignatureLen, /* signature length */
+ CK_BYTE_PTR pData, /* gets signed data */
+ CK_ULONG_PTR pulDataLen /* gets signed data len */
+/* Dual-function cryptographic operations */
+/* C_DigestEncryptUpdate continues a multiple-part digesting
+ * and encryption operation. */
+CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pPart, /* the plaintext data */
+ CK_ULONG ulPartLen, /* plaintext length */
+ CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */
+ CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */
+/* C_DecryptDigestUpdate continues a multiple-part decryption and
+ * digesting operation. */
+CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pEncryptedPart, /* ciphertext */
+ CK_ULONG ulEncryptedPartLen, /* ciphertext length */
+ CK_BYTE_PTR pPart, /* gets plaintext */
+ CK_ULONG_PTR pulPartLen /* gets plaintext len */
+/* C_SignEncryptUpdate continues a multiple-part signing and
+ * encryption operation. */
+CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pPart, /* the plaintext data */
+ CK_ULONG ulPartLen, /* plaintext length */
+ CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */
+ CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */
+/* C_DecryptVerifyUpdate continues a multiple-part decryption and
+CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_BYTE_PTR pEncryptedPart, /* ciphertext */
+ CK_ULONG ulEncryptedPartLen, /* ciphertext length */
+ CK_BYTE_PTR pPart, /* gets plaintext */
+ CK_ULONG_PTR pulPartLen /* gets p-text length */
+/* C_GenerateKey generates a secret key, creating a new key
+CK_PKCS11_FUNCTION_INFO(C_GenerateKey)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_MECHANISM_PTR pMechanism, /* key generation mech. */
+ CK_ATTRIBUTE_PTR pTemplate, /* template for new key */
+ CK_ULONG ulCount, /* # of attrs in template */
+ CK_OBJECT_HANDLE_PTR phKey /* gets handle of new key */
+ * creating new key objects. */
+CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair)
+ CK_SESSION_HANDLE hSession, /* session
+ CK_MECHANISM_PTR pMechanism, /* key-gen
+ CK_ATTRIBUTE_PTR pPublicKeyTemplate, /* template
+ CK_ULONG ulPublicKeyAttributeCount, /* # pub.
+ CK_ATTRIBUTE_PTR pPrivateKeyTemplate, /* template
+ CK_ULONG ulPrivateKeyAttributeCount, /* # priv.
+ CK_OBJECT_HANDLE_PTR phPublicKey, /* gets pub.
+ CK_OBJECT_HANDLE_PTR phPrivateKey /* gets
+/* C_WrapKey wraps (
i.e., encrypts) a key. */
+CK_PKCS11_FUNCTION_INFO(C_WrapKey)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_MECHANISM_PTR pMechanism, /* the wrapping mechanism */
+ CK_OBJECT_HANDLE hWrappingKey, /* wrapping key */
+ CK_OBJECT_HANDLE hKey, /* key to be wrapped */
+ CK_BYTE_PTR pWrappedKey, /* gets wrapped key */
+ CK_ULONG_PTR pulWrappedKeyLen /* gets wrapped key size */
+/* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new
+CK_PKCS11_FUNCTION_INFO(C_UnwrapKey)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_MECHANISM_PTR pMechanism, /* unwrapping mech. */
+ CK_OBJECT_HANDLE hUnwrappingKey, /* unwrapping key */
+ CK_BYTE_PTR pWrappedKey, /* the wrapped key */
+ CK_ULONG ulWrappedKeyLen, /* wrapped key len */
+ CK_ATTRIBUTE_PTR pTemplate, /* new key template */
+ CK_ULONG ulAttributeCount, /* template length */
+ CK_OBJECT_HANDLE_PTR phKey /* gets new handle */
+/* C_DeriveKey derives a key from a base key, creating a new key
+CK_PKCS11_FUNCTION_INFO(C_DeriveKey)
+ CK_SESSION_HANDLE hSession, /* session's handle */
+ CK_MECHANISM_PTR pMechanism, /* key deriv. mech. */
+ CK_OBJECT_HANDLE hBaseKey, /* base key */
+ CK_ATTRIBUTE_PTR pTemplate, /* new key template */
+ CK_ULONG ulAttributeCount, /* template length */
+ CK_OBJECT_HANDLE_PTR phKey /* gets new handle */
+/* Random number generation */
+/* C_SeedRandom mixes additional seed material into the token's
+ * random number generator. */
+CK_PKCS11_FUNCTION_INFO(C_SeedRandom)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR pSeed, /* the seed material */
+ CK_ULONG ulSeedLen /* length of seed material */
+/* C_GenerateRandom generates random data. */
+CK_PKCS11_FUNCTION_INFO(C_GenerateRandom)
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_BYTE_PTR RandomData, /* receives the random data */
+ CK_ULONG ulRandomLen /* # of bytes to generate */
+/* Parallel function management */
+/* C_GetFunctionStatus is a legacy function; it obtains an
+ * updated status of a function running in parallel with an
+CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus)
+ CK_SESSION_HANDLE hSession /* the session's handle */
+/* C_CancelFunction is a legacy function; it cancels a function
+ * running in parallel. */
+CK_PKCS11_FUNCTION_INFO(C_CancelFunction)
+ CK_SESSION_HANDLE hSession /* the session's handle */
+/* Functions added in for Cryptoki Version 2.01 or later */
+/* C_WaitForSlotEvent waits for a slot event (token insertion,
+ * removal, etc.) to occur. */
+CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent)
+ CK_SLOT_ID_PTR pSlot, /* location that receives the slot ID */
+ CK_VOID_PTR pRserved /* reserved. Should be NULL_PTR */
+/* License to copy and use this software is granted provided that it is
+ * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
+ * (Cryptoki)" in all material mentioning or referencing this software.
+ * License is also granted to make and use derivative works provided that
+ * such works are identified as "derived from the RSA Security Inc. PKCS #11
+ * Cryptographic Token Interface (Cryptoki)" in all material mentioning or
+ * referencing the derived work.
+ * RSA Security Inc. makes no representations concerning either the
+ * merchantability of this software or the suitability of this software for
+ * any particular purpose. It is provided "as is" without express or implied
+ * warranty of any kind.
+/* See top of
pkcs11.h for information about the macros that
+ * must be defined and the structure-packing conventions that
+ * must be set before including this file. */
+#define CRYPTOKI_VERSION_MAJOR 2
+#define CRYPTOKI_VERSION_MINOR 20
+#define CRYPTOKI_VERSION_AMENDMENT 3
+#ifndef CK_DISABLE_TRUE_FALSE
+/* an unsigned 8-bit value */
+typedef unsigned char CK_BYTE;
+/* an unsigned 8-bit character */
+typedef CK_BYTE CK_CHAR;
+/* an 8-bit UTF-8 character */
+typedef CK_BYTE CK_UTF8CHAR;
+/* a BYTE-sized Boolean flag */
+typedef CK_BYTE CK_BBOOL;
+/* an unsigned value, at least 32 bits long */
+typedef unsigned long int CK_ULONG;
+/* a signed value, the same size as a CK_ULONG */
+/* CK_LONG is new for v2.0 */
+typedef long int CK_LONG;
+/* at least 32 bits; each bit is a Boolean flag */
+typedef CK_ULONG CK_FLAGS;
+/* some special values for certain CK_ULONG variables */
+#define CK_UNAVAILABLE_INFORMATION (~0UL)
+#define CK_EFFECTIVELY_INFINITE 0
+typedef CK_BYTE CK_PTR CK_BYTE_PTR;
+typedef CK_CHAR CK_PTR CK_CHAR_PTR;
+typedef CK_UTF8CHAR CK_PTR CK_UTF8CHAR_PTR;
+typedef CK_ULONG CK_PTR CK_ULONG_PTR;
+typedef void CK_PTR CK_VOID_PTR;
+/* Pointer to a CK_VOID_PTR--
i.e., pointer to pointer to void */
+typedef CK_VOID_PTR CK_PTR CK_VOID_PTR_PTR;
+/* The following value is always invalid if used as a session */
+/* handle or object handle */
+#define CK_INVALID_HANDLE 0
+typedef struct CK_VERSION {
+ CK_BYTE major; /* integer portion of version number */
+ CK_BYTE minor; /* 1/100ths portion of version number */
+typedef CK_VERSION CK_PTR CK_VERSION_PTR;
+typedef struct CK_INFO {
+ /* manufacturerID and libraryDecription have been changed from
+ * CK_CHAR to CK_UTF8CHAR for v2.10 */
+ CK_VERSION cryptokiVersion; /* Cryptoki interface ver */
+ CK_UTF8CHAR manufacturerID[32]; /* blank padded */
+ CK_FLAGS flags; /* must be zero */
+ /* libraryDescription and libraryVersion are new for v2.0 */
+ CK_UTF8CHAR libraryDescription[32]; /* blank padded */
+ CK_VERSION libraryVersion; /* version of library */
+typedef CK_INFO CK_PTR CK_INFO_PTR;
+/* CK_NOTIFICATION enumerates the types of notifications that
+ * Cryptoki provides to an application */
+/* CK_NOTIFICATION has been changed from an enum to a CK_ULONG
+typedef CK_ULONG CK_NOTIFICATION;
+/* The following notification is new for PKCS #11 v2.20 amendment 3 */
+#define CKN_OTP_CHANGED 1
+typedef CK_ULONG CK_SLOT_ID;
+typedef CK_SLOT_ID CK_PTR CK_SLOT_ID_PTR;
+/* CK_SLOT_INFO provides information about a slot */
+typedef struct CK_SLOT_INFO {
+ /* slotDescription and manufacturerID have been changed from
+ * CK_CHAR to CK_UTF8CHAR for v2.10 */
+ CK_UTF8CHAR slotDescription[64]; /* blank padded */
+ CK_UTF8CHAR manufacturerID[32]; /* blank padded */
+ /* hardwareVersion and firmwareVersion are new for v2.0 */
+ CK_VERSION hardwareVersion; /* version of hardware */
+ CK_VERSION firmwareVersion; /* version of firmware */
+/* flags: bit flags that provide capabilities of the slot
+ * Bit Flag Mask Meaning
+#define CKF_TOKEN_PRESENT 0x00000001 /* a token is there */
+#define CKF_REMOVABLE_DEVICE 0x00000002 /* removable devices*/
+#define CKF_HW_SLOT 0x00000004 /* hardware slot */
+typedef CK_SLOT_INFO CK_PTR CK_SLOT_INFO_PTR;
+/* CK_TOKEN_INFO provides information about a token */
+typedef struct CK_TOKEN_INFO {
+ /* label, manufacturerID, and model have been changed from
+ * CK_CHAR to CK_UTF8CHAR for v2.10 */
+ CK_UTF8CHAR label[32]; /* blank padded */
+ CK_UTF8CHAR manufacturerID[32]; /* blank padded */
+ CK_UTF8CHAR model[16]; /* blank padded */
+ CK_CHAR serialNumber[16]; /* blank padded */
+ CK_FLAGS flags; /* see below */
+ /* ulMaxSessionCount, ulSessionCount, ulMaxRwSessionCount,
+ * ulRwSessionCount, ulMaxPinLen, and ulMinPinLen have all been
+ * changed from CK_USHORT to CK_ULONG for v2.0 */
+ CK_ULONG ulMaxSessionCount; /* max open sessions */
+ CK_ULONG ulSessionCount; /* sess. now open */
+ CK_ULONG ulMaxRwSessionCount; /* max R/W sessions */
+ CK_ULONG ulRwSessionCount; /* R/W sess. now open */
+ CK_ULONG ulMaxPinLen; /* in bytes */
+ CK_ULONG ulMinPinLen; /* in bytes */
+ CK_ULONG ulTotalPublicMemory; /* in bytes */
+ CK_ULONG ulFreePublicMemory; /* in bytes */
+ CK_ULONG ulTotalPrivateMemory; /* in bytes */
+ CK_ULONG ulFreePrivateMemory; /* in bytes */
+ /* hardwareVersion, firmwareVersion, and time are new for
+ CK_VERSION hardwareVersion; /* version of hardware */
+ CK_VERSION firmwareVersion; /* version of firmware */
+ CK_CHAR utcTime[16]; /* time */
+/* The flags parameter is defined as follows:
+ * Bit Flag Mask Meaning
+#define CKF_RNG 0x00000001 /* has random #
+#define CKF_WRITE_PROTECTED 0x00000002 /* token is
+#define CKF_LOGIN_REQUIRED 0x00000004 /* user must
+#define CKF_USER_PIN_INITIALIZED 0x00000008 /* normal user's
+/* CKF_RESTORE_KEY_NOT_NEEDED is new for v2.0. If it is set,
+ * that means that *every* time the state of cryptographic
+ * operations of a session is successfully saved, all keys
+ * needed to continue those operations are stored in the state */
+#define CKF_RESTORE_KEY_NOT_NEEDED 0x00000020
+/* CKF_CLOCK_ON_TOKEN is new for v2.0. If it is set, that means
+ * that the token has some sort of clock. The time on that
+ * clock is returned in the token info structure */
+#define CKF_CLOCK_ON_TOKEN 0x00000040
+/* CKF_PROTECTED_AUTHENTICATION_PATH is new for v2.0. If it is
+ * set, that means that there is some way for the user to login
+ * without sending a PIN through the Cryptoki library itself */
+#define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100
+/* CKF_DUAL_CRYPTO_OPERATIONS is new for v2.0. If it is true,
+ * that means that a single session with the token can perform
+ * dual simultaneous cryptographic operations (digest and
+ * encrypt; decrypt and digest; sign and encrypt; and decrypt
+#define CKF_DUAL_CRYPTO_OPERATIONS 0x00000200
+/* CKF_TOKEN_INITIALIZED if new for v2.10. If it is true, the
+ * token has been initialized using C_InitializeToken or an
+ * equivalent mechanism outside the scope of PKCS #11.
+ * Calling C_InitializeToken when this flag is set will cause
+ * the token to be reinitialized. */
+#define CKF_TOKEN_INITIALIZED 0x00000400
+/* CKF_SECONDARY_AUTHENTICATION if new for v2.10. If it is
+ * true, the token supports secondary authentication for
+ * private key objects. This flag is deprecated in v2.11 and
+#define CKF_SECONDARY_AUTHENTICATION 0x00000800
+/* CKF_USER_PIN_COUNT_LOW if new for v2.10. If it is true, an
+ * incorrect user login PIN has been entered at least once
+ * since the last successful authentication. */
+#define CKF_USER_PIN_COUNT_LOW 0x00010000
+/* CKF_USER_PIN_FINAL_TRY if new for v2.10. If it is true,
+ * supplying an incorrect user PIN will it to become locked. */
+#define CKF_USER_PIN_FINAL_TRY 0x00020000
+/* CKF_USER_PIN_LOCKED if new for v2.10. If it is true, the
+ * user PIN has been locked. User login to the token is not
+#define CKF_USER_PIN_LOCKED 0x00040000
+/* CKF_USER_PIN_TO_BE_CHANGED if new for v2.10. If it is true,
+ * the user PIN value is the default value set by token
+ * initialization or manufacturing, or the PIN has been
+ * expired by the card. */
+#define CKF_USER_PIN_TO_BE_CHANGED 0x00080000
+/* CKF_SO_PIN_COUNT_LOW if new for v2.10. If it is true, an
+ * incorrect SO login PIN has been entered at least once since
+ * the last successful authentication. */
+#define CKF_SO_PIN_COUNT_LOW 0x00100000
+/* CKF_SO_PIN_FINAL_TRY if new for v2.10. If it is true,
+ * supplying an incorrect SO PIN will it to become locked. */
+#define CKF_SO_PIN_FINAL_TRY 0x00200000
+/* CKF_SO_PIN_LOCKED if new for v2.10. If it is true, the SO
+ * PIN has been locked. SO login to the token is not possible.
+#define CKF_SO_PIN_LOCKED 0x00400000
+/* CKF_SO_PIN_TO_BE_CHANGED if new for v2.10. If it is true,
+ * the SO PIN value is the default value set by token
+ * initialization or manufacturing, or the PIN has been
+ * expired by the card. */
+#define CKF_SO_PIN_TO_BE_CHANGED 0x00800000
+typedef CK_TOKEN_INFO CK_PTR CK_TOKEN_INFO_PTR;
+/* CK_SESSION_HANDLE is a Cryptoki-assigned value that
+ * identifies a session */
+typedef CK_ULONG CK_SESSION_HANDLE;
+typedef CK_SESSION_HANDLE CK_PTR CK_SESSION_HANDLE_PTR;
+/* CK_USER_TYPE enumerates the types of Cryptoki users */
+/* CK_USER_TYPE has been changed from an enum to a CK_ULONG for
+typedef CK_ULONG CK_USER_TYPE;
+/* Context specific (added in v2.20) */
+#define CKU_CONTEXT_SPECIFIC 2
+/* CK_STATE enumerates the session states */
+/* CK_STATE has been changed from an enum to a CK_ULONG for
+typedef CK_ULONG CK_STATE;
+#define CKS_RO_PUBLIC_SESSION 0
+#define CKS_RO_USER_FUNCTIONS 1
+#define CKS_RW_PUBLIC_SESSION 2
+#define CKS_RW_USER_FUNCTIONS 3
+#define CKS_RW_SO_FUNCTIONS 4
+/* CK_SESSION_INFO provides information about a session */
+typedef struct CK_SESSION_INFO {
+ CK_FLAGS flags; /* see below */
+ /* ulDeviceError was changed from CK_USHORT to CK_ULONG for
+ CK_ULONG ulDeviceError; /* device-dependent error code */
+/* The flags are defined in the following table:
+ * Bit Flag Mask Meaning
+#define CKF_RW_SESSION 0x00000002 /* session is r/w */
+#define CKF_SERIAL_SESSION 0x00000004 /* no parallel */
+typedef CK_SESSION_INFO CK_PTR CK_SESSION_INFO_PTR;
+/* CK_OBJECT_HANDLE is a token-specific identifier for an
+typedef CK_ULONG CK_OBJECT_HANDLE;
+typedef CK_OBJECT_HANDLE CK_PTR CK_OBJECT_HANDLE_PTR;
+/* CK_OBJECT_CLASS is a value that identifies the classes (or
+ * types) of objects that Cryptoki recognizes. It is defined
+/* CK_OBJECT_CLASS was changed from CK_USHORT to CK_ULONG for
+typedef CK_ULONG CK_OBJECT_CLASS;
+/* The following classes of objects are defined: */
+/* CKO_HW_FEATURE is new for v2.10 */
+/* CKO_DOMAIN_PARAMETERS is new for v2.11 */
+/* CKO_MECHANISM is new for v2.20 */
+#define CKO_DATA 0x00000000
+#define CKO_CERTIFICATE 0x00000001
+#define CKO_PUBLIC_KEY 0x00000002
+#define CKO_PRIVATE_KEY 0x00000003
+#define CKO_SECRET_KEY 0x00000004
+#define CKO_HW_FEATURE 0x00000005
+#define CKO_DOMAIN_PARAMETERS 0x00000006
+#define CKO_MECHANISM 0x00000007
+/* CKO_OTP_KEY is new for PKCS #11 v2.20 amendment 1 */
+#define CKO_OTP_KEY 0x00000008
+#define CKO_VENDOR_DEFINED 0x80000000
+typedef CK_OBJECT_CLASS CK_PTR CK_OBJECT_CLASS_PTR;
+/* CK_HW_FEATURE_TYPE is new for v2.10. CK_HW_FEATURE_TYPE is a
+ * value that identifies the hardware feature type of an object
+ * with CK_OBJECT_CLASS equal to CKO_HW_FEATURE. */
+typedef CK_ULONG CK_HW_FEATURE_TYPE;
+/* The following hardware feature types are defined */
+/* CKH_USER_INTERFACE is new for v2.20 */
+#define CKH_MONOTONIC_COUNTER 0x00000001
+#define CKH_CLOCK 0x00000002
+#define CKH_USER_INTERFACE 0x00000003
+#define CKH_VENDOR_DEFINED 0x80000000
+/* CK_KEY_TYPE is a value that identifies a key type */
+/* CK_KEY_TYPE was changed from CK_USHORT to CK_ULONG for v2.0 */
+typedef CK_ULONG CK_KEY_TYPE;
+/* the following key types are defined: */
+#define CKK_RSA 0x00000000
+#define CKK_DSA 0x00000001
+#define CKK_DH 0x00000002
+/* CKK_ECDSA and CKK_KEA are new for v2.0 */
+/* CKK_ECDSA is deprecated in v2.11, CKK_EC is preferred. */
+#define CKK_ECDSA 0x00000003
+#define CKK_EC 0x00000003
+#define CKK_X9_42_DH 0x00000004
+#define CKK_KEA 0x00000005
+#define CKK_GENERIC_SECRET 0x00000010
+#define CKK_RC2 0x00000011
+#define CKK_RC4 0x00000012
+#define CKK_DES 0x00000013
+#define CKK_DES2 0x00000014
+#define CKK_DES3 0x00000015
+/* all these key types are new for v2.0 */
+#define CKK_CAST 0x00000016
+#define CKK_CAST3 0x00000017
+/* CKK_CAST5 is deprecated in v2.11, CKK_CAST128 is preferred. */
+#define CKK_CAST5 0x00000018
+#define CKK_CAST128 0x00000018
+#define CKK_RC5 0x00000019
+#define CKK_IDEA 0x0000001A
+#define CKK_SKIPJACK 0x0000001B
+#define CKK_BATON 0x0000001C
+#define CKK_JUNIPER 0x0000001D
+#define CKK_CDMF 0x0000001E
+#define CKK_AES 0x0000001F
+/* BlowFish and TwoFish are new for v2.20 */
+#define CKK_BLOWFISH 0x00000020
+#define CKK_TWOFISH 0x00000021
+/* SecurID, HOTP, and ACTI are new for PKCS #11 v2.20 amendment 1 */
+#define CKK_SECURID 0x00000022
+#define CKK_HOTP 0x00000023
+#define CKK_ACTI 0x00000024
+/* Camellia is new for PKCS #11 v2.20 amendment 3 */
+#define CKK_CAMELLIA 0x00000025
+/* ARIA is new for PKCS #11 v2.20 amendment 3 */
+#define CKK_ARIA 0x00000026
+#define CKK_VENDOR_DEFINED 0x80000000
+/* CK_CERTIFICATE_TYPE is a value that identifies a certificate
+/* CK_CERTIFICATE_TYPE was changed from CK_USHORT to CK_ULONG
+typedef CK_ULONG CK_CERTIFICATE_TYPE;
+/* The following certificate types are defined: */
+/* CKC_X_509_ATTR_CERT is new for v2.10 */
+/* CKC_WTLS is new for v2.20 */
+#define CKC_X_509 0x00000000
+#define CKC_X_509_ATTR_CERT 0x00000001
+#define CKC_WTLS 0x00000002
+#define CKC_VENDOR_DEFINED 0x80000000
+/* CK_ATTRIBUTE_TYPE is a value that identifies an attribute
+/* CK_ATTRIBUTE_TYPE was changed from CK_USHORT to CK_ULONG for
+typedef CK_ULONG CK_ATTRIBUTE_TYPE;
+/* The CKF_ARRAY_ATTRIBUTE flag identifies an attribute which
+ consists of an array of values. */
+#define CKF_ARRAY_ATTRIBUTE 0x40000000
+/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1
+ and relates to the CKA_OTP_FORMAT attribute */
+#define CK_OTP_FORMAT_DECIMAL 0
+#define CK_OTP_FORMAT_HEXADECIMAL 1
+#define CK_OTP_FORMAT_ALPHANUMERIC 2
+#define CK_OTP_FORMAT_BINARY 3
+/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1
+ and relates to the CKA_OTP_..._REQUIREMENT attributes */
+#define CK_OTP_PARAM_IGNORED 0
+#define CK_OTP_PARAM_OPTIONAL 1
+#define CK_OTP_PARAM_MANDATORY 2
+/* The following attribute types are defined: */
+#define CKA_CLASS 0x00000000
+#define CKA_TOKEN 0x00000001
+#define CKA_PRIVATE 0x00000002
+#define CKA_LABEL 0x00000003
+#define CKA_APPLICATION 0x00000010
+#define CKA_VALUE 0x00000011
+/* CKA_OBJECT_ID is new for v2.10 */
+#define CKA_OBJECT_ID 0x00000012
+#define CKA_CERTIFICATE_TYPE 0x00000080
+#define CKA_ISSUER 0x00000081
+#define CKA_SERIAL_NUMBER 0x00000082
+/* CKA_AC_ISSUER, CKA_OWNER, and CKA_ATTR_TYPES are new
+#define CKA_AC_ISSUER 0x00000083
+#define CKA_OWNER 0x00000084
+#define CKA_ATTR_TYPES 0x00000085
+/* CKA_TRUSTED is new for v2.11 */
+#define CKA_TRUSTED 0x00000086
+/* CKA_CERTIFICATE_CATEGORY ...
+ * CKA_CHECK_VALUE are new for v2.20 */
+#define CKA_CERTIFICATE_CATEGORY 0x00000087
+#define CKA_JAVA_MIDP_SECURITY_DOMAIN 0x00000088
+#define CKA_URL 0x00000089
+#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY 0x0000008A
+#define CKA_HASH_OF_ISSUER_PUBLIC_KEY 0x0000008B
+#define CKA_CHECK_VALUE 0x00000090
+#define CKA_KEY_TYPE 0x00000100
+#define CKA_SUBJECT 0x00000101
+#define CKA_ID 0x00000102
+#define CKA_SENSITIVE 0x00000103
+#define CKA_ENCRYPT 0x00000104
+#define CKA_DECRYPT 0x00000105
+#define CKA_WRAP 0x00000106
+#define CKA_UNWRAP 0x00000107
+#define CKA_SIGN 0x00000108
+#define CKA_SIGN_RECOVER 0x00000109
+#define CKA_VERIFY 0x0000010A
+#define CKA_VERIFY_RECOVER 0x0000010B
+#define CKA_DERIVE 0x0000010C
+#define CKA_START_DATE 0x00000110
+#define CKA_END_DATE 0x00000111
+#define CKA_MODULUS 0x00000120
+#define CKA_MODULUS_BITS 0x00000121
+#define CKA_PUBLIC_EXPONENT 0x00000122
+#define CKA_PRIVATE_EXPONENT 0x00000123
+#define CKA_PRIME_1 0x00000124
+#define CKA_PRIME_2 0x00000125
+#define CKA_EXPONENT_1 0x00000126
+#define CKA_EXPONENT_2 0x00000127
+#define CKA_COEFFICIENT 0x00000128
+#define CKA_PRIME 0x00000130
+#define CKA_SUBPRIME 0x00000131
+#define CKA_BASE 0x00000132
+/* CKA_PRIME_BITS and CKA_SUB_PRIME_BITS are new for v2.11 */
+#define CKA_PRIME_BITS 0x00000133
+#define CKA_SUBPRIME_BITS 0x00000134
+#define CKA_SUB_PRIME_BITS CKA_SUBPRIME_BITS
+/* (To retain backwards-compatibility) */
+#define CKA_VALUE_BITS 0x00000160
+#define CKA_VALUE_LEN 0x00000161
+/* CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE,
+ * CKA_ALWAYS_SENSITIVE, CKA_MODIFIABLE, CKA_ECDSA_PARAMS,
+ * and CKA_EC_POINT are new for v2.0 */
+#define CKA_EXTRACTABLE 0x00000162
+#define CKA_LOCAL 0x00000163
+#define CKA_NEVER_EXTRACTABLE 0x00000164
+#define CKA_ALWAYS_SENSITIVE 0x00000165
+/* CKA_KEY_GEN_MECHANISM is new for v2.11 */
+#define CKA_KEY_GEN_MECHANISM 0x00000166
+#define CKA_MODIFIABLE 0x00000170
+/* CKA_ECDSA_PARAMS is deprecated in v2.11,
+ * CKA_EC_PARAMS is preferred. */
+#define CKA_ECDSA_PARAMS 0x00000180
+#define CKA_EC_PARAMS 0x00000180
+#define CKA_EC_POINT 0x00000181
+/* CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,
+ * are new for v2.10. Deprecated in v2.11 and onwards. */
+#define CKA_SECONDARY_AUTH 0x00000200
+#define CKA_AUTH_PIN_FLAGS 0x00000201
+/* CKA_ALWAYS_AUTHENTICATE ...
+ * CKA_UNWRAP_TEMPLATE are new for v2.20 */
+#define CKA_ALWAYS_AUTHENTICATE 0x00000202
+#define CKA_WRAP_WITH_TRUSTED 0x00000210
+#define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000211)
+#define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000212)
+/* CKA_OTP... atttributes are new for PKCS #11 v2.20 amendment 3. */
+#define CKA_OTP_FORMAT 0x00000220
+#define CKA_OTP_LENGTH 0x00000221
+#define CKA_OTP_TIME_INTERVAL 0x00000222
+#define CKA_OTP_USER_FRIENDLY_MODE 0x00000223
+#define CKA_OTP_CHALLENGE_REQUIREMENT 0x00000224
+#define CKA_OTP_TIME_REQUIREMENT 0x00000225
+#define CKA_OTP_COUNTER_REQUIREMENT 0x00000226
+#define CKA_OTP_PIN_REQUIREMENT 0x00000227
+#define CKA_OTP_COUNTER 0x0000022E
+#define CKA_OTP_TIME 0x0000022F
+#define CKA_OTP_USER_IDENTIFIER 0x0000022A
+#define CKA_OTP_SERVICE_IDENTIFIER 0x0000022B
+#define CKA_OTP_SERVICE_LOGO 0x0000022C
+#define CKA_OTP_SERVICE_LOGO_TYPE 0x0000022D
+/* CKA_HW_FEATURE_TYPE, CKA_RESET_ON_INIT, and CKA_HAS_RESET
+#define CKA_HW_FEATURE_TYPE 0x00000300
+#define CKA_RESET_ON_INIT 0x00000301
+#define CKA_HAS_RESET 0x00000302
+/* The following attributes are new for v2.20 */
+#define CKA_PIXEL_X 0x00000400
+#define CKA_PIXEL_Y 0x00000401
+#define CKA_RESOLUTION 0x00000402
+#define CKA_CHAR_ROWS 0x00000403
+#define CKA_CHAR_COLUMNS 0x00000404
+#define CKA_COLOR 0x00000405
+#define CKA_BITS_PER_PIXEL 0x00000406
+#define CKA_CHAR_SETS 0x00000480
+#define CKA_ENCODING_METHODS 0x00000481
+#define CKA_MIME_TYPES 0x00000482
+#define CKA_MECHANISM_TYPE 0x00000500
+#define CKA_REQUIRED_CMS_ATTRIBUTES 0x00000501
+#define CKA_DEFAULT_CMS_ATTRIBUTES 0x00000502
+#define CKA_SUPPORTED_CMS_ATTRIBUTES 0x00000503
+#define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE|0x00000600)
+#define CKA_VENDOR_DEFINED 0x80000000
+/* CK_ATTRIBUTE is a structure that includes the type, length
+ * and value of an attribute */
+typedef struct CK_ATTRIBUTE {
+ CK_ATTRIBUTE_TYPE type;
+ /* ulValueLen went from CK_USHORT to CK_ULONG for v2.0 */
+ CK_ULONG ulValueLen; /* in bytes */
+typedef CK_ATTRIBUTE CK_PTR CK_ATTRIBUTE_PTR;
+/* CK_DATE is a structure that defines a date */
+ CK_CHAR year[4]; /* the year ("1900" - "9999") */
+ CK_CHAR month[2]; /* the month ("01" - "12") */
+ CK_CHAR day[2]; /* the day ("01" - "31") */
+/* CK_MECHANISM_TYPE is a value that identifies a mechanism
+/* CK_MECHANISM_TYPE was changed from CK_USHORT to CK_ULONG for
+typedef CK_ULONG CK_MECHANISM_TYPE;
+/* the following mechanism types are defined: */
+#define CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000
+#define CKM_RSA_PKCS 0x00000001
+#define CKM_RSA_9796 0x00000002
+#define CKM_RSA_X_509 0x00000003
+/* CKM_MD2_RSA_PKCS, CKM_MD5_RSA_PKCS, and CKM_SHA1_RSA_PKCS
+ * are new for v2.0. They are mechanisms which hash and sign */
+#define CKM_MD2_RSA_PKCS 0x00000004
+#define CKM_MD5_RSA_PKCS 0x00000005
+#define CKM_SHA1_RSA_PKCS 0x00000006
+/* CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160_RSA_PKCS, and
+ * CKM_RSA_PKCS_OAEP are new for v2.10 */
+#define CKM_RIPEMD128_RSA_PKCS 0x00000007
+#define CKM_RIPEMD160_RSA_PKCS 0x00000008
+#define CKM_RSA_PKCS_OAEP 0x00000009
+/* CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31,
+ * CKM_RSA_PKCS_PSS, and CKM_SHA1_RSA_PKCS_PSS are new for v2.11 */
+#define CKM_RSA_X9_31_KEY_PAIR_GEN 0x0000000A
+#define CKM_RSA_X9_31 0x0000000B
+#define CKM_SHA1_RSA_X9_31 0x0000000C
+#define CKM_RSA_PKCS_PSS 0x0000000D
+#define CKM_SHA1_RSA_PKCS_PSS 0x0000000E
+#define CKM_DSA_KEY_PAIR_GEN 0x00000010
+#define CKM_DSA 0x00000011
+#define CKM_DSA_SHA1 0x00000012
+#define CKM_DH_PKCS_KEY_PAIR_GEN 0x00000020
+#define CKM_DH_PKCS_DERIVE 0x00000021
+/* CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_DERIVE,
+ * CKM_X9_42_DH_HYBRID_DERIVE, and CKM_X9_42_MQV_DERIVE are new for
+#define CKM_X9_42_DH_KEY_PAIR_GEN 0x00000030
+#define CKM_X9_42_DH_DERIVE 0x00000031
+#define CKM_X9_42_DH_HYBRID_DERIVE 0x00000032
+#define CKM_X9_42_MQV_DERIVE 0x00000033
+/* CKM_SHA256/384/512 are new for v2.20 */
+#define CKM_SHA256_RSA_PKCS 0x00000040
+#define CKM_SHA384_RSA_PKCS 0x00000041
+#define CKM_SHA512_RSA_PKCS 0x00000042
+#define CKM_SHA256_RSA_PKCS_PSS 0x00000043
+#define CKM_SHA384_RSA_PKCS_PSS 0x00000044
+#define CKM_SHA512_RSA_PKCS_PSS 0x00000045
+/* SHA-224 RSA mechanisms are new for PKCS #11 v2.20 amendment 3 */
+#define CKM_SHA224_RSA_PKCS 0x00000046
+#define CKM_SHA224_RSA_PKCS_PSS 0x00000047
+#define CKM_RC2_KEY_GEN 0x00000100
+#define CKM_RC2_ECB 0x00000101
+#define CKM_RC2_CBC 0x00000102
+#define CKM_RC2_MAC 0x00000103
+/* CKM_RC2_MAC_GENERAL and CKM_RC2_CBC_PAD are new for v2.0 */
+#define CKM_RC2_MAC_GENERAL 0x00000104
+#define CKM_RC2_CBC_PAD 0x00000105
+#define CKM_RC4_KEY_GEN 0x00000110
+#define CKM_RC4 0x00000111
+#define CKM_DES_KEY_GEN 0x00000120
+#define CKM_DES_ECB 0x00000121
+#define CKM_DES_CBC 0x00000122
+#define CKM_DES_MAC 0x00000123
+/* CKM_DES_MAC_GENERAL and CKM_DES_CBC_PAD are new for v2.0 */
+#define CKM_DES_MAC_GENERAL 0x00000124
+#define CKM_DES_CBC_PAD 0x00000125
+#define CKM_DES2_KEY_GEN 0x00000130
+#define CKM_DES3_KEY_GEN 0x00000131
+#define CKM_DES3_ECB 0x00000132
+#define CKM_DES3_CBC 0x00000133
+#define CKM_DES3_MAC 0x00000134
+/* CKM_DES3_MAC_GENERAL, CKM_DES3_CBC_PAD, CKM_CDMF_KEY_GEN,
+ * CKM_CDMF_ECB, CKM_CDMF_CBC, CKM_CDMF_MAC,
+ * CKM_CDMF_MAC_GENERAL, and CKM_CDMF_CBC_PAD are new for v2.0 */
+#define CKM_DES3_MAC_GENERAL 0x00000135
+#define CKM_DES3_CBC_PAD 0x00000136
+#define CKM_CDMF_KEY_GEN 0x00000140
+#define CKM_CDMF_ECB 0x00000141
+#define CKM_CDMF_CBC 0x00000142
+#define CKM_CDMF_MAC 0x00000143
+#define CKM_CDMF_MAC_GENERAL 0x00000144
+#define CKM_CDMF_CBC_PAD 0x00000145
+/* the following four DES mechanisms are new for v2.20 */
+#define CKM_DES_OFB64 0x00000150
+#define CKM_DES_OFB8 0x00000151
+#define CKM_DES_CFB64 0x00000152
+#define CKM_DES_CFB8 0x00000153
+#define CKM_MD2 0x00000200
+/* CKM_MD2_HMAC and CKM_MD2_HMAC_GENERAL are new for v2.0 */
+#define CKM_MD2_HMAC 0x00000201
+#define CKM_MD2_HMAC_GENERAL 0x00000202
+#define CKM_MD5 0x00000210
+/* CKM_MD5_HMAC and CKM_MD5_HMAC_GENERAL are new for v2.0 */
+#define CKM_MD5_HMAC 0x00000211
+#define CKM_MD5_HMAC_GENERAL 0x00000212
+#define CKM_SHA_1 0x00000220
+/* CKM_SHA_1_HMAC and CKM_SHA_1_HMAC_GENERAL are new for v2.0 */
+#define CKM_SHA_1_HMAC 0x00000221
+#define CKM_SHA_1_HMAC_GENERAL 0x00000222
+/* CKM_RIPEMD128, CKM_RIPEMD128_HMAC,
+ * CKM_RIPEMD128_HMAC_GENERAL, CKM_RIPEMD160, CKM_RIPEMD160_HMAC,
+ * and CKM_RIPEMD160_HMAC_GENERAL are new for v2.10 */
+#define CKM_RIPEMD128 0x00000230
+#define CKM_RIPEMD128_HMAC 0x00000231
+#define CKM_RIPEMD128_HMAC_GENERAL 0x00000232
+#define CKM_RIPEMD160 0x00000240
+#define CKM_RIPEMD160_HMAC 0x00000241
+#define CKM_RIPEMD160_HMAC_GENERAL 0x00000242
+/* CKM_SHA256/384/512 are new for v2.20 */
+#define CKM_SHA256 0x00000250
+#define CKM_SHA256_HMAC 0x00000251
+#define CKM_SHA256_HMAC_GENERAL 0x00000252
+/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_SHA224 0x00000255
+#define CKM_SHA224_HMAC 0x00000256
+#define CKM_SHA224_HMAC_GENERAL 0x00000257
+#define CKM_SHA384 0x00000260
+#define CKM_SHA384_HMAC 0x00000261
+#define CKM_SHA384_HMAC_GENERAL 0x00000262
+#define CKM_SHA512 0x00000270
+#define CKM_SHA512_HMAC 0x00000271
+#define CKM_SHA512_HMAC_GENERAL 0x00000272
+/* SecurID is new for PKCS #11 v2.20 amendment 1 */
+#define CKM_SECURID_KEY_GEN 0x00000280
+#define CKM_SECURID 0x00000282
+/* HOTP is new for PKCS #11 v2.20 amendment 1 */
+#define CKM_HOTP_KEY_GEN 0x00000290
+#define CKM_HOTP 0x00000291
+/* ACTI is new for PKCS #11 v2.20 amendment 1 */
+#define CKM_ACTI 0x000002A0
+#define CKM_ACTI_KEY_GEN 0x000002A1
+/* All of the following mechanisms are new for v2.0 */
+/* Note that CAST128 and CAST5 are the same algorithm */
+#define CKM_CAST_KEY_GEN 0x00000300
+#define CKM_CAST_ECB 0x00000301
+#define CKM_CAST_CBC 0x00000302
+#define CKM_CAST_MAC 0x00000303
+#define CKM_CAST_MAC_GENERAL 0x00000304
+#define CKM_CAST_CBC_PAD 0x00000305
+#define CKM_CAST3_KEY_GEN 0x00000310
+#define CKM_CAST3_ECB 0x00000311
+#define CKM_CAST3_CBC 0x00000312
+#define CKM_CAST3_MAC 0x00000313
+#define CKM_CAST3_MAC_GENERAL 0x00000314
+#define CKM_CAST3_CBC_PAD 0x00000315
+#define CKM_CAST5_KEY_GEN 0x00000320
+#define CKM_CAST128_KEY_GEN 0x00000320
+#define CKM_CAST5_ECB 0x00000321
+#define CKM_CAST128_ECB 0x00000321
+#define CKM_CAST5_CBC 0x00000322
+#define CKM_CAST128_CBC 0x00000322
+#define CKM_CAST5_MAC 0x00000323
+#define CKM_CAST128_MAC 0x00000323
+#define CKM_CAST5_MAC_GENERAL 0x00000324
+#define CKM_CAST128_MAC_GENERAL 0x00000324
+#define CKM_CAST5_CBC_PAD 0x00000325
+#define CKM_CAST128_CBC_PAD 0x00000325
+#define CKM_RC5_KEY_GEN 0x00000330
+#define CKM_RC5_ECB 0x00000331
+#define CKM_RC5_CBC 0x00000332
+#define CKM_RC5_MAC 0x00000333
+#define CKM_RC5_MAC_GENERAL 0x00000334
+#define CKM_RC5_CBC_PAD 0x00000335
+#define CKM_IDEA_KEY_GEN 0x00000340
+#define CKM_IDEA_ECB 0x00000341
+#define CKM_IDEA_CBC 0x00000342
+#define CKM_IDEA_MAC 0x00000343
+#define CKM_IDEA_MAC_GENERAL 0x00000344
+#define CKM_IDEA_CBC_PAD 0x00000345
+#define CKM_GENERIC_SECRET_KEY_GEN 0x00000350
+#define CKM_CONCATENATE_BASE_AND_KEY 0x00000360
+#define CKM_CONCATENATE_BASE_AND_DATA 0x00000362
+#define CKM_CONCATENATE_DATA_AND_BASE 0x00000363
+#define CKM_XOR_BASE_AND_DATA 0x00000364
+#define CKM_EXTRACT_KEY_FROM_KEY 0x00000365
+#define CKM_SSL3_PRE_MASTER_KEY_GEN 0x00000370
+#define CKM_SSL3_MASTER_KEY_DERIVE 0x00000371
+#define CKM_SSL3_KEY_AND_MAC_DERIVE 0x00000372
+/* CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_PRE_MASTER_KEY_GEN,
+ * CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE, and
+ * CKM_TLS_MASTER_KEY_DERIVE_DH are new for v2.11 */
+#define CKM_SSL3_MASTER_KEY_DERIVE_DH 0x00000373
+#define CKM_TLS_PRE_MASTER_KEY_GEN 0x00000374
+#define CKM_TLS_MASTER_KEY_DERIVE 0x00000375
+#define CKM_TLS_KEY_AND_MAC_DERIVE 0x00000376
+#define CKM_TLS_MASTER_KEY_DERIVE_DH 0x00000377
+/* CKM_TLS_PRF is new for v2.20 */
+#define CKM_TLS_PRF 0x00000378
+#define CKM_SSL3_MD5_MAC 0x00000380
+#define CKM_SSL3_SHA1_MAC 0x00000381
+#define CKM_MD5_KEY_DERIVATION 0x00000390
+#define CKM_MD2_KEY_DERIVATION 0x00000391
+#define CKM_SHA1_KEY_DERIVATION 0x00000392
+/* CKM_SHA256/384/512 are new for v2.20 */
+#define CKM_SHA256_KEY_DERIVATION 0x00000393
+#define CKM_SHA384_KEY_DERIVATION 0x00000394
+#define CKM_SHA512_KEY_DERIVATION 0x00000395
+/* SHA-224 key derivation is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_SHA224_KEY_DERIVATION 0x00000396
+#define CKM_PBE_MD2_DES_CBC 0x000003A0
+#define CKM_PBE_MD5_DES_CBC 0x000003A1
+#define CKM_PBE_MD5_CAST_CBC 0x000003A2
+#define CKM_PBE_MD5_CAST3_CBC 0x000003A3
+#define CKM_PBE_MD5_CAST5_CBC 0x000003A4
+#define CKM_PBE_MD5_CAST128_CBC 0x000003A4
+#define CKM_PBE_SHA1_CAST5_CBC 0x000003A5
+#define CKM_PBE_SHA1_CAST128_CBC 0x000003A5
+#define CKM_PBE_SHA1_RC4_128 0x000003A6
+#define CKM_PBE_SHA1_RC4_40 0x000003A7
+#define CKM_PBE_SHA1_DES3_EDE_CBC 0x000003A8
+#define CKM_PBE_SHA1_DES2_EDE_CBC 0x000003A9
+#define CKM_PBE_SHA1_RC2_128_CBC 0x000003AA
+#define CKM_PBE_SHA1_RC2_40_CBC 0x000003AB
+/* CKM_PKCS5_PBKD2 is new for v2.10 */
+#define CKM_PKCS5_PBKD2 0x000003B0
+#define CKM_PBA_SHA1_WITH_SHA1_HMAC 0x000003C0
+/* WTLS mechanisms are new for v2.20 */
+#define CKM_WTLS_PRE_MASTER_KEY_GEN 0x000003D0
+#define CKM_WTLS_MASTER_KEY_DERIVE 0x000003D1
+#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC 0x000003D2
+#define CKM_WTLS_PRF 0x000003D3
+#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE 0x000003D4
+#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE 0x000003D5
+#define CKM_KEY_WRAP_LYNKS 0x00000400
+#define CKM_KEY_WRAP_SET_OAEP 0x00000401
+/* CKM_CMS_SIG is new for v2.20 */
+#define CKM_CMS_SIG 0x00000500
+/* CKM_KIP mechanisms are new for PKCS #11 v2.20 amendment 2 */
+#define CKM_KIP_DERIVE 0x00000510
+#define CKM_KIP_WRAP 0x00000511
+#define CKM_KIP_MAC 0x00000512
+/* Camellia is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_CAMELLIA_KEY_GEN 0x00000550
+#define CKM_CAMELLIA_ECB 0x00000551
+#define CKM_CAMELLIA_CBC 0x00000552
+#define CKM_CAMELLIA_MAC 0x00000553
+#define CKM_CAMELLIA_MAC_GENERAL 0x00000554
+#define CKM_CAMELLIA_CBC_PAD 0x00000555
+#define CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556
+#define CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557
+#define CKM_CAMELLIA_CTR 0x00000558
+/* ARIA is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_ARIA_KEY_GEN 0x00000560
+#define CKM_ARIA_ECB 0x00000561
+#define CKM_ARIA_CBC 0x00000562
+#define CKM_ARIA_MAC 0x00000563
+#define CKM_ARIA_MAC_GENERAL 0x00000564
+#define CKM_ARIA_CBC_PAD 0x00000565
+#define CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566
+#define CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567
+/* Fortezza mechanisms */
+#define CKM_SKIPJACK_KEY_GEN 0x00001000
+#define CKM_SKIPJACK_ECB64 0x00001001
+#define CKM_SKIPJACK_CBC64 0x00001002
+#define CKM_SKIPJACK_OFB64 0x00001003
+#define CKM_SKIPJACK_CFB64 0x00001004
+#define CKM_SKIPJACK_CFB32 0x00001005
+#define CKM_SKIPJACK_CFB16 0x00001006
+#define CKM_SKIPJACK_CFB8 0x00001007
+#define CKM_SKIPJACK_WRAP 0x00001008
+#define CKM_SKIPJACK_PRIVATE_WRAP 0x00001009
+#define CKM_SKIPJACK_RELAYX 0x0000100a
+#define CKM_KEA_KEY_PAIR_GEN 0x00001010
+#define CKM_KEA_KEY_DERIVE 0x00001011
+#define CKM_FORTEZZA_TIMESTAMP 0x00001020
+#define CKM_BATON_KEY_GEN 0x00001030
+#define CKM_BATON_ECB128 0x00001031
+#define CKM_BATON_ECB96 0x00001032
+#define CKM_BATON_CBC128 0x00001033
+#define CKM_BATON_COUNTER 0x00001034
+#define CKM_BATON_SHUFFLE 0x00001035
+#define CKM_BATON_WRAP 0x00001036
+/* CKM_ECDSA_KEY_PAIR_GEN is deprecated in v2.11,
+ * CKM_EC_KEY_PAIR_GEN is preferred */
+#define CKM_ECDSA_KEY_PAIR_GEN 0x00001040
+#define CKM_EC_KEY_PAIR_GEN 0x00001040
+#define CKM_ECDSA 0x00001041
+#define CKM_ECDSA_SHA1 0x00001042
+/* CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, and CKM_ECMQV_DERIVE
+#define CKM_ECDH1_DERIVE 0x00001050
+#define CKM_ECDH1_COFACTOR_DERIVE 0x00001051
+#define CKM_ECMQV_DERIVE 0x00001052
+#define CKM_JUNIPER_KEY_GEN 0x00001060
+#define CKM_JUNIPER_ECB128 0x00001061
+#define CKM_JUNIPER_CBC128 0x00001062
+#define CKM_JUNIPER_COUNTER 0x00001063
+#define CKM_JUNIPER_SHUFFLE 0x00001064
+#define CKM_JUNIPER_WRAP 0x00001065
+#define CKM_FASTHASH 0x00001070
+/* CKM_AES_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_MAC,
+ * CKM_AES_MAC_GENERAL, CKM_AES_CBC_PAD, CKM_DSA_PARAMETER_GEN,
+ * CKM_DH_PKCS_PARAMETER_GEN, and CKM_X9_42_DH_PARAMETER_GEN are
+#define CKM_AES_KEY_GEN 0x00001080
+#define CKM_AES_ECB 0x00001081
+#define CKM_AES_CBC 0x00001082
+#define CKM_AES_MAC 0x00001083
+#define CKM_AES_MAC_GENERAL 0x00001084
+#define CKM_AES_CBC_PAD 0x00001085
+/* AES counter mode is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_AES_CTR 0x00001086
+/* BlowFish and TwoFish are new for v2.20 */
+#define CKM_BLOWFISH_KEY_GEN 0x00001090
+#define CKM_BLOWFISH_CBC 0x00001091
+#define CKM_TWOFISH_KEY_GEN 0x00001092
+#define CKM_TWOFISH_CBC 0x00001093
+/* CKM_xxx_ENCRYPT_DATA mechanisms are new for v2.20 */
+#define CKM_DES_ECB_ENCRYPT_DATA 0x00001100
+#define CKM_DES_CBC_ENCRYPT_DATA 0x00001101
+#define CKM_DES3_ECB_ENCRYPT_DATA 0x00001102
+#define CKM_DES3_CBC_ENCRYPT_DATA 0x00001103
+#define CKM_AES_ECB_ENCRYPT_DATA 0x00001104
+#define CKM_AES_CBC_ENCRYPT_DATA 0x00001105
+#define CKM_DSA_PARAMETER_GEN 0x00002000
+#define CKM_DH_PKCS_PARAMETER_GEN 0x00002001
+#define CKM_X9_42_DH_PARAMETER_GEN 0x00002002
+#define CKM_VENDOR_DEFINED 0x80000000
+typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR;
+/* CK_MECHANISM is a structure that specifies a particular
+typedef struct CK_MECHANISM {
+ CK_MECHANISM_TYPE mechanism;
+ CK_VOID_PTR pParameter;
+ /* ulParameterLen was changed from CK_USHORT to CK_ULONG for
+ CK_ULONG ulParameterLen; /* in bytes */
+typedef CK_MECHANISM CK_PTR CK_MECHANISM_PTR;
+/* CK_MECHANISM_INFO provides information about a particular
+typedef struct CK_MECHANISM_INFO {
+/* The flags are defined as follows:
+ * Bit Flag Mask Meaning */
+#define CKF_HW 0x00000001 /* performed by HW */
+/* The flags CKF_ENCRYPT, CKF_DECRYPT, CKF_DIGEST, CKF_SIGN,
+ * CKG_SIGN_RECOVER, CKF_VERIFY, CKF_VERIFY_RECOVER,
+ * CKF_GENERATE, CKF_GENERATE_KEY_PAIR, CKF_WRAP, CKF_UNWRAP,
+ * and CKF_DERIVE are new for v2.0. They specify whether or not
+ * a mechanism can be used for a particular task */
+#define CKF_ENCRYPT 0x00000100
+#define CKF_DECRYPT 0x00000200
+#define CKF_DIGEST 0x00000400
+#define CKF_SIGN 0x00000800
+#define CKF_SIGN_RECOVER 0x00001000
+#define CKF_VERIFY 0x00002000
+#define CKF_VERIFY_RECOVER 0x00004000
+#define CKF_GENERATE 0x00008000
+#define CKF_GENERATE_KEY_PAIR 0x00010000
+#define CKF_WRAP 0x00020000
+#define CKF_UNWRAP 0x00040000
+#define CKF_DERIVE 0x00080000
+/* CKF_EC_F_P, CKF_EC_F_2M, CKF_EC_ECPARAMETERS, CKF_EC_NAMEDCURVE,
+ * CKF_EC_UNCOMPRESS, and CKF_EC_COMPRESS are new for v2.11. They
+ * describe a token's EC capabilities not available in mechanism
+#define CKF_EC_F_P 0x00100000
+#define CKF_EC_F_2M 0x00200000
+#define CKF_EC_ECPARAMETERS 0x00400000
+#define CKF_EC_NAMEDCURVE 0x00800000
+#define CKF_EC_UNCOMPRESS 0x01000000
+#define CKF_EC_COMPRESS 0x02000000
+#define CKF_EXTENSION 0x80000000 /* FALSE for this version */
+typedef CK_MECHANISM_INFO CK_PTR CK_MECHANISM_INFO_PTR;
+/* CK_RV is a value that identifies the return value of a
+/* CK_RV was changed from CK_USHORT to CK_ULONG for v2.0 */
+#define CKR_OK 0x00000000
+#define CKR_CANCEL 0x00000001
+#define CKR_HOST_MEMORY 0x00000002
+#define CKR_SLOT_ID_INVALID 0x00000003
+/* CKR_FLAGS_INVALID was removed for v2.0 */
+/* CKR_GENERAL_ERROR and CKR_FUNCTION_FAILED are new for v2.0 */
+#define CKR_GENERAL_ERROR 0x00000005
+#define CKR_FUNCTION_FAILED 0x00000006
+/* CKR_ARGUMENTS_BAD, CKR_NO_EVENT, CKR_NEED_TO_CREATE_THREADS,
+ * and CKR_CANT_LOCK are new for v2.01 */
+#define CKR_ARGUMENTS_BAD 0x00000007
+#define CKR_NO_EVENT 0x00000008
+#define CKR_NEED_TO_CREATE_THREADS 0x00000009
+#define CKR_CANT_LOCK 0x0000000A
+#define CKR_ATTRIBUTE_READ_ONLY 0x00000010
+#define CKR_ATTRIBUTE_SENSITIVE 0x00000011
+#define CKR_ATTRIBUTE_TYPE_INVALID 0x00000012
+#define CKR_ATTRIBUTE_VALUE_INVALID 0x00000013
+#define CKR_DATA_INVALID 0x00000020
+#define CKR_DATA_LEN_RANGE 0x00000021
+#define CKR_DEVICE_ERROR 0x00000030
+#define CKR_DEVICE_MEMORY 0x00000031
+#define CKR_DEVICE_REMOVED 0x00000032
+#define CKR_ENCRYPTED_DATA_INVALID 0x00000040
+#define CKR_ENCRYPTED_DATA_LEN_RANGE 0x00000041
+#define CKR_FUNCTION_CANCELED 0x00000050
+#define CKR_FUNCTION_NOT_PARALLEL 0x00000051
+/* CKR_FUNCTION_NOT_SUPPORTED is new for v2.0 */
+#define CKR_FUNCTION_NOT_SUPPORTED 0x00000054
+#define CKR_KEY_HANDLE_INVALID 0x00000060
+/* CKR_KEY_SENSITIVE was removed for v2.0 */
+#define CKR_KEY_SIZE_RANGE 0x00000062
+#define CKR_KEY_TYPE_INCONSISTENT 0x00000063
+/* CKR_KEY_NOT_NEEDED, CKR_KEY_CHANGED, CKR_KEY_NEEDED,
+ * CKR_KEY_INDIGESTIBLE, CKR_KEY_FUNCTION_NOT_PERMITTED,
+ * CKR_KEY_NOT_WRAPPABLE, and CKR_KEY_UNEXTRACTABLE are new for
+#define CKR_KEY_NOT_NEEDED 0x00000064
+#define CKR_KEY_CHANGED 0x00000065
+#define CKR_KEY_NEEDED 0x00000066
+#define CKR_KEY_INDIGESTIBLE 0x00000067
+#define CKR_KEY_FUNCTION_NOT_PERMITTED 0x00000068
+#define CKR_KEY_NOT_WRAPPABLE 0x00000069
+#define CKR_KEY_UNEXTRACTABLE 0x0000006A
+#define CKR_MECHANISM_INVALID 0x00000070
+#define CKR_MECHANISM_PARAM_INVALID 0x00000071
+/* CKR_OBJECT_CLASS_INCONSISTENT and CKR_OBJECT_CLASS_INVALID
+ * were removed for v2.0 */
+#define CKR_OBJECT_HANDLE_INVALID 0x00000082
+#define CKR_OPERATION_ACTIVE 0x00000090
+#define CKR_OPERATION_NOT_INITIALIZED 0x00000091
+#define CKR_PIN_INCORRECT 0x000000A0
+#define CKR_PIN_INVALID 0x000000A1
+#define CKR_PIN_LEN_RANGE 0x000000A2
+/* CKR_PIN_EXPIRED and CKR_PIN_LOCKED are new for v2.0 */
+#define CKR_PIN_EXPIRED 0x000000A3
+#define CKR_PIN_LOCKED 0x000000A4
+#define CKR_SESSION_CLOSED 0x000000B0
+#define CKR_SESSION_COUNT 0x000000B1
+#define CKR_SESSION_HANDLE_INVALID 0x000000B3
+#define CKR_SESSION_PARALLEL_NOT_SUPPORTED 0x000000B4
+#define CKR_SESSION_READ_ONLY 0x000000B5
+#define CKR_SESSION_EXISTS 0x000000B6
+/* CKR_SESSION_READ_ONLY_EXISTS and
+ * CKR_SESSION_READ_WRITE_SO_EXISTS are new for v2.0 */
+#define CKR_SESSION_READ_ONLY_EXISTS 0x000000B7
+#define CKR_SESSION_READ_WRITE_SO_EXISTS 0x000000B8
+#define CKR_SIGNATURE_INVALID 0x000000C0
+#define CKR_SIGNATURE_LEN_RANGE 0x000000C1
+#define CKR_TEMPLATE_INCOMPLETE 0x000000D0
+#define CKR_TEMPLATE_INCONSISTENT 0x000000D1
+#define CKR_TOKEN_NOT_PRESENT 0x000000E0
+#define CKR_TOKEN_NOT_RECOGNIZED 0x000000E1
+#define CKR_TOKEN_WRITE_PROTECTED 0x000000E2
+#define CKR_UNWRAPPING_KEY_HANDLE_INVALID 0x000000F0
+#define CKR_UNWRAPPING_KEY_SIZE_RANGE 0x000000F1
+#define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT 0x000000F2
+#define CKR_USER_ALREADY_LOGGED_IN 0x00000100
+#define CKR_USER_NOT_LOGGED_IN 0x00000101
+#define CKR_USER_PIN_NOT_INITIALIZED 0x00000102
+#define CKR_USER_TYPE_INVALID 0x00000103
+/* CKR_USER_ANOTHER_ALREADY_LOGGED_IN and CKR_USER_TOO_MANY_TYPES
+#define CKR_USER_ANOTHER_ALREADY_LOGGED_IN 0x00000104
+#define CKR_USER_TOO_MANY_TYPES 0x00000105
+#define CKR_WRAPPED_KEY_INVALID 0x00000110
+#define CKR_WRAPPED_KEY_LEN_RANGE 0x00000112
+#define CKR_WRAPPING_KEY_HANDLE_INVALID 0x00000113
+#define CKR_WRAPPING_KEY_SIZE_RANGE 0x00000114
+#define CKR_WRAPPING_KEY_TYPE_INCONSISTENT 0x00000115
+#define CKR_RANDOM_SEED_NOT_SUPPORTED 0x00000120
+/* These are new to v2.0 */
+#define CKR_RANDOM_NO_RNG 0x00000121
+/* These are new to v2.11 */
+#define CKR_DOMAIN_PARAMS_INVALID 0x00000130
+/* These are new to v2.0 */
+#define CKR_BUFFER_TOO_SMALL 0x00000150
+#define CKR_SAVED_STATE_INVALID 0x00000160
+#define CKR_INFORMATION_SENSITIVE 0x00000170
+#define CKR_STATE_UNSAVEABLE 0x00000180
+/* These are new to v2.01 */
+#define CKR_CRYPTOKI_NOT_INITIALIZED 0x00000190
+#define CKR_CRYPTOKI_ALREADY_INITIALIZED 0x00000191
+#define CKR_MUTEX_BAD 0x000001A0
+#define CKR_MUTEX_NOT_LOCKED 0x000001A1
+/* The following return values are new for PKCS #11 v2.20 amendment 3 */
+#define CKR_NEW_PIN_MODE 0x000001B0
+#define CKR_NEXT_OTP 0x000001B1
+/* This is new to v2.20 */
+#define CKR_FUNCTION_REJECTED 0x00000200
+#define CKR_VENDOR_DEFINED 0x80000000
+/* CK_NOTIFY is an application callback that processes events */
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_NOTIFY)(
+ CK_SESSION_HANDLE hSession, /* the session's handle */
+ CK_VOID_PTR pApplication /* passed to C_OpenSession */
+/* CK_FUNCTION_LIST is a structure holding a Cryptoki spec
+ * version and pointers of appropriate types to all the
+ * Cryptoki functions */
+/* CK_FUNCTION_LIST is new for v2.0 */
+typedef struct CK_FUNCTION_LIST CK_FUNCTION_LIST;
+typedef CK_FUNCTION_LIST CK_PTR CK_FUNCTION_LIST_PTR;
+typedef CK_FUNCTION_LIST_PTR CK_PTR CK_FUNCTION_LIST_PTR_PTR;
+/* CK_CREATEMUTEX is an application callback for creating a
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_CREATEMUTEX)(
+ CK_VOID_PTR_PTR ppMutex /* location to receive ptr to mutex */
+/* CK_DESTROYMUTEX is an application callback for destroying a
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_DESTROYMUTEX)(
+ CK_VOID_PTR pMutex /* pointer to mutex */
+/* CK_LOCKMUTEX is an application callback for locking a mutex */
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_LOCKMUTEX)(
+ CK_VOID_PTR pMutex /* pointer to mutex */
+/* CK_UNLOCKMUTEX is an application callback for unlocking a
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_UNLOCKMUTEX)(
+ CK_VOID_PTR pMutex /* pointer to mutex */
+/* CK_C_INITIALIZE_ARGS provides the optional arguments to
+typedef struct CK_C_INITIALIZE_ARGS {
+ CK_CREATEMUTEX CreateMutex;
+ CK_DESTROYMUTEX DestroyMutex;
+ CK_LOCKMUTEX LockMutex;
+ CK_UNLOCKMUTEX UnlockMutex;
+/* flags: bit flags that provide capabilities of the slot
+ * Bit Flag Mask Meaning
+#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001
+#define CKF_OS_LOCKING_OK 0x00000002
+typedef CK_C_INITIALIZE_ARGS CK_PTR CK_C_INITIALIZE_ARGS_PTR;
+/* additional flags for parameters to functions */
+/* CKF_DONT_BLOCK is for the function C_WaitForSlotEvent */
+#define CKF_DONT_BLOCK 1
+/* CK_RSA_PKCS_OAEP_MGF_TYPE is new for v2.10.
+ * CK_RSA_PKCS_OAEP_MGF_TYPE is used to indicate the Message
+ * Generation Function (MGF) applied to a message block when
+ * formatting a message block for the PKCS #1 OAEP encryption
+typedef CK_ULONG CK_RSA_PKCS_MGF_TYPE;
+typedef CK_RSA_PKCS_MGF_TYPE CK_PTR CK_RSA_PKCS_MGF_TYPE_PTR;
+/* The following MGFs are defined */
+/* CKG_MGF1_SHA256, CKG_MGF1_SHA384, and CKG_MGF1_SHA512
+#define CKG_MGF1_SHA1 0x00000001
+#define CKG_MGF1_SHA256 0x00000002
+#define CKG_MGF1_SHA384 0x00000003
+#define CKG_MGF1_SHA512 0x00000004
+/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */
+#define CKG_MGF1_SHA224 0x00000005
+/* CK_RSA_PKCS_OAEP_SOURCE_TYPE is new for v2.10.
+ * CK_RSA_PKCS_OAEP_SOURCE_TYPE is used to indicate the source
+ * of the encoding parameter when formatting a message block
+ * for the PKCS #1 OAEP encryption scheme. */
+typedef CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE;
+typedef CK_RSA_PKCS_OAEP_SOURCE_TYPE CK_PTR CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR;
+/* The following encoding parameter sources are defined */
+#define CKZ_DATA_SPECIFIED 0x00000001
+/* CK_RSA_PKCS_OAEP_PARAMS is new for v2.10.
+ * CK_RSA_PKCS_OAEP_PARAMS provides the parameters to the
+ * CKM_RSA_PKCS_OAEP mechanism. */
+typedef struct CK_RSA_PKCS_OAEP_PARAMS {
+ CK_MECHANISM_TYPE hashAlg;
+ CK_RSA_PKCS_MGF_TYPE mgf;
+ CK_RSA_PKCS_OAEP_SOURCE_TYPE source;
+ CK_VOID_PTR pSourceData;
+ CK_ULONG ulSourceDataLen;
+} CK_RSA_PKCS_OAEP_PARAMS;
+typedef CK_RSA_PKCS_OAEP_PARAMS CK_PTR CK_RSA_PKCS_OAEP_PARAMS_PTR;
+/* CK_RSA_PKCS_PSS_PARAMS is new for v2.11.
+ * CK_RSA_PKCS_PSS_PARAMS provides the parameters to the
+ * CKM_RSA_PKCS_PSS mechanism(s). */
+typedef struct CK_RSA_PKCS_PSS_PARAMS {
+ CK_MECHANISM_TYPE hashAlg;
+ CK_RSA_PKCS_MGF_TYPE mgf;
+} CK_RSA_PKCS_PSS_PARAMS;
+typedef CK_RSA_PKCS_PSS_PARAMS CK_PTR CK_RSA_PKCS_PSS_PARAMS_PTR;
+/* CK_EC_KDF_TYPE is new for v2.11. */
+typedef CK_ULONG CK_EC_KDF_TYPE;
+/* The following EC Key Derivation Functions are defined */
+#define CKD_NULL 0x00000001
+#define CKD_SHA1_KDF 0x00000002
+/* CK_ECDH1_DERIVE_PARAMS is new for v2.11.
+ * CK_ECDH1_DERIVE_PARAMS provides the parameters to the
+ * CKM_ECDH1_DERIVE and CKM_ECDH1_COFACTOR_DERIVE mechanisms,
+ * where each party contributes one key pair.
+typedef struct CK_ECDH1_DERIVE_PARAMS {
+ CK_ULONG ulSharedDataLen;
+ CK_BYTE_PTR pSharedData;
+ CK_ULONG ulPublicDataLen;
+ CK_BYTE_PTR pPublicData;
+} CK_ECDH1_DERIVE_PARAMS;
+typedef CK_ECDH1_DERIVE_PARAMS CK_PTR CK_ECDH1_DERIVE_PARAMS_PTR;
+/* CK_ECDH2_DERIVE_PARAMS is new for v2.11.
+ * CK_ECDH2_DERIVE_PARAMS provides the parameters to the
+ * CKM_ECMQV_DERIVE mechanism, where each party contributes two key pairs. */
+typedef struct CK_ECDH2_DERIVE_PARAMS {
+ CK_ULONG ulSharedDataLen;
+ CK_BYTE_PTR pSharedData;
+ CK_ULONG ulPublicDataLen;
+ CK_BYTE_PTR pPublicData;
+ CK_ULONG ulPrivateDataLen;
+ CK_OBJECT_HANDLE hPrivateData;
+ CK_ULONG ulPublicDataLen2;
+ CK_BYTE_PTR pPublicData2;
+} CK_ECDH2_DERIVE_PARAMS;
+typedef CK_ECDH2_DERIVE_PARAMS CK_PTR CK_ECDH2_DERIVE_PARAMS_PTR;
+typedef struct CK_ECMQV_DERIVE_PARAMS {
+ CK_ULONG ulSharedDataLen;
+ CK_BYTE_PTR pSharedData;
+ CK_ULONG ulPublicDataLen;
+ CK_BYTE_PTR pPublicData;
+ CK_ULONG ulPrivateDataLen;
+ CK_OBJECT_HANDLE hPrivateData;
+ CK_ULONG ulPublicDataLen2;
+ CK_BYTE_PTR pPublicData2;
+ CK_OBJECT_HANDLE publicKey;
+} CK_ECMQV_DERIVE_PARAMS;
+typedef CK_ECMQV_DERIVE_PARAMS CK_PTR CK_ECMQV_DERIVE_PARAMS_PTR;
+/* Typedefs and defines for the CKM_X9_42_DH_KEY_PAIR_GEN and the
+ * CKM_X9_42_DH_PARAMETER_GEN mechanisms (new for PKCS #11 v2.11) */
+typedef CK_ULONG CK_X9_42_DH_KDF_TYPE;
+typedef CK_X9_42_DH_KDF_TYPE CK_PTR CK_X9_42_DH_KDF_TYPE_PTR;
+/* The following X9.42 DH key derivation functions are defined
+ (besides CKD_NULL already defined : */
+#define CKD_SHA1_KDF_ASN1 0x00000003
+#define CKD_SHA1_KDF_CONCATENATE 0x00000004
+/* CK_X9_42_DH1_DERIVE_PARAMS is new for v2.11.
+ * CK_X9_42_DH1_DERIVE_PARAMS provides the parameters to the
+ * CKM_X9_42_DH_DERIVE key derivation mechanism, where each party
+ * contributes one key pair */
+typedef struct CK_X9_42_DH1_DERIVE_PARAMS {
+ CK_X9_42_DH_KDF_TYPE kdf;
+ CK_ULONG ulOtherInfoLen;
+ CK_BYTE_PTR pOtherInfo;
+ CK_ULONG ulPublicDataLen;
+ CK_BYTE_PTR pPublicData;
+} CK_X9_42_DH1_DERIVE_PARAMS;
+typedef struct CK_X9_42_DH1_DERIVE_PARAMS CK_PTR CK_X9_42_DH1_DERIVE_PARAMS_PTR;
+/* CK_X9_42_DH2_DERIVE_PARAMS is new for v2.11.
+ * CK_X9_42_DH2_DERIVE_PARAMS provides the parameters to the
+ * CKM_X9_42_DH_HYBRID_DERIVE and CKM_X9_42_MQV_DERIVE key derivation
+ * mechanisms, where each party contributes two key pairs */
+typedef struct CK_X9_42_DH2_DERIVE_PARAMS {
+ CK_X9_42_DH_KDF_TYPE kdf;
+ CK_ULONG ulOtherInfoLen;
+ CK_BYTE_PTR pOtherInfo;
+ CK_ULONG ulPublicDataLen;
+ CK_BYTE_PTR pPublicData;
+ CK_ULONG ulPrivateDataLen;
+ CK_OBJECT_HANDLE hPrivateData;
+ CK_ULONG ulPublicDataLen2;
+ CK_BYTE_PTR pPublicData2;
+} CK_X9_42_DH2_DERIVE_PARAMS;
+typedef CK_X9_42_DH2_DERIVE_PARAMS CK_PTR CK_X9_42_DH2_DERIVE_PARAMS_PTR;
+typedef struct CK_X9_42_MQV_DERIVE_PARAMS {
+ CK_X9_42_DH_KDF_TYPE kdf;
+ CK_ULONG ulOtherInfoLen;
+ CK_BYTE_PTR pOtherInfo;
+ CK_ULONG ulPublicDataLen;
+ CK_BYTE_PTR pPublicData;
+ CK_ULONG ulPrivateDataLen;
+ CK_OBJECT_HANDLE hPrivateData;
+ CK_ULONG ulPublicDataLen2;
+ CK_BYTE_PTR pPublicData2;
+ CK_OBJECT_HANDLE publicKey;
+} CK_X9_42_MQV_DERIVE_PARAMS;
+typedef CK_X9_42_MQV_DERIVE_PARAMS CK_PTR CK_X9_42_MQV_DERIVE_PARAMS_PTR;
+/* CK_KEA_DERIVE_PARAMS provides the parameters to the
+ * CKM_KEA_DERIVE mechanism */
+/* CK_KEA_DERIVE_PARAMS is new for v2.0 */
+typedef struct CK_KEA_DERIVE_PARAMS {
+ CK_ULONG ulPublicDataLen;
+ CK_BYTE_PTR pPublicData;
+typedef CK_KEA_DERIVE_PARAMS CK_PTR CK_KEA_DERIVE_PARAMS_PTR;
+/* CK_RC2_PARAMS provides the parameters to the CKM_RC2_ECB and
+ * CKM_RC2_MAC mechanisms. An instance of CK_RC2_PARAMS just
+ * holds the effective keysize */
+typedef CK_ULONG CK_RC2_PARAMS;
+typedef CK_RC2_PARAMS CK_PTR CK_RC2_PARAMS_PTR;
+/* CK_RC2_CBC_PARAMS provides the parameters to the CKM_RC2_CBC
+typedef struct CK_RC2_CBC_PARAMS {
+ /* ulEffectiveBits was changed from CK_USHORT to CK_ULONG for
+ CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */
+ CK_BYTE iv[8]; /* IV for CBC mode */
+typedef CK_RC2_CBC_PARAMS CK_PTR CK_RC2_CBC_PARAMS_PTR;
+/* CK_RC2_MAC_GENERAL_PARAMS provides the parameters for the
+ * CKM_RC2_MAC_GENERAL mechanism */
+/* CK_RC2_MAC_GENERAL_PARAMS is new for v2.0 */
+typedef struct CK_RC2_MAC_GENERAL_PARAMS {
+ CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */
+ CK_ULONG ulMacLength; /* Length of MAC in bytes */
+} CK_RC2_MAC_GENERAL_PARAMS;
+typedef CK_RC2_MAC_GENERAL_PARAMS CK_PTR \
+ CK_RC2_MAC_GENERAL_PARAMS_PTR;
+/* CK_RC5_PARAMS provides the parameters to the CKM_RC5_ECB and
+ * CKM_RC5_MAC mechanisms */
+/* CK_RC5_PARAMS is new for v2.0 */
+typedef struct CK_RC5_PARAMS {
+ CK_ULONG ulWordsize; /* wordsize in bits */
+ CK_ULONG ulRounds; /* number of rounds */
+typedef CK_RC5_PARAMS CK_PTR CK_RC5_PARAMS_PTR;
+/* CK_RC5_CBC_PARAMS provides the parameters to the CKM_RC5_CBC
+/* CK_RC5_CBC_PARAMS is new for v2.0 */
+typedef struct CK_RC5_CBC_PARAMS {
+ CK_ULONG ulWordsize; /* wordsize in bits */
+ CK_ULONG ulRounds; /* number of rounds */
+ CK_BYTE_PTR pIv; /* pointer to IV */
+ CK_ULONG ulIvLen; /* length of IV in bytes */
+typedef CK_RC5_CBC_PARAMS CK_PTR CK_RC5_CBC_PARAMS_PTR;
+/* CK_RC5_MAC_GENERAL_PARAMS provides the parameters for the
+ * CKM_RC5_MAC_GENERAL mechanism */
+/* CK_RC5_MAC_GENERAL_PARAMS is new for v2.0 */
+typedef struct CK_RC5_MAC_GENERAL_PARAMS {
+ CK_ULONG ulWordsize; /* wordsize in bits */
+ CK_ULONG ulRounds; /* number of rounds */
+ CK_ULONG ulMacLength; /* Length of MAC in bytes */
+} CK_RC5_MAC_GENERAL_PARAMS;
+typedef CK_RC5_MAC_GENERAL_PARAMS CK_PTR \
+ CK_RC5_MAC_GENERAL_PARAMS_PTR;
+/* CK_MAC_GENERAL_PARAMS provides the parameters to most block
+ * ciphers' MAC_GENERAL mechanisms. Its value is the length of
+/* CK_MAC_GENERAL_PARAMS is new for v2.0 */
+typedef CK_ULONG CK_MAC_GENERAL_PARAMS;
+typedef CK_MAC_GENERAL_PARAMS CK_PTR CK_MAC_GENERAL_PARAMS_PTR;
+typedef struct CK_DES_CBC_ENCRYPT_DATA_PARAMS {
+} CK_DES_CBC_ENCRYPT_DATA_PARAMS;
+typedef CK_DES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+typedef struct CK_AES_CBC_ENCRYPT_DATA_PARAMS {
+} CK_AES_CBC_ENCRYPT_DATA_PARAMS;
+typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS provides the parameters to the
+ * CKM_SKIPJACK_PRIVATE_WRAP mechanism */
+/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS is new for v2.0 */
+typedef struct CK_SKIPJACK_PRIVATE_WRAP_PARAMS {
+ CK_ULONG ulPasswordLen;
+ CK_ULONG ulPublicDataLen;
+ CK_BYTE_PTR pPublicData;
+ CK_BYTE_PTR pSubprimeQ;
+} CK_SKIPJACK_PRIVATE_WRAP_PARAMS;
+typedef CK_SKIPJACK_PRIVATE_WRAP_PARAMS CK_PTR \
+ CK_SKIPJACK_PRIVATE_WRAP_PTR;
+/* CK_SKIPJACK_RELAYX_PARAMS provides the parameters to the
+ * CKM_SKIPJACK_RELAYX mechanism */
+/* CK_SKIPJACK_RELAYX_PARAMS is new for v2.0 */
+typedef struct CK_SKIPJACK_RELAYX_PARAMS {
+ CK_ULONG ulOldWrappedXLen;
+ CK_BYTE_PTR pOldWrappedX;
+ CK_ULONG ulOldPasswordLen;
+ CK_BYTE_PTR pOldPassword;
+ CK_ULONG ulOldPublicDataLen;
+ CK_BYTE_PTR pOldPublicData;
+ CK_ULONG ulOldRandomLen;
+ CK_BYTE_PTR pOldRandomA;
+ CK_ULONG ulNewPasswordLen;
+ CK_BYTE_PTR pNewPassword;
+ CK_ULONG ulNewPublicDataLen;
+ CK_BYTE_PTR pNewPublicData;
+ CK_ULONG ulNewRandomLen;
+ CK_BYTE_PTR pNewRandomA;
+} CK_SKIPJACK_RELAYX_PARAMS;
+typedef CK_SKIPJACK_RELAYX_PARAMS CK_PTR \
+ CK_SKIPJACK_RELAYX_PARAMS_PTR;
+typedef struct CK_PBE_PARAMS {
+ CK_BYTE_PTR pInitVector;
+ CK_UTF8CHAR_PTR pPassword;
+ CK_ULONG ulPasswordLen;
+typedef CK_PBE_PARAMS CK_PTR CK_PBE_PARAMS_PTR;
+/* CK_KEY_WRAP_SET_OAEP_PARAMS provides the parameters to the
+ * CKM_KEY_WRAP_SET_OAEP mechanism */
+/* CK_KEY_WRAP_SET_OAEP_PARAMS is new for v2.0 */
+typedef struct CK_KEY_WRAP_SET_OAEP_PARAMS {
+ CK_BYTE bBC; /* block contents byte */
+ CK_BYTE_PTR pX; /* extra data */
+ CK_ULONG ulXLen; /* length of extra data in bytes */
+} CK_KEY_WRAP_SET_OAEP_PARAMS;
+typedef CK_KEY_WRAP_SET_OAEP_PARAMS CK_PTR \
+ CK_KEY_WRAP_SET_OAEP_PARAMS_PTR;
+typedef struct CK_SSL3_RANDOM_DATA {
+ CK_BYTE_PTR pClientRandom;
+ CK_ULONG ulClientRandomLen;
+ CK_BYTE_PTR pServerRandom;
+ CK_ULONG ulServerRandomLen;
+typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS {
+ CK_SSL3_RANDOM_DATA RandomInfo;
+ CK_VERSION_PTR pVersion;
+} CK_SSL3_MASTER_KEY_DERIVE_PARAMS;
+typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS CK_PTR \
+ CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR;
+typedef struct CK_SSL3_KEY_MAT_OUT {
+ CK_OBJECT_HANDLE hClientMacSecret;
+ CK_OBJECT_HANDLE hServerMacSecret;
+ CK_OBJECT_HANDLE hClientKey;
+ CK_OBJECT_HANDLE hServerKey;
+typedef CK_SSL3_KEY_MAT_OUT CK_PTR CK_SSL3_KEY_MAT_OUT_PTR;
+typedef struct CK_SSL3_KEY_MAT_PARAMS {
+ CK_ULONG ulMacSizeInBits;
+ CK_ULONG ulKeySizeInBits;
+ CK_ULONG ulIVSizeInBits;
+ CK_SSL3_RANDOM_DATA RandomInfo;
+ CK_SSL3_KEY_MAT_OUT_PTR pReturnedKeyMaterial;
+} CK_SSL3_KEY_MAT_PARAMS;
+typedef CK_SSL3_KEY_MAT_PARAMS CK_PTR CK_SSL3_KEY_MAT_PARAMS_PTR;
+/* CK_TLS_PRF_PARAMS is new for version 2.20 */
+typedef struct CK_TLS_PRF_PARAMS {
+ CK_ULONG_PTR pulOutputLen;
+typedef CK_TLS_PRF_PARAMS CK_PTR CK_TLS_PRF_PARAMS_PTR;
+/* WTLS is new for version 2.20 */
+typedef struct CK_WTLS_RANDOM_DATA {
+ CK_BYTE_PTR pClientRandom;
+ CK_ULONG ulClientRandomLen;
+ CK_BYTE_PTR pServerRandom;
+ CK_ULONG ulServerRandomLen;
+typedef CK_WTLS_RANDOM_DATA CK_PTR CK_WTLS_RANDOM_DATA_PTR;
+typedef struct CK_WTLS_MASTER_KEY_DERIVE_PARAMS {
+ CK_MECHANISM_TYPE DigestMechanism;
+ CK_WTLS_RANDOM_DATA RandomInfo;
+} CK_WTLS_MASTER_KEY_DERIVE_PARAMS;
+typedef CK_WTLS_MASTER_KEY_DERIVE_PARAMS CK_PTR \
+ CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR;
+typedef struct CK_WTLS_PRF_PARAMS {
+ CK_MECHANISM_TYPE DigestMechanism;
+ CK_ULONG_PTR pulOutputLen;
+typedef CK_WTLS_PRF_PARAMS CK_PTR CK_WTLS_PRF_PARAMS_PTR;
+typedef struct CK_WTLS_KEY_MAT_OUT {
+ CK_OBJECT_HANDLE hMacSecret;
+typedef CK_WTLS_KEY_MAT_OUT CK_PTR CK_WTLS_KEY_MAT_OUT_PTR;
+typedef struct CK_WTLS_KEY_MAT_PARAMS {
+ CK_MECHANISM_TYPE DigestMechanism;
+ CK_ULONG ulMacSizeInBits;
+ CK_ULONG ulKeySizeInBits;
+ CK_ULONG ulIVSizeInBits;
+ CK_ULONG ulSequenceNumber;
+ CK_WTLS_RANDOM_DATA RandomInfo;
+ CK_WTLS_KEY_MAT_OUT_PTR pReturnedKeyMaterial;
+} CK_WTLS_KEY_MAT_PARAMS;
+typedef CK_WTLS_KEY_MAT_PARAMS CK_PTR CK_WTLS_KEY_MAT_PARAMS_PTR;
+/* CMS is new for version 2.20 */
+typedef struct CK_CMS_SIG_PARAMS {
+ CK_OBJECT_HANDLE certificateHandle;
+ CK_MECHANISM_PTR pSigningMechanism;
+ CK_MECHANISM_PTR pDigestMechanism;
+ CK_UTF8CHAR_PTR pContentType;
+ CK_BYTE_PTR pRequestedAttributes;
+ CK_ULONG ulRequestedAttributesLen;
+ CK_BYTE_PTR pRequiredAttributes;
+ CK_ULONG ulRequiredAttributesLen;
+typedef CK_CMS_SIG_PARAMS CK_PTR CK_CMS_SIG_PARAMS_PTR;
+typedef struct CK_KEY_DERIVATION_STRING_DATA {
+} CK_KEY_DERIVATION_STRING_DATA;
+typedef CK_KEY_DERIVATION_STRING_DATA CK_PTR \
+ CK_KEY_DERIVATION_STRING_DATA_PTR;
+/* The CK_EXTRACT_PARAMS is used for the
+ * CKM_EXTRACT_KEY_FROM_KEY mechanism. It specifies which bit
+ * of the base key should be used as the first bit of the
+/* CK_EXTRACT_PARAMS is new for v2.0 */
+typedef CK_ULONG CK_EXTRACT_PARAMS;
+typedef CK_EXTRACT_PARAMS CK_PTR CK_EXTRACT_PARAMS_PTR;
+/* CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is new for v2.10.
+ * CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is used to
+ * indicate the Pseudo-Random Function (PRF) used to generate
+ * key bits using PKCS #5 PBKDF2. */
+typedef CK_ULONG CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE;
+typedef CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE CK_PTR CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR;
+/* The following PRFs are defined in PKCS #5 v2.0. */
+#define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001
+/* CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is new for v2.10.
+ * CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is used to indicate the
+ * source of the salt value when deriving a key using PKCS #5
+typedef CK_ULONG CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE;
+typedef CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE CK_PTR CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR;
+/* The following salt value sources are defined in PKCS #5 v2.0. */
+#define CKZ_SALT_SPECIFIED 0x00000001
+/* CK_PKCS5_PBKD2_PARAMS is new for v2.10.
+ * CK_PKCS5_PBKD2_PARAMS is a structure that provides the
+ * parameters to the CKM_PKCS5_PBKD2 mechanism. */
+typedef struct CK_PKCS5_PBKD2_PARAMS {
+ CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource;
+ CK_VOID_PTR pSaltSourceData;
+ CK_ULONG ulSaltSourceDataLen;
+ CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf;
+ CK_UTF8CHAR_PTR pPassword;
+ CK_ULONG_PTR ulPasswordLen;
+} CK_PKCS5_PBKD2_PARAMS;
+typedef CK_PKCS5_PBKD2_PARAMS CK_PTR CK_PKCS5_PBKD2_PARAMS_PTR;
+/* All CK_OTP structs are new for PKCS #11 v2.20 amendment 3 */
+typedef CK_ULONG CK_OTP_PARAM_TYPE;
+typedef CK_OTP_PARAM_TYPE CK_PARAM_TYPE; /* B/w compatibility */
+typedef struct CK_OTP_PARAM {
+ CK_OTP_PARAM_TYPE type;
+typedef CK_OTP_PARAM CK_PTR CK_OTP_PARAM_PTR;
+typedef struct CK_OTP_PARAMS {
+ CK_OTP_PARAM_PTR pParams;
+typedef CK_OTP_PARAMS CK_PTR CK_OTP_PARAMS_PTR;
+typedef struct CK_OTP_SIGNATURE_INFO {
+ CK_OTP_PARAM_PTR pParams;
+} CK_OTP_SIGNATURE_INFO;
+typedef CK_OTP_SIGNATURE_INFO CK_PTR CK_OTP_SIGNATURE_INFO_PTR;
+/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 */
+#define CK_OTP_CHALLENGE 2
+#define CK_OTP_COUNTER 4
+#define CK_OTP_OUTPUT_LENGTH 6
+#define CK_OTP_OUTPUT_FORMAT 7
+/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 */
+#define CKF_NEXT_OTP 0x00000001
+#define CKF_EXCLUDE_TIME 0x00000002
+#define CKF_EXCLUDE_COUNTER 0x00000004
+#define CKF_EXCLUDE_CHALLENGE 0x00000008
+#define CKF_EXCLUDE_PIN 0x00000010
+#define CKF_USER_FRIENDLY_OTP 0x00000020
+/* CK_KIP_PARAMS is new for PKCS #11 v2.20 amendment 2 */
+typedef struct CK_KIP_PARAMS {
+ CK_MECHANISM_PTR pMechanism;
+typedef CK_KIP_PARAMS CK_PTR CK_KIP_PARAMS_PTR;
+/* CK_AES_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */
+typedef struct CK_AES_CTR_PARAMS {
+ CK_ULONG ulCounterBits;
+typedef CK_AES_CTR_PARAMS CK_PTR CK_AES_CTR_PARAMS_PTR;
+/* CK_CAMELLIA_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */
+typedef struct CK_CAMELLIA_CTR_PARAMS {
+ CK_ULONG ulCounterBits;
+} CK_CAMELLIA_CTR_PARAMS;
+typedef CK_CAMELLIA_CTR_PARAMS CK_PTR CK_CAMELLIA_CTR_PARAMS_PTR;
+/* CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */
+typedef struct CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS {
+} CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS;
+typedef CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
+/* CK_ARIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */
+typedef struct CK_ARIA_CBC_ENCRYPT_DATA_PARAMS {
+} CK_ARIA_CBC_ENCRYPT_DATA_PARAMS;
+typedef CK_ARIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
pqueue_size 4114 EXIST::FUNCTION:
OPENSSL_uni2asc 4115 EXIST:NETWARE:FUNCTION:
OPENSSL_asc2uni 4116 EXIST:NETWARE:FUNCTION:
+ENGINE_load_pk11ca 4117 EXIST::FUNCTION:HW_PKCS11CA,ENGINE
+ENGINE_load_pk11so 4117 EXIST::FUNCTION:HW_PKCS11SO,ENGINE
ASN1_TYPE_cmp 4428 EXIST::FUNCTION:
+ no-hw-pkcs11ca - No hw PKCS#11 CA flavor
+ no-hw-pkcs11so - No hw PKCS#11 SO flavor
nasm - Use NASM for x86 asm
nw-nasm - Use NASM x86 asm for NetWare
nw-mwasm - Use Metrowerks x86 asm for NetWare
$cflags.=" -DOPENSSL_NO_ECDH" if $no_ecdh;
$cflags.=" -DOPENSSL_NO_ENGINE" if $no_engine;
$cflags.=" -DOPENSSL_NO_HW" if $no_hw;
+$cflags.=" -DOPENSSL_NO_HW_PKCS11CA" if $no_hw_pkcs11ca;
+$cflags.=" -DOPENSSL_NO_HW_PKCS11SO" if $no_hw_pkcs11so;
$cflags.=" -DOPENSSL_FIPS" if $fips;
$cflags.= " -DZLIB" if $zlib_opt;
$cflags.= " -DZLIB_SHARED" if $zlib_opt == 2;
+ if ($key eq "PK11_LIB_LOCATION")
+ { $cflags .= " -D$key=\\\"$val\\\"" if $val ne "";}
if ($key eq "KRB5_INCLUDES")
"no-engine" => \$no_engine,
+ "no-hw-pkcs11ca" => \$no_hw_pkcs11ca,
+ "no-hw-pkcs11so" => \$no_hw_pkcs11so,
[\$no_rc2, \$no_idea, \$no_des, \$no_bf, \$no_cast,
\$no_md2, \$no_sha, \$no_mdc2, \$no_dsa, \$no_dh,
"FP_API", "STDIO", "SOCK", "KRB5", "DGRAM",
- "STATIC_ENGINE", "ENGINE", "HW", "GMP",
+ "STATIC_ENGINE", "ENGINE", "HW", "GMP", "HW_PKCS11CA", "HW_PKCS11SO",
my $no_md2; my $no_md4; my $no_md5; my $no_sha; my $no_ripemd; my $no_mdc2;
my $no_rsa; my $no_dsa; my $no_dh; my $no_hmac=0; my $no_aes; my $no_krb5;
my $no_ec; my $no_ecdsa; my $no_ecdh; my $no_engine; my $no_hw; my $no_camellia;
+my $no_pkcs11ca; my $no_pkcs11so;
my $no_fp_api; my $no_static_engine; my $no_gmp; my $no_deprecated;
my $no_rfc3779; my $no_tlsext; my $no_cms; my $no_capieng; my $no_jpake;
elsif (/^no-cms$/) { $no_cms=1; }
elsif (/^no-capieng$/) { $no_capieng=1; }
elsif (/^no-jpake$/) { $no_jpake=1; }
+ elsif (/^no-hw-pkcs11ca$/) { $no_pkcs11ca=1; }
+ elsif (/^no-hw-pkcs11so$/) { $no_pkcs11so=1; }
if ($keyword eq "KRB5" && $no_krb5) { return 0; }
if ($keyword eq "ENGINE" && $no_engine) { return 0; }
if ($keyword eq "HW" && $no_hw) { return 0; }
+ if ($keyword eq "HW_PKCS11CA" && $no_pkcs11ca) { return 0; }
+ if ($keyword eq "HW_PKCS11SO" && $no_pkcs11so) { return 0; }
if ($keyword eq "FP_API" && $no_fp_api) { return 0; }
if ($keyword eq "STATIC_ENGINE" && $no_static_engine) { return 0; }
if ($keyword eq "GMP" && $no_gmp) { return 0; }
my $f = $shlib || $fips ?' /MD':' /MT';
$lib_cflag='/Zl' if (!$shlib); # remove /DEFAULTLIBs from static lib
- $dbg_cflags=$f.'d /Od -DDEBUG -D_DEBUG';
+ $dbg_cflags=$f.'d /Od /Zi -DDEBUG -D_DEBUG';
$lflags="/nologo /subsystem:console /opt:ref";