components/openssl/openssl-1.0.1-fips-140/engines/pkcs11/hw_pk11.c
changeset 1587 314c74b881bc
parent 1586 2d3ec080d6a3
child 1588 8117331776d5
equal deleted inserted replaced
1586:2d3ec080d6a3 1587:314c74b881bc
     1 /*
       
     2  * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
       
     3  */
       
     4 
       
     5 /* crypto/engine/hw_pk11.c */
       
     6 /*
       
     7  * This product includes software developed by the OpenSSL Project for
       
     8  * use in the OpenSSL Toolkit (http://www.openssl.org/).
       
     9  *
       
    10  * This project also referenced hw_pkcs11-0.9.7b.patch written by
       
    11  * Afchine Madjlessi.
       
    12  */
       
    13 /*
       
    14  * ====================================================================
       
    15  * Copyright (c) 2000-2001 The OpenSSL Project.  All rights reserved.
       
    16  *
       
    17  * Redistribution and use in source and binary forms, with or without
       
    18  * modification, are permitted provided that the following conditions
       
    19  * are met:
       
    20  *
       
    21  * 1. Redistributions of source code must retain the above copyright
       
    22  *    notice, this list of conditions and the following disclaimer.
       
    23  *
       
    24  * 2. Redistributions in binary form must reproduce the above copyright
       
    25  *    notice, this list of conditions and the following disclaimer in
       
    26  *    the documentation and/or other materials provided with the
       
    27  *    distribution.
       
    28  *
       
    29  * 3. All advertising materials mentioning features or use of this
       
    30  *    software must display the following acknowledgment:
       
    31  *    "This product includes software developed by the OpenSSL Project
       
    32  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
       
    33  *
       
    34  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
       
    35  *    endorse or promote products derived from this software without
       
    36  *    prior written permission. For written permission, please contact
       
    37  *    [email protected].
       
    38  *
       
    39  * 5. Products derived from this software may not be called "OpenSSL"
       
    40  *    nor may "OpenSSL" appear in their names without prior written
       
    41  *    permission of the OpenSSL Project.
       
    42  *
       
    43  * 6. Redistributions of any form whatsoever must retain the following
       
    44  *    acknowledgment:
       
    45  *    "This product includes software developed by the OpenSSL Project
       
    46  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
       
    47  *
       
    48  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
       
    49  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
       
    50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
       
    51  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
       
    52  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
       
    53  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
       
    54  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
       
    55  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
       
    56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
       
    57  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
       
    58  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
       
    59  * OF THE POSSIBILITY OF SUCH DAMAGE.
       
    60  * ====================================================================
       
    61  *
       
    62  * This product includes cryptographic software written by Eric Young
       
    63  * ([email protected]).  This product includes software written by Tim
       
    64  * Hudson ([email protected]).
       
    65  *
       
    66  */
       
    67 
       
    68 #include <stdio.h>
       
    69 #include <stdlib.h>
       
    70 #include <string.h>
       
    71 #include <sys/types.h>
       
    72 #include <unistd.h>
       
    73 #include <strings.h>
       
    74 
       
    75 #include <openssl/e_os2.h>
       
    76 #include <openssl/crypto.h>
       
    77 #include <openssl/engine.h>
       
    78 #include <openssl/dso.h>
       
    79 #include <openssl/err.h>
       
    80 #include <openssl/bn.h>
       
    81 #include <openssl/md5.h>
       
    82 #include <openssl/pem.h>
       
    83 #ifndef OPENSSL_NO_RSA
       
    84 #include <openssl/rsa.h>
       
    85 #endif
       
    86 #ifndef OPENSSL_NO_DSA
       
    87 #include <openssl/dsa.h>
       
    88 #endif
       
    89 #ifndef OPENSSL_NO_DH
       
    90 #include <openssl/dh.h>
       
    91 #endif
       
    92 #include <openssl/rand.h>
       
    93 #include <openssl/objects.h>
       
    94 #include <openssl/x509.h>
       
    95 #include <openssl/aes.h>
       
    96 #include <cryptlib.h>
       
    97 #include <dlfcn.h>
       
    98 #include <pthread.h>
       
    99 
       
   100 #ifndef OPENSSL_NO_HW
       
   101 #ifndef OPENSSL_NO_HW_PK11
       
   102 
       
   103 /* label for debug messages printed on stderr */
       
   104 #define	PK11_DBG	"PKCS#11 ENGINE DEBUG"
       
   105 /* prints a lot of debug messages on stderr about slot selection process */
       
   106 #undef	DEBUG_SLOT_SELECTION
       
   107 /*
       
   108  * Solaris specific code. See comment at check_hw_mechanisms() for more
       
   109  * information.
       
   110  */
       
   111 #if defined(__SVR4) && defined(__sun)
       
   112 #define	SOLARIS_HW_SLOT_SELECTION
       
   113 #endif
       
   114 
       
   115 #ifdef DEBUG_SLOT_SELECTION
       
   116 #define	DEBUG_SLOT_SEL(...) fprintf(stderr, __VA_ARGS__)
       
   117 #else
       
   118 #define	DEBUG_SLOT_SEL(...)
       
   119 #endif
       
   120 
       
   121 #include <security/cryptoki.h>
       
   122 #include <security/pkcs11.h>
       
   123 #include "hw_pk11.h"
       
   124 #include "hw_pk11_uri.h"
       
   125 
       
   126 #define	PK11_ENGINE_LIB_NAME "PKCS#11 engine"
       
   127 #include "hw_pk11_err.c"
       
   128 
       
   129 /*
       
   130  * We use this lock to prevent multiple C_Login()s, guard getpassphrase(),
       
   131  * uri_struct manipulation, and static token info. All of that is used by the
       
   132  * RSA keys by reference feature.
       
   133  */
       
   134 pthread_mutex_t *uri_lock;
       
   135 
       
   136 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
   137 /*
       
   138  * Tables for symmetric ciphers and digest mechs found in the pkcs11_kernel
       
   139  * library. See comment at check_hw_mechanisms() for more information.
       
   140  */
       
   141 int *hw_cnids;
       
   142 int *hw_dnids;
       
   143 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
   144 
       
   145 /* PKCS#11 session caches and their locks for all operation types */
       
   146 static PK11_CACHE session_cache[OP_MAX];
       
   147 
       
   148 /*
       
   149  * We cache the flags so that we do not have to run C_GetTokenInfo() again when
       
   150  * logging into the token.
       
   151  */
       
   152 CK_FLAGS pubkey_token_flags;
       
   153 
       
   154 /*
       
   155  * As stated in v2.20, 11.7 Object Management Function, in section for
       
   156  * C_FindObjectsInit(), at most one search operation may be active at a given
       
   157  * time in a given session. Therefore, C_Find{,Init,Final}Objects() should be
       
   158  * grouped together to form one atomic search operation. This is already
       
   159  * ensured by the property of unique PKCS#11 session handle used for each
       
   160  * PK11_SESSION object.
       
   161  *
       
   162  * This is however not the biggest concern - maintaining consistency of the
       
   163  * underlying object store is more important. The same section of the spec also
       
   164  * says that one thread can be in the middle of a search operation while another
       
   165  * thread destroys the object matching the search template which would result in
       
   166  * invalid handle returned from the search operation.
       
   167  *
       
   168  * Hence, the following locks are used for both protection of the object stores.
       
   169  * They are also used for active list protection.
       
   170  */
       
   171 pthread_mutex_t *find_lock[OP_MAX] = { NULL };
       
   172 
       
   173 /*
       
   174  * lists of asymmetric key handles which are active (referenced by at least one
       
   175  * PK11_SESSION structure, either held by a thread or present in free_session
       
   176  * list) for given algorithm type
       
   177  */
       
   178 PK11_active *active_list[OP_MAX] = { NULL };
       
   179 
       
   180 /*
       
   181  * Create all secret key objects in a global session so that they are available
       
   182  * to use for other sessions. These other sessions may be opened or closed
       
   183  * without losing the secret key objects.
       
   184  */
       
   185 static CK_SESSION_HANDLE	global_session = CK_INVALID_HANDLE;
       
   186 
       
   187 /* Index for the supported ciphers */
       
   188 enum pk11_cipher_id
       
   189 	{
       
   190 	PK11_DES_CBC,
       
   191 	PK11_DES3_CBC,
       
   192 	PK11_DES_ECB,
       
   193 	PK11_DES3_ECB,
       
   194 	PK11_RC4,
       
   195 	PK11_AES_128_CBC,
       
   196 	PK11_AES_192_CBC,
       
   197 	PK11_AES_256_CBC,
       
   198 	PK11_AES_128_ECB,
       
   199 	PK11_AES_192_ECB,
       
   200 	PK11_AES_256_ECB,
       
   201 	PK11_BLOWFISH_CBC,
       
   202 	PK11_AES_128_CTR,
       
   203 	PK11_AES_192_CTR,
       
   204 	PK11_AES_256_CTR,
       
   205 	PK11_CIPHER_MAX
       
   206 	};
       
   207 
       
   208 /* Index for the supported digests */
       
   209 enum pk11_digest_id
       
   210 	{
       
   211 	PK11_MD5,
       
   212 	PK11_SHA1,
       
   213 	PK11_SHA224,
       
   214 	PK11_SHA256,
       
   215 	PK11_SHA384,
       
   216 	PK11_SHA512,
       
   217 	PK11_DIGEST_MAX
       
   218 	};
       
   219 
       
   220 typedef struct PK11_CIPHER_st
       
   221 	{
       
   222 	enum pk11_cipher_id	id;
       
   223 	int			nid;
       
   224 	int			iv_len;
       
   225 	int			min_key_len;
       
   226 	int			max_key_len;
       
   227 	CK_KEY_TYPE		key_type;
       
   228 	CK_MECHANISM_TYPE	mech_type;
       
   229 	} PK11_CIPHER;
       
   230 
       
   231 typedef struct PK11_DIGEST_st
       
   232 	{
       
   233 	enum pk11_digest_id	id;
       
   234 	int			nid;
       
   235 	CK_MECHANISM_TYPE	mech_type;
       
   236 	} PK11_DIGEST;
       
   237 
       
   238 /* ENGINE level stuff */
       
   239 static int pk11_init(ENGINE *e);
       
   240 static int pk11_library_init(ENGINE *e);
       
   241 static int pk11_finish(ENGINE *e);
       
   242 static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
       
   243 static int pk11_destroy(ENGINE *e);
       
   244 
       
   245 /* RAND stuff */
       
   246 static void pk11_rand_seed(const void *buf, int num);
       
   247 static void pk11_rand_add(const void *buf, int num, double add_entropy);
       
   248 static void pk11_rand_cleanup(void);
       
   249 static int pk11_rand_bytes(unsigned char *buf, int num);
       
   250 static int pk11_rand_status(void);
       
   251 
       
   252 /* These functions are also used in other files */
       
   253 PK11_SESSION *pk11_get_session(PK11_OPTYPE optype);
       
   254 void pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype);
       
   255 
       
   256 /* active list manipulation functions used in this file */
       
   257 extern int pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type);
       
   258 extern void pk11_free_active_list(PK11_OPTYPE type);
       
   259 
       
   260 #ifndef OPENSSL_NO_RSA
       
   261 int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
       
   262 int pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
       
   263 int pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
       
   264 #endif
       
   265 #ifndef OPENSSL_NO_DSA
       
   266 int pk11_destroy_dsa_key_objects(PK11_SESSION *session);
       
   267 int pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
       
   268 int pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
       
   269 #endif
       
   270 #ifndef OPENSSL_NO_DH
       
   271 int pk11_destroy_dh_key_objects(PK11_SESSION *session);
       
   272 int pk11_destroy_dh_object(PK11_SESSION *session, CK_BBOOL uselock);
       
   273 #endif
       
   274 
       
   275 /* Local helper functions */
       
   276 static int pk11_free_all_sessions(void);
       
   277 static int pk11_free_session_list(PK11_OPTYPE optype);
       
   278 static int pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype);
       
   279 static int pk11_destroy_cipher_key_objects(PK11_SESSION *session);
       
   280 static int pk11_destroy_object(CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE oh,
       
   281     CK_BBOOL persistent);
       
   282 static const char *get_PK11_LIBNAME(void);
       
   283 static void free_PK11_LIBNAME(void);
       
   284 static long set_PK11_LIBNAME(const char *name);
       
   285 
       
   286 /* Symmetric cipher and digest support functions */
       
   287 static int cipher_nid_to_pk11(int nid);
       
   288 static int pk11_usable_ciphers(const int **nids);
       
   289 static int pk11_usable_digests(const int **nids);
       
   290 static int pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
       
   291 	const unsigned char *iv, int enc);
       
   292 static int pk11_cipher_final(PK11_SESSION *sp);
       
   293 static int pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
       
   294 	const unsigned char *in, unsigned int inl);
       
   295 static int pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx);
       
   296 static int pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
       
   297 	const int **nids, int nid);
       
   298 static int pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
       
   299 	const int **nids, int nid);
       
   300 static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
       
   301 	const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp);
       
   302 static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
       
   303 	int key_len);
       
   304 static int md_nid_to_pk11(int nid);
       
   305 static int pk11_digest_init(EVP_MD_CTX *ctx);
       
   306 static int pk11_digest_update(EVP_MD_CTX *ctx, const void *data,
       
   307 	size_t count);
       
   308 static int pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md);
       
   309 static int pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from);
       
   310 static int pk11_digest_cleanup(EVP_MD_CTX *ctx);
       
   311 
       
   312 static int pk11_choose_slots(int *any_slot_found);
       
   313 static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist,
       
   314     CK_SLOT_ID current_slot, int *current_slot_n_cipher,
       
   315     int *local_cipher_nids);
       
   316 static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
       
   317     CK_SLOT_ID current_slot, int *current_slot_n_digest,
       
   318     int *local_digest_nids);
       
   319 static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR, int slot_id,
       
   320     int *current_slot_n_cipher, int *local_cipher_nids,
       
   321     PK11_CIPHER *cipher);
       
   322 static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist, int slot_id,
       
   323     int *current_slot_n_digest, int *local_digest_nids,
       
   324     PK11_DIGEST *digest);
       
   325 
       
   326 static int pk11_init_all_locks(void);
       
   327 static void pk11_free_all_locks(void);
       
   328 
       
   329 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
   330 static int check_hw_mechanisms(void);
       
   331 static int nid_in_table(int nid, int *nid_table);
       
   332 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
   333 
       
   334 #define	TRY_OBJ_DESTROY(sp, obj_hdl, retval, uselock, alg_type)	\
       
   335 	{								\
       
   336 	if (uselock)							\
       
   337 		LOCK_OBJSTORE(alg_type);				\
       
   338 	if (pk11_active_delete(obj_hdl, alg_type) == 1)			\
       
   339 		{							\
       
   340 		retval = pk11_destroy_object(sp->session, obj_hdl,	\
       
   341 		    sp->persistent);					\
       
   342 		}							\
       
   343 	if (uselock)							\
       
   344 		UNLOCK_OBJSTORE(alg_type);				\
       
   345 	}
       
   346 
       
   347 static int cipher_nids[PK11_CIPHER_MAX];
       
   348 static int digest_nids[PK11_DIGEST_MAX];
       
   349 static int cipher_count		= 0;
       
   350 static int digest_count		= 0;
       
   351 static CK_BBOOL pk11_have_rsa	= CK_FALSE;
       
   352 static CK_BBOOL pk11_have_dsa	= CK_FALSE;
       
   353 static CK_BBOOL pk11_have_dh	= CK_FALSE;
       
   354 static CK_BBOOL pk11_have_random = CK_FALSE;
       
   355 
       
   356 /*
       
   357  * Static list of ciphers.
       
   358  * Note, that ciphers array is indexed by member PK11_CIPHER.id,
       
   359  * thus ciphers[i].id == i
       
   360  * Rows must be kept in sync with enum pk11_cipher_id.
       
   361  */
       
   362 static PK11_CIPHER ciphers[] =
       
   363 	{
       
   364 	{ PK11_DES_CBC,		NID_des_cbc,		8,	 8,   8,
       
   365 		CKK_DES,	CKM_DES_CBC, },
       
   366 	{ PK11_DES3_CBC,	NID_des_ede3_cbc,	8,	24,  24,
       
   367 		CKK_DES3,	CKM_DES3_CBC, },
       
   368 	{ PK11_DES_ECB,		NID_des_ecb,		0,	 8,   8,
       
   369 		CKK_DES,	CKM_DES_ECB, },
       
   370 	{ PK11_DES3_ECB,	NID_des_ede3_ecb,	0,	24,  24,
       
   371 		CKK_DES3,	CKM_DES3_ECB, },
       
   372 	{ PK11_RC4,		NID_rc4,		0,	16, 256,
       
   373 		CKK_RC4,	CKM_RC4, },
       
   374 	{ PK11_AES_128_CBC,	NID_aes_128_cbc,	16,	16,  16,
       
   375 		CKK_AES,	CKM_AES_CBC, },
       
   376 	{ PK11_AES_192_CBC,	NID_aes_192_cbc,	16,	24,  24,
       
   377 		CKK_AES,	CKM_AES_CBC, },
       
   378 	{ PK11_AES_256_CBC,	NID_aes_256_cbc,	16,	32,  32,
       
   379 		CKK_AES,	CKM_AES_CBC, },
       
   380 	{ PK11_AES_128_ECB,	NID_aes_128_ecb,	0,	16,  16,
       
   381 		CKK_AES,	CKM_AES_ECB, },
       
   382 	{ PK11_AES_192_ECB,	NID_aes_192_ecb,	0,	24,  24,
       
   383 		CKK_AES,	CKM_AES_ECB, },
       
   384 	{ PK11_AES_256_ECB,	NID_aes_256_ecb,	0,	32,  32,
       
   385 		CKK_AES,	CKM_AES_ECB, },
       
   386 	{ PK11_BLOWFISH_CBC,	NID_bf_cbc,		8,	16,  16,
       
   387 		CKK_BLOWFISH,	CKM_BLOWFISH_CBC, },
       
   388 	{ PK11_AES_128_CTR,	NID_aes_128_ctr,	16,	16,  16,
       
   389 		CKK_AES,	CKM_AES_CTR, },
       
   390 	{ PK11_AES_192_CTR,	NID_aes_192_ctr,	16,	24,  24,
       
   391 		CKK_AES,	CKM_AES_CTR, },
       
   392 	{ PK11_AES_256_CTR,	NID_aes_256_ctr,	16,	32,  32,
       
   393 		CKK_AES,	CKM_AES_CTR, },
       
   394 	};
       
   395 
       
   396 /*
       
   397  * Static list of digests.
       
   398  * Note, that digests array is indexed by member PK11_DIGEST.id,
       
   399  * thus digests[i].id == i
       
   400  * Rows must be kept in sync with enum pk11_digest_id.
       
   401  */
       
   402 static PK11_DIGEST digests[] =
       
   403 	{
       
   404 	{PK11_MD5,	NID_md5,	CKM_MD5, },
       
   405 	{PK11_SHA1,	NID_sha1,	CKM_SHA_1, },
       
   406 	{PK11_SHA224,	NID_sha224,	CKM_SHA224, },
       
   407 	{PK11_SHA256,	NID_sha256,	CKM_SHA256, },
       
   408 	{PK11_SHA384,	NID_sha384,	CKM_SHA384, },
       
   409 	{PK11_SHA512,	NID_sha512,	CKM_SHA512, },
       
   410 	{0,		NID_undef,	0xFFFF, },
       
   411 	};
       
   412 
       
   413 /*
       
   414  * Structure to be used for the cipher_data/md_data in
       
   415  * EVP_CIPHER_CTX/EVP_MD_CTX structures in order to use the same pk11
       
   416  * session in multiple cipher_update calls
       
   417  */
       
   418 typedef struct PK11_CIPHER_STATE_st
       
   419 	{
       
   420 	PK11_SESSION	*sp;
       
   421 	} PK11_CIPHER_STATE;
       
   422 
       
   423 
       
   424 /*
       
   425  * libcrypto EVP stuff - this is how we get wired to EVP so the engine gets
       
   426  * called when libcrypto requests a cipher NID.
       
   427  *
       
   428  * Note how the PK11_CIPHER_STATE is used here.
       
   429  */
       
   430 
       
   431 /* DES CBC EVP */
       
   432 static const EVP_CIPHER pk11_des_cbc =
       
   433 	{
       
   434 	NID_des_cbc,
       
   435 	8, 8, 8,
       
   436 	EVP_CIPH_CBC_MODE,
       
   437 	pk11_cipher_init,
       
   438 	pk11_cipher_do_cipher,
       
   439 	pk11_cipher_cleanup,
       
   440 	sizeof (PK11_CIPHER_STATE),
       
   441 	EVP_CIPHER_set_asn1_iv,
       
   442 	EVP_CIPHER_get_asn1_iv,
       
   443 	NULL
       
   444 	};
       
   445 
       
   446 /* 3DES CBC EVP */
       
   447 static const EVP_CIPHER pk11_3des_cbc =
       
   448 	{
       
   449 	NID_des_ede3_cbc,
       
   450 	8, 24, 8,
       
   451 	EVP_CIPH_CBC_MODE,
       
   452 	pk11_cipher_init,
       
   453 	pk11_cipher_do_cipher,
       
   454 	pk11_cipher_cleanup,
       
   455 	sizeof (PK11_CIPHER_STATE),
       
   456 	EVP_CIPHER_set_asn1_iv,
       
   457 	EVP_CIPHER_get_asn1_iv,
       
   458 	NULL
       
   459 	};
       
   460 
       
   461 /*
       
   462  * ECB modes don't use an Initial Vector so that's why set_asn1_parameters and
       
   463  * get_asn1_parameters fields are set to NULL.
       
   464  */
       
   465 static const EVP_CIPHER pk11_des_ecb =
       
   466 	{
       
   467 	NID_des_ecb,
       
   468 	8, 8, 8,
       
   469 	EVP_CIPH_ECB_MODE,
       
   470 	pk11_cipher_init,
       
   471 	pk11_cipher_do_cipher,
       
   472 	pk11_cipher_cleanup,
       
   473 	sizeof (PK11_CIPHER_STATE),
       
   474 	NULL,
       
   475 	NULL,
       
   476 	NULL
       
   477 	};
       
   478 
       
   479 static const EVP_CIPHER pk11_3des_ecb =
       
   480 	{
       
   481 	NID_des_ede3_ecb,
       
   482 	8, 24, 8,
       
   483 	EVP_CIPH_ECB_MODE,
       
   484 	pk11_cipher_init,
       
   485 	pk11_cipher_do_cipher,
       
   486 	pk11_cipher_cleanup,
       
   487 	sizeof (PK11_CIPHER_STATE),
       
   488 	NULL,
       
   489 	NULL,
       
   490 	NULL
       
   491 	};
       
   492 
       
   493 
       
   494 static const EVP_CIPHER pk11_aes_128_cbc =
       
   495 	{
       
   496 	NID_aes_128_cbc,
       
   497 	16, 16, 16,
       
   498 	EVP_CIPH_CBC_MODE,
       
   499 	pk11_cipher_init,
       
   500 	pk11_cipher_do_cipher,
       
   501 	pk11_cipher_cleanup,
       
   502 	sizeof (PK11_CIPHER_STATE),
       
   503 	EVP_CIPHER_set_asn1_iv,
       
   504 	EVP_CIPHER_get_asn1_iv,
       
   505 	NULL
       
   506 	};
       
   507 
       
   508 static const EVP_CIPHER pk11_aes_192_cbc =
       
   509 	{
       
   510 	NID_aes_192_cbc,
       
   511 	16, 24, 16,
       
   512 	EVP_CIPH_CBC_MODE,
       
   513 	pk11_cipher_init,
       
   514 	pk11_cipher_do_cipher,
       
   515 	pk11_cipher_cleanup,
       
   516 	sizeof (PK11_CIPHER_STATE),
       
   517 	EVP_CIPHER_set_asn1_iv,
       
   518 	EVP_CIPHER_get_asn1_iv,
       
   519 	NULL
       
   520 	};
       
   521 
       
   522 static const EVP_CIPHER pk11_aes_256_cbc =
       
   523 	{
       
   524 	NID_aes_256_cbc,
       
   525 	16, 32, 16,
       
   526 	EVP_CIPH_CBC_MODE,
       
   527 	pk11_cipher_init,
       
   528 	pk11_cipher_do_cipher,
       
   529 	pk11_cipher_cleanup,
       
   530 	sizeof (PK11_CIPHER_STATE),
       
   531 	EVP_CIPHER_set_asn1_iv,
       
   532 	EVP_CIPHER_get_asn1_iv,
       
   533 	NULL
       
   534 	};
       
   535 
       
   536 /*
       
   537  * ECB modes don't use IV so that's why set_asn1_parameters and
       
   538  * get_asn1_parameters are set to NULL.
       
   539  */
       
   540 static const EVP_CIPHER pk11_aes_128_ecb =
       
   541 	{
       
   542 	NID_aes_128_ecb,
       
   543 	16, 16, 0,
       
   544 	EVP_CIPH_ECB_MODE,
       
   545 	pk11_cipher_init,
       
   546 	pk11_cipher_do_cipher,
       
   547 	pk11_cipher_cleanup,
       
   548 	sizeof (PK11_CIPHER_STATE),
       
   549 	NULL,
       
   550 	NULL,
       
   551 	NULL
       
   552 	};
       
   553 
       
   554 static const EVP_CIPHER pk11_aes_192_ecb =
       
   555 	{
       
   556 	NID_aes_192_ecb,
       
   557 	16, 24, 0,
       
   558 	EVP_CIPH_ECB_MODE,
       
   559 	pk11_cipher_init,
       
   560 	pk11_cipher_do_cipher,
       
   561 	pk11_cipher_cleanup,
       
   562 	sizeof (PK11_CIPHER_STATE),
       
   563 	NULL,
       
   564 	NULL,
       
   565 	NULL
       
   566 	};
       
   567 
       
   568 static const EVP_CIPHER pk11_aes_256_ecb =
       
   569 	{
       
   570 	NID_aes_256_ecb,
       
   571 	16, 32, 0,
       
   572 	EVP_CIPH_ECB_MODE,
       
   573 	pk11_cipher_init,
       
   574 	pk11_cipher_do_cipher,
       
   575 	pk11_cipher_cleanup,
       
   576 	sizeof (PK11_CIPHER_STATE),
       
   577 	NULL,
       
   578 	NULL,
       
   579 	NULL
       
   580 	};
       
   581 
       
   582 static EVP_CIPHER pk11_aes_128_ctr =
       
   583 	{
       
   584 	NID_aes_128_ctr,
       
   585 	16, 16, 16,
       
   586 	EVP_CIPH_CTR_MODE,
       
   587 	pk11_cipher_init,
       
   588 	pk11_cipher_do_cipher,
       
   589 	pk11_cipher_cleanup,
       
   590 	sizeof (PK11_CIPHER_STATE),
       
   591 	EVP_CIPHER_set_asn1_iv,
       
   592 	EVP_CIPHER_get_asn1_iv,
       
   593 	NULL
       
   594 	};
       
   595 
       
   596 static EVP_CIPHER pk11_aes_192_ctr =
       
   597 	{
       
   598 	NID_aes_192_ctr,
       
   599 	16, 24, 16,
       
   600 	EVP_CIPH_CTR_MODE,
       
   601 	pk11_cipher_init,
       
   602 	pk11_cipher_do_cipher,
       
   603 	pk11_cipher_cleanup,
       
   604 	sizeof (PK11_CIPHER_STATE),
       
   605 	EVP_CIPHER_set_asn1_iv,
       
   606 	EVP_CIPHER_get_asn1_iv,
       
   607 	NULL
       
   608 	};
       
   609 
       
   610 static EVP_CIPHER pk11_aes_256_ctr =
       
   611 	{
       
   612 	NID_aes_256_ctr,
       
   613 	16, 32, 16,
       
   614 	EVP_CIPH_CTR_MODE,
       
   615 	pk11_cipher_init,
       
   616 	pk11_cipher_do_cipher,
       
   617 	pk11_cipher_cleanup,
       
   618 	sizeof (PK11_CIPHER_STATE),
       
   619 	EVP_CIPHER_set_asn1_iv,
       
   620 	EVP_CIPHER_get_asn1_iv,
       
   621 	NULL
       
   622 	};
       
   623 
       
   624 static const EVP_CIPHER pk11_bf_cbc =
       
   625 	{
       
   626 	NID_bf_cbc,
       
   627 	8, 16, 8,
       
   628 	EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CBC_MODE,
       
   629 	pk11_cipher_init,
       
   630 	pk11_cipher_do_cipher,
       
   631 	pk11_cipher_cleanup,
       
   632 	sizeof (PK11_CIPHER_STATE),
       
   633 	EVP_CIPHER_set_asn1_iv,
       
   634 	EVP_CIPHER_get_asn1_iv,
       
   635 	NULL
       
   636 	};
       
   637 
       
   638 static const EVP_CIPHER pk11_rc4 =
       
   639 	{
       
   640 	NID_rc4,
       
   641 	1, 16, 0,
       
   642 	EVP_CIPH_VARIABLE_LENGTH,
       
   643 	pk11_cipher_init,
       
   644 	pk11_cipher_do_cipher,
       
   645 	pk11_cipher_cleanup,
       
   646 	sizeof (PK11_CIPHER_STATE),
       
   647 	NULL,
       
   648 	NULL,
       
   649 	NULL
       
   650 	};
       
   651 
       
   652 static const EVP_MD pk11_md5 =
       
   653 	{
       
   654 	NID_md5,
       
   655 	NID_md5WithRSAEncryption,
       
   656 	MD5_DIGEST_LENGTH,
       
   657 	0,
       
   658 	pk11_digest_init,
       
   659 	pk11_digest_update,
       
   660 	pk11_digest_final,
       
   661 	pk11_digest_copy,
       
   662 	pk11_digest_cleanup,
       
   663 	EVP_PKEY_RSA_method,
       
   664 	MD5_CBLOCK,
       
   665 	sizeof (PK11_CIPHER_STATE),
       
   666 	};
       
   667 
       
   668 static const EVP_MD pk11_sha1 =
       
   669 	{
       
   670 	NID_sha1,
       
   671 	NID_sha1WithRSAEncryption,
       
   672 	SHA_DIGEST_LENGTH,
       
   673 	EVP_MD_FLAG_FIPS,
       
   674 	pk11_digest_init,
       
   675 	pk11_digest_update,
       
   676 	pk11_digest_final,
       
   677 	pk11_digest_copy,
       
   678 	pk11_digest_cleanup,
       
   679 	EVP_PKEY_RSA_method,
       
   680 	SHA_CBLOCK,
       
   681 	sizeof (PK11_CIPHER_STATE),
       
   682 	};
       
   683 
       
   684 static const EVP_MD pk11_sha224 =
       
   685 	{
       
   686 	NID_sha224,
       
   687 	NID_sha224WithRSAEncryption,
       
   688 	SHA224_DIGEST_LENGTH,
       
   689 	EVP_MD_FLAG_FIPS,
       
   690 	pk11_digest_init,
       
   691 	pk11_digest_update,
       
   692 	pk11_digest_final,
       
   693 	pk11_digest_copy,
       
   694 	pk11_digest_cleanup,
       
   695 	EVP_PKEY_RSA_method,
       
   696 	/* SHA-224 uses the same cblock size as SHA-256 */
       
   697 	SHA256_CBLOCK,
       
   698 	sizeof (PK11_CIPHER_STATE),
       
   699 	};
       
   700 
       
   701 static const EVP_MD pk11_sha256 =
       
   702 	{
       
   703 	NID_sha256,
       
   704 	NID_sha256WithRSAEncryption,
       
   705 	SHA256_DIGEST_LENGTH,
       
   706 	EVP_MD_FLAG_FIPS,
       
   707 	pk11_digest_init,
       
   708 	pk11_digest_update,
       
   709 	pk11_digest_final,
       
   710 	pk11_digest_copy,
       
   711 	pk11_digest_cleanup,
       
   712 	EVP_PKEY_RSA_method,
       
   713 	SHA256_CBLOCK,
       
   714 	sizeof (PK11_CIPHER_STATE),
       
   715 	};
       
   716 
       
   717 static const EVP_MD pk11_sha384 =
       
   718 	{
       
   719 	NID_sha384,
       
   720 	NID_sha384WithRSAEncryption,
       
   721 	SHA384_DIGEST_LENGTH,
       
   722 	EVP_MD_FLAG_FIPS,
       
   723 	pk11_digest_init,
       
   724 	pk11_digest_update,
       
   725 	pk11_digest_final,
       
   726 	pk11_digest_copy,
       
   727 	pk11_digest_cleanup,
       
   728 	EVP_PKEY_RSA_method,
       
   729 	/* SHA-384 uses the same cblock size as SHA-512 */
       
   730 	SHA512_CBLOCK,
       
   731 	sizeof (PK11_CIPHER_STATE),
       
   732 	};
       
   733 
       
   734 static const EVP_MD pk11_sha512 =
       
   735 	{
       
   736 	NID_sha512,
       
   737 	NID_sha512WithRSAEncryption,
       
   738 	SHA512_DIGEST_LENGTH,
       
   739 	EVP_MD_FLAG_FIPS,
       
   740 	pk11_digest_init,
       
   741 	pk11_digest_update,
       
   742 	pk11_digest_final,
       
   743 	pk11_digest_copy,
       
   744 	pk11_digest_cleanup,
       
   745 	EVP_PKEY_RSA_method,
       
   746 	SHA512_CBLOCK,
       
   747 	sizeof (PK11_CIPHER_STATE),
       
   748 	};
       
   749 
       
   750 /*
       
   751  * Initialization function. Sets up various PKCS#11 library components.
       
   752  * The definitions for control commands specific to this engine
       
   753  */
       
   754 #define	PK11_CMD_SO_PATH		ENGINE_CMD_BASE
       
   755 static const ENGINE_CMD_DEFN pk11_cmd_defns[] =
       
   756 	{
       
   757 		{
       
   758 		PK11_CMD_SO_PATH,
       
   759 		"SO_PATH",
       
   760 		"Specifies the path to the 'pkcs#11' shared library",
       
   761 		ENGINE_CMD_FLAG_STRING
       
   762 		},
       
   763 		{0, NULL, NULL, 0}
       
   764 	};
       
   765 
       
   766 
       
   767 static RAND_METHOD pk11_random =
       
   768 	{
       
   769 	pk11_rand_seed,
       
   770 	pk11_rand_bytes,
       
   771 	pk11_rand_cleanup,
       
   772 	pk11_rand_add,
       
   773 	pk11_rand_bytes,
       
   774 	pk11_rand_status
       
   775 	};
       
   776 
       
   777 
       
   778 /* Constants used when creating the ENGINE */
       
   779 static const char *engine_pk11_id = "pkcs11";
       
   780 static const char *engine_pk11_name = "PKCS #11 engine support";
       
   781 
       
   782 CK_FUNCTION_LIST_PTR pFuncList = NULL;
       
   783 static const char PK11_GET_FUNCTION_LIST[] = "C_GetFunctionList";
       
   784 
       
   785 /*
       
   786  * This is a static string constant for the DSO file name and the function
       
   787  * symbol names to bind to. We set it in the Configure script based on whether
       
   788  * this is 32 or 64 bit build.
       
   789  */
       
   790 static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;
       
   791 
       
   792 static CK_BBOOL pk11_true = CK_TRUE;
       
   793 static CK_BBOOL pk11_false = CK_FALSE;
       
   794 /* Needed in hw_pk11_pub.c as well so that's why it is not static. */
       
   795 CK_SLOT_ID pubkey_SLOTID = 0;
       
   796 static CK_SLOT_ID rand_SLOTID = 0;
       
   797 static CK_SLOT_ID SLOTID = 0;
       
   798 static CK_BBOOL pk11_library_initialized = CK_FALSE;
       
   799 static CK_BBOOL pk11_atfork_initialized = CK_FALSE;
       
   800 static int pk11_pid = 0;
       
   801 
       
   802 static DSO *pk11_dso = NULL;
       
   803 
       
   804 /* allocate and initialize all locks used by the engine itself */
       
   805 static int pk11_init_all_locks(void)
       
   806 	{
       
   807 	int type;
       
   808 
       
   809 #ifndef OPENSSL_NO_RSA
       
   810 	find_lock[OP_RSA] = OPENSSL_malloc(sizeof (pthread_mutex_t));
       
   811 	if (find_lock[OP_RSA] == NULL)
       
   812 		goto malloc_err;
       
   813 	(void) pthread_mutex_init(find_lock[OP_RSA], NULL);
       
   814 #endif /* OPENSSL_NO_RSA */
       
   815 
       
   816 	if ((uri_lock = OPENSSL_malloc(sizeof (pthread_mutex_t))) == NULL)
       
   817 		goto malloc_err;
       
   818 	(void) pthread_mutex_init(uri_lock, NULL);
       
   819 
       
   820 #ifndef OPENSSL_NO_DSA
       
   821 	find_lock[OP_DSA] = OPENSSL_malloc(sizeof (pthread_mutex_t));
       
   822 	if (find_lock[OP_DSA] == NULL)
       
   823 		goto malloc_err;
       
   824 	(void) pthread_mutex_init(find_lock[OP_DSA], NULL);
       
   825 #endif /* OPENSSL_NO_DSA */
       
   826 
       
   827 #ifndef OPENSSL_NO_DH
       
   828 	find_lock[OP_DH] = OPENSSL_malloc(sizeof (pthread_mutex_t));
       
   829 	if (find_lock[OP_DH] == NULL)
       
   830 		goto malloc_err;
       
   831 	(void) pthread_mutex_init(find_lock[OP_DH], NULL);
       
   832 #endif /* OPENSSL_NO_DH */
       
   833 
       
   834 	for (type = 0; type < OP_MAX; type++)
       
   835 		{
       
   836 		session_cache[type].lock =
       
   837 		    OPENSSL_malloc(sizeof (pthread_mutex_t));
       
   838 		if (session_cache[type].lock == NULL)
       
   839 			goto malloc_err;
       
   840 		(void) pthread_mutex_init(session_cache[type].lock, NULL);
       
   841 		}
       
   842 
       
   843 	return (1);
       
   844 
       
   845 malloc_err:
       
   846 	pk11_free_all_locks();
       
   847 	PK11err(PK11_F_INIT_ALL_LOCKS, PK11_R_MALLOC_FAILURE);
       
   848 	return (0);
       
   849 	}
       
   850 
       
   851 static void pk11_free_all_locks(void)
       
   852 	{
       
   853 	int type;
       
   854 
       
   855 #ifndef OPENSSL_NO_RSA
       
   856 	if (find_lock[OP_RSA] != NULL)
       
   857 		{
       
   858 		(void) pthread_mutex_destroy(find_lock[OP_RSA]);
       
   859 		OPENSSL_free(find_lock[OP_RSA]);
       
   860 		find_lock[OP_RSA] = NULL;
       
   861 		}
       
   862 #endif /* OPENSSL_NO_RSA */
       
   863 #ifndef OPENSSL_NO_DSA
       
   864 	if (find_lock[OP_DSA] != NULL)
       
   865 		{
       
   866 		(void) pthread_mutex_destroy(find_lock[OP_DSA]);
       
   867 		OPENSSL_free(find_lock[OP_DSA]);
       
   868 		find_lock[OP_DSA] = NULL;
       
   869 		}
       
   870 #endif /* OPENSSL_NO_DSA */
       
   871 #ifndef OPENSSL_NO_DH
       
   872 	if (find_lock[OP_DH] != NULL)
       
   873 		{
       
   874 		(void) pthread_mutex_destroy(find_lock[OP_DH]);
       
   875 		OPENSSL_free(find_lock[OP_DH]);
       
   876 		find_lock[OP_DH] = NULL;
       
   877 		}
       
   878 #endif /* OPENSSL_NO_DH */
       
   879 
       
   880 	for (type = 0; type < OP_MAX; type++)
       
   881 		{
       
   882 		if (session_cache[type].lock != NULL)
       
   883 			{
       
   884 			(void) pthread_mutex_destroy(session_cache[type].lock);
       
   885 			OPENSSL_free(session_cache[type].lock);
       
   886 			session_cache[type].lock = NULL;
       
   887 			}
       
   888 		}
       
   889 	}
       
   890 
       
   891 /*
       
   892  * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
       
   893  */
       
   894 static int bind_pk11(ENGINE *e)
       
   895 	{
       
   896 #ifndef OPENSSL_NO_RSA
       
   897 	const RSA_METHOD *rsa = NULL;
       
   898 	RSA_METHOD *pk11_rsa = PK11_RSA();
       
   899 #endif	/* OPENSSL_NO_RSA */
       
   900 	if (!pk11_library_initialized)
       
   901 		if (!pk11_library_init(e))
       
   902 			return (0);
       
   903 
       
   904 	if (!ENGINE_set_id(e, engine_pk11_id) ||
       
   905 	    !ENGINE_set_name(e, engine_pk11_name) ||
       
   906 	    !ENGINE_set_ciphers(e, pk11_engine_ciphers) ||
       
   907 	    !ENGINE_set_digests(e, pk11_engine_digests))
       
   908 		return (0);
       
   909 #ifndef OPENSSL_NO_RSA
       
   910 	if (pk11_have_rsa == CK_TRUE)
       
   911 		{
       
   912 		if (!ENGINE_set_RSA(e, PK11_RSA()) ||
       
   913 		    !ENGINE_set_load_privkey_function(e, pk11_load_privkey) ||
       
   914 		    !ENGINE_set_load_pubkey_function(e, pk11_load_pubkey))
       
   915 			return (0);
       
   916 		DEBUG_SLOT_SEL("%s: registered RSA\n", PK11_DBG);
       
   917 		}
       
   918 #endif	/* OPENSSL_NO_RSA */
       
   919 #ifndef OPENSSL_NO_DSA
       
   920 	if (pk11_have_dsa == CK_TRUE)
       
   921 		{
       
   922 		if (!ENGINE_set_DSA(e, PK11_DSA()))
       
   923 			return (0);
       
   924 		DEBUG_SLOT_SEL("%s: registered DSA\n", PK11_DBG);
       
   925 		}
       
   926 #endif	/* OPENSSL_NO_DSA */
       
   927 #ifndef OPENSSL_NO_DH
       
   928 	if (pk11_have_dh == CK_TRUE)
       
   929 		{
       
   930 		if (!ENGINE_set_DH(e, PK11_DH()))
       
   931 			return (0);
       
   932 		DEBUG_SLOT_SEL("%s: registered DH\n", PK11_DBG);
       
   933 		}
       
   934 #endif	/* OPENSSL_NO_DH */
       
   935 	if (pk11_have_random)
       
   936 		{
       
   937 		if (!ENGINE_set_RAND(e, &pk11_random))
       
   938 			return (0);
       
   939 		DEBUG_SLOT_SEL("%s: registered random\n", PK11_DBG);
       
   940 		}
       
   941 	if (!ENGINE_set_init_function(e, pk11_init) ||
       
   942 	    !ENGINE_set_destroy_function(e, pk11_destroy) ||
       
   943 	    !ENGINE_set_finish_function(e, pk11_finish) ||
       
   944 	    !ENGINE_set_ctrl_function(e, pk11_ctrl) ||
       
   945 	    !ENGINE_set_cmd_defns(e, pk11_cmd_defns))
       
   946 		return (0);
       
   947 
       
   948 /*
       
   949  * Apache calls OpenSSL function RSA_blinding_on() once during startup
       
   950  * which in turn calls bn_mod_exp. Since we do not implement bn_mod_exp
       
   951  * here, we wire it back to the OpenSSL software implementation.
       
   952  * Since it is used only once, performance is not a concern.
       
   953  */
       
   954 #ifndef OPENSSL_NO_RSA
       
   955 	rsa = RSA_PKCS1_SSLeay();
       
   956 	pk11_rsa->rsa_mod_exp = rsa->rsa_mod_exp;
       
   957 	pk11_rsa->bn_mod_exp = rsa->bn_mod_exp;
       
   958 #endif	/* OPENSSL_NO_RSA */
       
   959 
       
   960 	/* Ensure the pk11 error handling is set up */
       
   961 	ERR_load_pk11_strings();
       
   962 
       
   963 	return (1);
       
   964 	}
       
   965 
       
   966 /* Dynamic engine support is disabled at a higher level for Solaris */
       
   967 #ifdef	ENGINE_DYNAMIC_SUPPORT
       
   968 static int bind_helper(ENGINE *e, const char *id)
       
   969 	{
       
   970 	if (id && (strcmp(id, engine_pk11_id) != 0))
       
   971 		return (0);
       
   972 
       
   973 	if (!bind_pk11(e))
       
   974 		return (0);
       
   975 
       
   976 	return (1);
       
   977 	}
       
   978 
       
   979 IMPLEMENT_DYNAMIC_CHECK_FN()
       
   980 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
       
   981 
       
   982 #else
       
   983 static ENGINE *engine_pk11(void)
       
   984 	{
       
   985 	ENGINE *ret = ENGINE_new();
       
   986 
       
   987 	if (!ret)
       
   988 		return (NULL);
       
   989 
       
   990 	if (!bind_pk11(ret))
       
   991 		{
       
   992 		ENGINE_free(ret);
       
   993 		return (NULL);
       
   994 		}
       
   995 
       
   996 	return (ret);
       
   997 	}
       
   998 
       
   999 void
       
  1000 ENGINE_load_pk11(void)
       
  1001 	{
       
  1002 	ENGINE *e_pk11 = NULL;
       
  1003 
       
  1004 	/*
       
  1005 	 * Do not use dynamic PKCS#11 library on Solaris due to
       
  1006 	 * security reasons. We will link it in statically.
       
  1007 	 */
       
  1008 	/* Attempt to load PKCS#11 library */
       
  1009 	if (!pk11_dso)
       
  1010 		pk11_dso = DSO_load(NULL, get_PK11_LIBNAME(), NULL, 0);
       
  1011 
       
  1012 	if (pk11_dso == NULL)
       
  1013 		{
       
  1014 		PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
       
  1015 		return;
       
  1016 		}
       
  1017 
       
  1018 	e_pk11 = engine_pk11();
       
  1019 	if (!e_pk11)
       
  1020 		{
       
  1021 		DSO_free(pk11_dso);
       
  1022 		pk11_dso = NULL;
       
  1023 		return;
       
  1024 		}
       
  1025 
       
  1026 	/*
       
  1027 	 * At this point, the pk11 shared library is either dynamically
       
  1028 	 * loaded or statically linked in. So, initialize the pk11
       
  1029 	 * library before calling ENGINE_set_default since the latter
       
  1030 	 * needs cipher and digest algorithm information
       
  1031 	 */
       
  1032 	if (!pk11_library_init(e_pk11))
       
  1033 		{
       
  1034 		DSO_free(pk11_dso);
       
  1035 		pk11_dso = NULL;
       
  1036 		ENGINE_free(e_pk11);
       
  1037 		return;
       
  1038 		}
       
  1039 
       
  1040 	ENGINE_add(e_pk11);
       
  1041 
       
  1042 	ENGINE_free(e_pk11);
       
  1043 	ERR_clear_error();
       
  1044 	}
       
  1045 #endif	/* ENGINE_DYNAMIC_SUPPORT */
       
  1046 
       
  1047 /*
       
  1048  * These are the static string constants for the DSO file name and
       
  1049  * the function symbol names to bind to.
       
  1050  */
       
  1051 static const char *PK11_LIBNAME = NULL;
       
  1052 
       
  1053 static const char *get_PK11_LIBNAME(void)
       
  1054 	{
       
  1055 	if (PK11_LIBNAME)
       
  1056 		return (PK11_LIBNAME);
       
  1057 
       
  1058 	return (def_PK11_LIBNAME);
       
  1059 	}
       
  1060 
       
  1061 static void free_PK11_LIBNAME(void)
       
  1062 	{
       
  1063 	if (PK11_LIBNAME)
       
  1064 		OPENSSL_free((void*)PK11_LIBNAME);
       
  1065 
       
  1066 	PK11_LIBNAME = NULL;
       
  1067 	}
       
  1068 
       
  1069 static long set_PK11_LIBNAME(const char *name)
       
  1070 	{
       
  1071 	free_PK11_LIBNAME();
       
  1072 
       
  1073 	return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
       
  1074 	}
       
  1075 
       
  1076 /* acquire all engine specific mutexes before fork */
       
  1077 static void pk11_fork_prepare(void)
       
  1078 	{
       
  1079 	int i;
       
  1080 
       
  1081 	if (!pk11_library_initialized)
       
  1082 		return;
       
  1083 
       
  1084 	LOCK_OBJSTORE(OP_RSA);
       
  1085 	LOCK_OBJSTORE(OP_DSA);
       
  1086 	LOCK_OBJSTORE(OP_DH);
       
  1087 	(void) pthread_mutex_lock(uri_lock);
       
  1088 	for (i = 0; i < OP_MAX; i++)
       
  1089 		{
       
  1090 		(void) pthread_mutex_lock(session_cache[i].lock);
       
  1091 		}
       
  1092 	}
       
  1093 
       
  1094 /* release all engine specific mutexes */
       
  1095 static void pk11_fork_parent(void)
       
  1096 	{
       
  1097 	int i;
       
  1098 
       
  1099 	if (!pk11_library_initialized)
       
  1100 		return;
       
  1101 
       
  1102 	for (i = OP_MAX - 1; i >= 0; i--)
       
  1103 		{
       
  1104 		(void) pthread_mutex_unlock(session_cache[i].lock);
       
  1105 		}
       
  1106 	UNLOCK_OBJSTORE(OP_DH);
       
  1107 	UNLOCK_OBJSTORE(OP_DSA);
       
  1108 	UNLOCK_OBJSTORE(OP_RSA);
       
  1109 	(void) pthread_mutex_unlock(uri_lock);
       
  1110 	}
       
  1111 
       
  1112 /*
       
  1113  * same situation as in parent - we need to unlock all locks to make them
       
  1114  * accessible to all threads.
       
  1115  */
       
  1116 static void pk11_fork_child(void)
       
  1117 	{
       
  1118 	int i;
       
  1119 
       
  1120 	if (!pk11_library_initialized)
       
  1121 		return;
       
  1122 
       
  1123 	for (i = OP_MAX - 1; i >= 0; i--)
       
  1124 		{
       
  1125 		(void) pthread_mutex_unlock(session_cache[i].lock);
       
  1126 		}
       
  1127 	UNLOCK_OBJSTORE(OP_DH);
       
  1128 	UNLOCK_OBJSTORE(OP_DSA);
       
  1129 	UNLOCK_OBJSTORE(OP_RSA);
       
  1130 	(void) pthread_mutex_unlock(uri_lock);
       
  1131 	}
       
  1132 
       
  1133 /* Initialization function for the pk11 engine */
       
  1134 static int pk11_init(ENGINE *e)
       
  1135 	{
       
  1136 	return (pk11_library_init(e));
       
  1137 	}
       
  1138 
       
  1139 /*
       
  1140  * Initialization function. Sets up various PKCS#11 library components.
       
  1141  * It selects a slot based on predefined critiera. In the process, it also
       
  1142  * count how many ciphers and digests to support. Since the cipher and
       
  1143  * digest information is needed when setting default engine, this function
       
  1144  * needs to be called before calling ENGINE_set_default.
       
  1145  */
       
  1146 /* ARGSUSED */
       
  1147 static int pk11_library_init(ENGINE *e)
       
  1148 	{
       
  1149 	CK_C_GetFunctionList p;
       
  1150 	CK_RV rv = CKR_OK;
       
  1151 	CK_INFO info;
       
  1152 	CK_ULONG ul_state_len;
       
  1153 	int any_slot_found;
       
  1154 	int i;
       
  1155 
       
  1156 	/*
       
  1157 	 * pk11_library_initialized is set to 0 in pk11_finish() which is called
       
  1158 	 * from ENGINE_finish(). However, if there is still at least one
       
  1159 	 * existing functional reference to the engine (see engine(3) for more
       
  1160 	 * information), pk11_finish() is skipped. For example, this can happen
       
  1161 	 * if an application forgets to clear one cipher context. In case of a
       
  1162 	 * fork() when the application is finishing the engine so that it can be
       
  1163 	 * reinitialized in the child, forgotten functional reference causes
       
  1164 	 * pk11_library_initialized to stay 1. In that case we need the PID
       
  1165 	 * check so that we properly initialize the engine again.
       
  1166 	 */
       
  1167 	if (pk11_library_initialized)
       
  1168 		{
       
  1169 		if (pk11_pid == getpid())
       
  1170 			{
       
  1171 			return (1);
       
  1172 			}
       
  1173 		else
       
  1174 			{
       
  1175 			global_session = CK_INVALID_HANDLE;
       
  1176 			/*
       
  1177 			 * free the locks first to prevent memory leak in case
       
  1178 			 * the application calls fork() without finishing the
       
  1179 			 * engine first.
       
  1180 			 */
       
  1181 			pk11_free_all_locks();
       
  1182 			}
       
  1183 		}
       
  1184 
       
  1185 	if (pk11_dso == NULL)
       
  1186 		{
       
  1187 		PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
       
  1188 		goto err;
       
  1189 		}
       
  1190 
       
  1191 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  1192 	if (check_hw_mechanisms() == 0)
       
  1193 		goto err;
       
  1194 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  1195 
       
  1196 	/* get the C_GetFunctionList function from the loaded library */
       
  1197 	p = (CK_C_GetFunctionList)DSO_bind_func(pk11_dso,
       
  1198 		PK11_GET_FUNCTION_LIST);
       
  1199 	if (!p)
       
  1200 		{
       
  1201 		PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
       
  1202 		goto err;
       
  1203 		}
       
  1204 
       
  1205 	/* get the full function list from the loaded library */
       
  1206 	rv = p(&pFuncList);
       
  1207 	if (rv != CKR_OK)
       
  1208 		{
       
  1209 		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE, rv);
       
  1210 		goto err;
       
  1211 		}
       
  1212 
       
  1213 	rv = pFuncList->C_Initialize(NULL_PTR);
       
  1214 	if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
       
  1215 		{
       
  1216 		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE, rv);
       
  1217 		goto err;
       
  1218 		}
       
  1219 
       
  1220 	rv = pFuncList->C_GetInfo(&info);
       
  1221 	if (rv != CKR_OK)
       
  1222 		{
       
  1223 		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_GETINFO, rv);
       
  1224 		goto err;
       
  1225 		}
       
  1226 
       
  1227 	if (pk11_choose_slots(&any_slot_found) == 0)
       
  1228 		goto err;
       
  1229 
       
  1230 	/*
       
  1231 	 * The library we use, set in def_PK11_LIBNAME, may not offer any
       
  1232 	 * slot(s). In that case, we must not proceed but we must not return an
       
  1233 	 * error. The reason is that applications that try to set up the PKCS#11
       
  1234 	 * engine don't exit on error during the engine initialization just
       
  1235 	 * because no slot was present.
       
  1236 	 */
       
  1237 	if (any_slot_found == 0)
       
  1238 		return (1);
       
  1239 
       
  1240 	if (global_session == CK_INVALID_HANDLE)
       
  1241 		{
       
  1242 		/* Open the global_session for the new process */
       
  1243 		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
       
  1244 			NULL_PTR, NULL_PTR, &global_session);
       
  1245 		if (rv != CKR_OK)
       
  1246 			{
       
  1247 			PK11err_add_data(PK11_F_LIBRARY_INIT,
       
  1248 			    PK11_R_OPENSESSION, rv);
       
  1249 			goto err;
       
  1250 			}
       
  1251 		}
       
  1252 
       
  1253 	/*
       
  1254 	 * Disable digest if C_GetOperationState is not supported since
       
  1255 	 * this function is required by OpenSSL digest copy function
       
  1256 	 */
       
  1257 	if (pFuncList->C_GetOperationState(global_session, NULL, &ul_state_len)
       
  1258 			== CKR_FUNCTION_NOT_SUPPORTED)
       
  1259 		{
       
  1260 		DEBUG_SLOT_SEL("%s: C_GetOperationState() not supported, "
       
  1261 		    "setting digest_count to 0\n", PK11_DBG);
       
  1262 		digest_count = 0;
       
  1263 		}
       
  1264 
       
  1265 	pk11_library_initialized = CK_TRUE;
       
  1266 	pk11_pid = getpid();
       
  1267 	/*
       
  1268 	 * if initialization of the locks fails pk11_init_all_locks()
       
  1269 	 * will do the cleanup.
       
  1270 	 */
       
  1271 	if (!pk11_init_all_locks())
       
  1272 		goto err;
       
  1273 	for (i = 0; i < OP_MAX; i++)
       
  1274 		session_cache[i].head = NULL;
       
  1275 	/*
       
  1276 	 * initialize active lists. We only use active lists
       
  1277 	 * for asymmetric ciphers.
       
  1278 	 */
       
  1279 	for (i = 0; i < OP_MAX; i++)
       
  1280 		active_list[i] = NULL;
       
  1281 
       
  1282 	if (!pk11_atfork_initialized)
       
  1283 		{
       
  1284 		if (pthread_atfork(pk11_fork_prepare, pk11_fork_parent,
       
  1285 		    pk11_fork_child) != 0)
       
  1286 			{
       
  1287 			PK11err(PK11_F_LIBRARY_INIT, PK11_R_ATFORK_FAILED);
       
  1288 			goto err;
       
  1289 			}
       
  1290 		pk11_atfork_initialized = CK_TRUE;
       
  1291 		}
       
  1292 
       
  1293 	return (1);
       
  1294 
       
  1295 err:
       
  1296 	return (0);
       
  1297 	}
       
  1298 
       
  1299 /* Destructor (complements the "ENGINE_pk11()" constructor) */
       
  1300 /* ARGSUSED */
       
  1301 static int pk11_destroy(ENGINE *e)
       
  1302 	{
       
  1303 	free_PK11_LIBNAME();
       
  1304 	ERR_unload_pk11_strings();
       
  1305 	return (1);
       
  1306 	}
       
  1307 
       
  1308 /*
       
  1309  * Termination function to clean up the session, the token, and the pk11
       
  1310  * library.
       
  1311  */
       
  1312 /* ARGSUSED */
       
  1313 static int pk11_finish(ENGINE *e)
       
  1314 	{
       
  1315 	int i;
       
  1316 
       
  1317 	if (pk11_dso == NULL)
       
  1318 		{
       
  1319 		PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
       
  1320 		goto err;
       
  1321 		}
       
  1322 
       
  1323 	OPENSSL_assert(pFuncList != NULL);
       
  1324 
       
  1325 	if (pk11_free_all_sessions() == 0)
       
  1326 		goto err;
       
  1327 
       
  1328 	/* free all active lists */
       
  1329 	for (i = 0; i < OP_MAX; i++)
       
  1330 		pk11_free_active_list(i);
       
  1331 
       
  1332 	pFuncList->C_CloseSession(global_session);
       
  1333 	global_session = CK_INVALID_HANDLE;
       
  1334 
       
  1335 	/*
       
  1336 	 * Since we are part of a library (libcrypto.so), calling this function
       
  1337 	 * may have side-effects.
       
  1338 	 */
       
  1339 #if 0
       
  1340 	pFuncList->C_Finalize(NULL);
       
  1341 #endif
       
  1342 	if (!DSO_free(pk11_dso))
       
  1343 		{
       
  1344 		PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
       
  1345 		goto err;
       
  1346 		}
       
  1347 	pk11_dso = NULL;
       
  1348 	pFuncList = NULL;
       
  1349 	pk11_library_initialized = CK_FALSE;
       
  1350 	pk11_pid = 0;
       
  1351 	/*
       
  1352 	 * There is no way how to unregister atfork handlers (other than
       
  1353 	 * unloading the library) so we just free the locks. For this reason
       
  1354 	 * the atfork handlers check if the engine is initialized and bail out
       
  1355 	 * immediately if not. This is necessary in case a process finishes
       
  1356 	 * the engine before calling fork().
       
  1357 	 */
       
  1358 	pk11_free_all_locks();
       
  1359 
       
  1360 	return (1);
       
  1361 
       
  1362 err:
       
  1363 	return (0);
       
  1364 	}
       
  1365 
       
  1366 /* Standard engine interface function to set the dynamic library path */
       
  1367 /* ARGSUSED */
       
  1368 static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
       
  1369 	{
       
  1370 	int initialized = ((pk11_dso == NULL) ? 0 : 1);
       
  1371 
       
  1372 	switch (cmd)
       
  1373 		{
       
  1374 	case PK11_CMD_SO_PATH:
       
  1375 		if (p == NULL)
       
  1376 			{
       
  1377 			PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
       
  1378 			return (0);
       
  1379 			}
       
  1380 
       
  1381 		if (initialized)
       
  1382 			{
       
  1383 			PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
       
  1384 			return (0);
       
  1385 			}
       
  1386 
       
  1387 		return (set_PK11_LIBNAME((const char *)p));
       
  1388 	default:
       
  1389 		break;
       
  1390 		}
       
  1391 
       
  1392 	PK11err(PK11_F_CTRL, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
       
  1393 
       
  1394 	return (0);
       
  1395 	}
       
  1396 
       
  1397 
       
  1398 /* Required function by the engine random interface. It does nothing here */
       
  1399 static void pk11_rand_cleanup(void)
       
  1400 	{
       
  1401 	return;
       
  1402 	}
       
  1403 
       
  1404 /* ARGSUSED */
       
  1405 static void pk11_rand_add(const void *buf, int num, double add)
       
  1406 	{
       
  1407 	PK11_SESSION *sp;
       
  1408 
       
  1409 	if ((sp = pk11_get_session(OP_RAND)) == NULL)
       
  1410 		return;
       
  1411 
       
  1412 	/*
       
  1413 	 * Ignore any errors (e.g. CKR_RANDOM_SEED_NOT_SUPPORTED) since
       
  1414 	 * the calling functions do not care anyway
       
  1415 	 */
       
  1416 	pFuncList->C_SeedRandom(sp->session, (unsigned char *) buf, num);
       
  1417 	pk11_return_session(sp, OP_RAND);
       
  1418 
       
  1419 	return;
       
  1420 	}
       
  1421 
       
  1422 static void pk11_rand_seed(const void *buf, int num)
       
  1423 	{
       
  1424 	pk11_rand_add(buf, num, 0);
       
  1425 	}
       
  1426 
       
  1427 static int pk11_rand_bytes(unsigned char *buf, int num)
       
  1428 	{
       
  1429 	CK_RV rv;
       
  1430 	PK11_SESSION *sp;
       
  1431 
       
  1432 	if ((sp = pk11_get_session(OP_RAND)) == NULL)
       
  1433 		return (0);
       
  1434 
       
  1435 	rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
       
  1436 	if (rv != CKR_OK)
       
  1437 		{
       
  1438 		PK11err_add_data(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM, rv);
       
  1439 		pk11_return_session(sp, OP_RAND);
       
  1440 		return (0);
       
  1441 		}
       
  1442 
       
  1443 	pk11_return_session(sp, OP_RAND);
       
  1444 	return (1);
       
  1445 	}
       
  1446 
       
  1447 /* Required function by the engine random interface. It does nothing here */
       
  1448 static int pk11_rand_status(void)
       
  1449 	{
       
  1450 	return (1);
       
  1451 	}
       
  1452 
       
  1453 /* Free all BIGNUM structures from PK11_SESSION. */
       
  1454 static void pk11_free_nums(PK11_SESSION *sp, PK11_OPTYPE optype)
       
  1455 	{
       
  1456 	switch (optype)
       
  1457 		{
       
  1458 #ifndef	OPENSSL_NO_RSA
       
  1459 		case OP_RSA:
       
  1460 			if (sp->opdata_rsa_n_num != NULL)
       
  1461 				{
       
  1462 				BN_free(sp->opdata_rsa_n_num);
       
  1463 				sp->opdata_rsa_n_num = NULL;
       
  1464 				}
       
  1465 			if (sp->opdata_rsa_e_num != NULL)
       
  1466 				{
       
  1467 				BN_free(sp->opdata_rsa_e_num);
       
  1468 				sp->opdata_rsa_e_num = NULL;
       
  1469 				}
       
  1470 			if (sp->opdata_rsa_d_num != NULL)
       
  1471 				{
       
  1472 				BN_free(sp->opdata_rsa_d_num);
       
  1473 				sp->opdata_rsa_d_num = NULL;
       
  1474 				}
       
  1475 			break;
       
  1476 #endif
       
  1477 #ifndef	OPENSSL_NO_DSA
       
  1478 		case OP_DSA:
       
  1479 			if (sp->opdata_dsa_pub_num != NULL)
       
  1480 				{
       
  1481 				BN_free(sp->opdata_dsa_pub_num);
       
  1482 				sp->opdata_dsa_pub_num = NULL;
       
  1483 				}
       
  1484 			if (sp->opdata_dsa_priv_num != NULL)
       
  1485 				{
       
  1486 				BN_free(sp->opdata_dsa_priv_num);
       
  1487 				sp->opdata_dsa_priv_num = NULL;
       
  1488 				}
       
  1489 			break;
       
  1490 #endif
       
  1491 #ifndef	OPENSSL_NO_DH
       
  1492 		case OP_DH:
       
  1493 			if (sp->opdata_dh_priv_num != NULL)
       
  1494 				{
       
  1495 				BN_free(sp->opdata_dh_priv_num);
       
  1496 				sp->opdata_dh_priv_num = NULL;
       
  1497 				}
       
  1498 			break;
       
  1499 #endif
       
  1500 		default:
       
  1501 			break;
       
  1502 		}
       
  1503 	}
       
  1504 
       
  1505 /*
       
  1506  * Get new PK11_SESSION structure ready for use. Every process must have
       
  1507  * its own freelist of PK11_SESSION structures so handle fork() here
       
  1508  * by destroying the old and creating new freelist.
       
  1509  * The returned PK11_SESSION structure is disconnected from the freelist.
       
  1510  */
       
  1511 PK11_SESSION *
       
  1512 pk11_get_session(PK11_OPTYPE optype)
       
  1513 	{
       
  1514 	PK11_SESSION *sp = NULL, *sp1, *freelist;
       
  1515 	pthread_mutex_t *freelist_lock;
       
  1516 	static pid_t pid = 0;
       
  1517 	pid_t new_pid;
       
  1518 	CK_RV rv;
       
  1519 
       
  1520 	switch (optype)
       
  1521 		{
       
  1522 		case OP_RSA:
       
  1523 		case OP_DSA:
       
  1524 		case OP_DH:
       
  1525 		case OP_RAND:
       
  1526 		case OP_DIGEST:
       
  1527 		case OP_CIPHER:
       
  1528 			freelist_lock = session_cache[optype].lock;
       
  1529 			break;
       
  1530 		default:
       
  1531 			PK11err(PK11_F_GET_SESSION,
       
  1532 				PK11_R_INVALID_OPERATION_TYPE);
       
  1533 			return (NULL);
       
  1534 		}
       
  1535 	(void) pthread_mutex_lock(freelist_lock);
       
  1536 
       
  1537 	/*
       
  1538 	 * Will use it to find out if we forked. We cannot use the PID field in
       
  1539 	 * the session structure because we could get a newly allocated session
       
  1540 	 * here, with no PID information.
       
  1541 	 */
       
  1542 	if (pid == 0)
       
  1543 		pid = getpid();
       
  1544 
       
  1545 	freelist = session_cache[optype].head;
       
  1546 	sp = freelist;
       
  1547 
       
  1548 	/*
       
  1549 	 * If the free list is empty, allocate new uninitialized (filled
       
  1550 	 * with zeroes) PK11_SESSION structure otherwise return first
       
  1551 	 * structure from the freelist.
       
  1552 	 */
       
  1553 	if (sp == NULL)
       
  1554 		{
       
  1555 		if ((sp = OPENSSL_malloc(sizeof (PK11_SESSION))) == NULL)
       
  1556 			{
       
  1557 			PK11err(PK11_F_GET_SESSION,
       
  1558 				PK11_R_MALLOC_FAILURE);
       
  1559 			goto err;
       
  1560 			}
       
  1561 		(void) memset(sp, 0, sizeof (PK11_SESSION));
       
  1562 
       
  1563 		/*
       
  1564 		 * It is a new session so it will look like a cache miss to the
       
  1565 		 * code below. So, we must not try to to destroy its members so
       
  1566 		 * mark them as unused.
       
  1567 		 */
       
  1568 		sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
       
  1569 		sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
       
  1570 		}
       
  1571 	else
       
  1572 		freelist = sp->next;
       
  1573 
       
  1574 	/*
       
  1575 	 * Check whether we have forked. In that case, we must get rid of all
       
  1576 	 * inherited sessions and start allocating new ones.
       
  1577 	 */
       
  1578 	if (pid != (new_pid = getpid()))
       
  1579 		{
       
  1580 		pid = new_pid;
       
  1581 
       
  1582 		/*
       
  1583 		 * We are a new process and thus need to free any inherited
       
  1584 		 * PK11_SESSION objects aside from the first session (sp) which
       
  1585 		 * is the only PK11_SESSION structure we will reuse (for the
       
  1586 		 * head of the list).
       
  1587 		 */
       
  1588 		while ((sp1 = freelist) != NULL)
       
  1589 			{
       
  1590 			freelist = sp1->next;
       
  1591 			/*
       
  1592 			 * NOTE: we do not want to call pk11_free_all_sessions()
       
  1593 			 * here because it would close underlying PKCS#11
       
  1594 			 * sessions and destroy all objects.
       
  1595 			 */
       
  1596 			pk11_free_nums(sp1, optype);
       
  1597 			OPENSSL_free(sp1);
       
  1598 			}
       
  1599 
       
  1600 		/* we have to free the active list as well. */
       
  1601 		pk11_free_active_list(optype);
       
  1602 
       
  1603 		/* Initialize the process */
       
  1604 		rv = pFuncList->C_Initialize(NULL_PTR);
       
  1605 		if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
       
  1606 			{
       
  1607 			PK11err_add_data(PK11_F_GET_SESSION, PK11_R_INITIALIZE,
       
  1608 			    rv);
       
  1609 			OPENSSL_free(sp);
       
  1610 			sp = NULL;
       
  1611 			goto err;
       
  1612 			}
       
  1613 
       
  1614 		/*
       
  1615 		 * Choose slot here since the slot table is different on this
       
  1616 		 * process. If we are here then we must have found at least one
       
  1617 		 * usable slot before so we don't need to check any_slot_found.
       
  1618 		 * See pk11_library_init()'s usage of this function for more
       
  1619 		 * information.
       
  1620 		 */
       
  1621 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  1622 		if (check_hw_mechanisms() == 0)
       
  1623 			goto err;
       
  1624 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  1625 		if (pk11_choose_slots(NULL) == 0)
       
  1626 			goto err;
       
  1627 
       
  1628 		/* Open the global_session for the new process */
       
  1629 		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
       
  1630 			NULL_PTR, NULL_PTR, &global_session);
       
  1631 		if (rv != CKR_OK)
       
  1632 			{
       
  1633 			PK11err_add_data(PK11_F_GET_SESSION, PK11_R_OPENSESSION,
       
  1634 			    rv);
       
  1635 			OPENSSL_free(sp);
       
  1636 			sp = NULL;
       
  1637 			goto err;
       
  1638 			}
       
  1639 
       
  1640 		/*
       
  1641 		 * It is an inherited session from our parent so it needs
       
  1642 		 * re-initialization.
       
  1643 		 */
       
  1644 		if (pk11_setup_session(sp, optype) == 0)
       
  1645 			{
       
  1646 			OPENSSL_free(sp);
       
  1647 			sp = NULL;
       
  1648 			goto err;
       
  1649 			}
       
  1650 		if (pk11_token_relogin(sp->session) == 0)
       
  1651 			{
       
  1652 			/*
       
  1653 			 * We will keep the session in the cache list and let
       
  1654 			 * the caller cope with the situation.
       
  1655 			 */
       
  1656 			freelist = sp;
       
  1657 			sp = NULL;
       
  1658 			goto err;
       
  1659 			}
       
  1660 		}
       
  1661 
       
  1662 	if (sp->pid == 0)
       
  1663 		{
       
  1664 		/* It is a new session and needs initialization. */
       
  1665 		if (pk11_setup_session(sp, optype) == 0)
       
  1666 			{
       
  1667 			OPENSSL_free(sp);
       
  1668 			sp = NULL;
       
  1669 			}
       
  1670 		}
       
  1671 
       
  1672 	/* set new head for the list of PK11_SESSION objects */
       
  1673 	session_cache[optype].head = freelist;
       
  1674 
       
  1675 err:
       
  1676 	if (sp != NULL)
       
  1677 		sp->next = NULL;
       
  1678 
       
  1679 	(void) pthread_mutex_unlock(freelist_lock);
       
  1680 
       
  1681 	return (sp);
       
  1682 	}
       
  1683 
       
  1684 
       
  1685 void
       
  1686 pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype)
       
  1687 	{
       
  1688 	pthread_mutex_t *freelist_lock;
       
  1689 	PK11_SESSION *freelist;
       
  1690 
       
  1691 	/*
       
  1692 	 * If this is a session from the parent it will be taken care of and
       
  1693 	 * freed in pk11_get_session() as part of the post-fork clean up the
       
  1694 	 * next time we will ask for a new session.
       
  1695 	 */
       
  1696 	if (sp == NULL || sp->pid != getpid())
       
  1697 		return;
       
  1698 
       
  1699 	switch (optype)
       
  1700 		{
       
  1701 		case OP_RSA:
       
  1702 		case OP_DSA:
       
  1703 		case OP_DH:
       
  1704 		case OP_RAND:
       
  1705 		case OP_DIGEST:
       
  1706 		case OP_CIPHER:
       
  1707 			freelist_lock = session_cache[optype].lock;
       
  1708 			break;
       
  1709 		default:
       
  1710 			PK11err(PK11_F_RETURN_SESSION,
       
  1711 				PK11_R_INVALID_OPERATION_TYPE);
       
  1712 			return;
       
  1713 		}
       
  1714 
       
  1715 	(void) pthread_mutex_lock(freelist_lock);
       
  1716 	freelist = session_cache[optype].head;
       
  1717 	sp->next = freelist;
       
  1718 	session_cache[optype].head = sp;
       
  1719 	(void) pthread_mutex_unlock(freelist_lock);
       
  1720 	}
       
  1721 
       
  1722 
       
  1723 /* Destroy all objects. This function is called when the engine is finished */
       
  1724 static int pk11_free_all_sessions()
       
  1725 	{
       
  1726 	int ret = 1;
       
  1727 	int type;
       
  1728 
       
  1729 #ifndef OPENSSL_NO_RSA
       
  1730 	(void) pk11_destroy_rsa_key_objects(NULL);
       
  1731 #endif	/* OPENSSL_NO_RSA */
       
  1732 #ifndef OPENSSL_NO_DSA
       
  1733 	(void) pk11_destroy_dsa_key_objects(NULL);
       
  1734 #endif	/* OPENSSL_NO_DSA */
       
  1735 #ifndef OPENSSL_NO_DH
       
  1736 	(void) pk11_destroy_dh_key_objects(NULL);
       
  1737 #endif	/* OPENSSL_NO_DH */
       
  1738 	(void) pk11_destroy_cipher_key_objects(NULL);
       
  1739 
       
  1740 	/*
       
  1741 	 * We try to release as much as we can but any error means that we will
       
  1742 	 * return 0 on exit.
       
  1743 	 */
       
  1744 	for (type = 0; type < OP_MAX; type++)
       
  1745 		{
       
  1746 		if (pk11_free_session_list(type) == 0)
       
  1747 			ret = 0;
       
  1748 		}
       
  1749 
       
  1750 	return (ret);
       
  1751 	}
       
  1752 
       
  1753 /*
       
  1754  * Destroy session structures from the linked list specified. Free as many
       
  1755  * sessions as possible but any failure in C_CloseSession() means that we
       
  1756  * return an error on return.
       
  1757  */
       
  1758 static int pk11_free_session_list(PK11_OPTYPE optype)
       
  1759 	{
       
  1760 	CK_RV rv;
       
  1761 	PK11_SESSION *sp = NULL;
       
  1762 	PK11_SESSION *freelist = NULL;
       
  1763 	pid_t mypid = getpid();
       
  1764 	pthread_mutex_t *freelist_lock;
       
  1765 	int ret = 1;
       
  1766 
       
  1767 	switch (optype)
       
  1768 		{
       
  1769 		case OP_RSA:
       
  1770 		case OP_DSA:
       
  1771 		case OP_DH:
       
  1772 		case OP_RAND:
       
  1773 		case OP_DIGEST:
       
  1774 		case OP_CIPHER:
       
  1775 			freelist_lock = session_cache[optype].lock;
       
  1776 			break;
       
  1777 		default:
       
  1778 			PK11err(PK11_F_FREE_ALL_SESSIONS,
       
  1779 				PK11_R_INVALID_OPERATION_TYPE);
       
  1780 			return (0);
       
  1781 		}
       
  1782 
       
  1783 	(void) pthread_mutex_lock(freelist_lock);
       
  1784 	freelist = session_cache[optype].head;
       
  1785 	while ((sp = freelist) != NULL)
       
  1786 		{
       
  1787 		if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
       
  1788 			{
       
  1789 			rv = pFuncList->C_CloseSession(sp->session);
       
  1790 			if (rv != CKR_OK)
       
  1791 				{
       
  1792 				PK11err_add_data(PK11_F_FREE_ALL_SESSIONS,
       
  1793 					PK11_R_CLOSESESSION, rv);
       
  1794 				ret = 0;
       
  1795 				}
       
  1796 			}
       
  1797 		freelist = sp->next;
       
  1798 		pk11_free_nums(sp, optype);
       
  1799 		OPENSSL_free(sp);
       
  1800 		}
       
  1801 
       
  1802 	(void) pthread_mutex_unlock(freelist_lock);
       
  1803 	return (ret);
       
  1804 	}
       
  1805 
       
  1806 
       
  1807 static int
       
  1808 pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype)
       
  1809 	{
       
  1810 	CK_RV rv;
       
  1811 	CK_SLOT_ID myslot;
       
  1812 
       
  1813 	switch (optype)
       
  1814 		{
       
  1815 		case OP_RSA:
       
  1816 		case OP_DSA:
       
  1817 		case OP_DH:
       
  1818 			myslot = pubkey_SLOTID;
       
  1819 			break;
       
  1820 		case OP_RAND:
       
  1821 			myslot = rand_SLOTID;
       
  1822 			break;
       
  1823 		case OP_DIGEST:
       
  1824 		case OP_CIPHER:
       
  1825 			myslot = SLOTID;
       
  1826 			break;
       
  1827 		default:
       
  1828 			PK11err(PK11_F_SETUP_SESSION,
       
  1829 			    PK11_R_INVALID_OPERATION_TYPE);
       
  1830 			return (0);
       
  1831 		}
       
  1832 
       
  1833 	sp->session = CK_INVALID_HANDLE;
       
  1834 	DEBUG_SLOT_SEL("%s: myslot=%d optype=%d\n", PK11_DBG, myslot, optype);
       
  1835 	rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
       
  1836 		NULL_PTR, NULL_PTR, &sp->session);
       
  1837 	if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
       
  1838 		{
       
  1839 		/*
       
  1840 		 * We are probably a child process so force the
       
  1841 		 * reinitialize of the session
       
  1842 		 */
       
  1843 		pk11_library_initialized = CK_FALSE;
       
  1844 		if (!pk11_library_init(NULL))
       
  1845 			return (0);
       
  1846 		rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
       
  1847 			NULL_PTR, NULL_PTR, &sp->session);
       
  1848 		}
       
  1849 	if (rv != CKR_OK)
       
  1850 		{
       
  1851 		PK11err_add_data(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION, rv);
       
  1852 		return (0);
       
  1853 		}
       
  1854 
       
  1855 	sp->pid = getpid();
       
  1856 
       
  1857 	switch (optype)
       
  1858 		{
       
  1859 #ifndef OPENSSL_NO_RSA
       
  1860 		case OP_RSA:
       
  1861 			sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
       
  1862 			sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
       
  1863 			sp->opdata_rsa_pub = NULL;
       
  1864 			sp->opdata_rsa_n_num = NULL;
       
  1865 			sp->opdata_rsa_e_num = NULL;
       
  1866 			sp->opdata_rsa_priv = NULL;
       
  1867 			sp->opdata_rsa_d_num = NULL;
       
  1868 			break;
       
  1869 #endif	/* OPENSSL_NO_RSA */
       
  1870 #ifndef OPENSSL_NO_DSA
       
  1871 		case OP_DSA:
       
  1872 			sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
       
  1873 			sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
       
  1874 			sp->opdata_dsa_pub = NULL;
       
  1875 			sp->opdata_dsa_pub_num = NULL;
       
  1876 			sp->opdata_dsa_priv = NULL;
       
  1877 			sp->opdata_dsa_priv_num = NULL;
       
  1878 			break;
       
  1879 #endif	/* OPENSSL_NO_DSA */
       
  1880 #ifndef OPENSSL_NO_DH
       
  1881 		case OP_DH:
       
  1882 			sp->opdata_dh_key = CK_INVALID_HANDLE;
       
  1883 			sp->opdata_dh = NULL;
       
  1884 			sp->opdata_dh_priv_num = NULL;
       
  1885 			break;
       
  1886 #endif	/* OPENSSL_NO_DH */
       
  1887 		case OP_CIPHER:
       
  1888 			sp->opdata_cipher_key = CK_INVALID_HANDLE;
       
  1889 			sp->opdata_encrypt = -1;
       
  1890 			break;
       
  1891 		}
       
  1892 
       
  1893 	/*
       
  1894 	 * We always initialize the session as containing a non-persistent
       
  1895 	 * object. The key load functions set it to persistent if that is so.
       
  1896 	 */
       
  1897 	sp->persistent = CK_FALSE;
       
  1898 	return (1);
       
  1899 	}
       
  1900 
       
  1901 #ifndef OPENSSL_NO_RSA
       
  1902 /*
       
  1903  * Destroy all non-NULL RSA parameters. For the RSA keys by reference code,
       
  1904  * public components 'n'/'e' are the key components we use to check for the
       
  1905  * cache hit even for the private keys. So, no matter whether we are destroying
       
  1906  * a public or a private key, we always free what we can.
       
  1907  */
       
  1908 static void
       
  1909 destroy_all_rsa_params(PK11_SESSION *sp)
       
  1910 	{
       
  1911 	if (sp->opdata_rsa_n_num != NULL)
       
  1912 		{
       
  1913 		BN_free(sp->opdata_rsa_n_num);
       
  1914 		sp->opdata_rsa_n_num = NULL;
       
  1915 		}
       
  1916 	if (sp->opdata_rsa_e_num != NULL)
       
  1917 		{
       
  1918 		BN_free(sp->opdata_rsa_e_num);
       
  1919 		sp->opdata_rsa_e_num = NULL;
       
  1920 		}
       
  1921 	if (sp->opdata_rsa_d_num != NULL)
       
  1922 		{
       
  1923 		BN_free(sp->opdata_rsa_d_num);
       
  1924 		sp->opdata_rsa_d_num = NULL;
       
  1925 		}
       
  1926 	}
       
  1927 
       
  1928 /* Destroy RSA public key from single session. */
       
  1929 int
       
  1930 pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
       
  1931 	{
       
  1932 	int ret = 0;
       
  1933 
       
  1934 	if (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE)
       
  1935 		{
       
  1936 		TRY_OBJ_DESTROY(sp, sp->opdata_rsa_pub_key,
       
  1937 		    ret, uselock, OP_RSA);
       
  1938 		sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
       
  1939 		sp->opdata_rsa_pub = NULL;
       
  1940 		destroy_all_rsa_params(sp);
       
  1941 		}
       
  1942 
       
  1943 	return (ret);
       
  1944 	}
       
  1945 
       
  1946 /* Destroy RSA private key from single session. */
       
  1947 int
       
  1948 pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
       
  1949 	{
       
  1950 	int ret = 0;
       
  1951 
       
  1952 	if (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE)
       
  1953 		{
       
  1954 		TRY_OBJ_DESTROY(sp, sp->opdata_rsa_priv_key,
       
  1955 		    ret, uselock, OP_RSA);
       
  1956 		sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
       
  1957 		sp->opdata_rsa_priv = NULL;
       
  1958 		destroy_all_rsa_params(sp);
       
  1959 		}
       
  1960 
       
  1961 	return (ret);
       
  1962 	}
       
  1963 
       
  1964 /*
       
  1965  * Destroy RSA key object wrapper. If session is NULL, try to destroy all
       
  1966  * objects in the free list.
       
  1967  */
       
  1968 int
       
  1969 pk11_destroy_rsa_key_objects(PK11_SESSION *session)
       
  1970 	{
       
  1971 	int ret = 1;
       
  1972 	PK11_SESSION *sp = NULL;
       
  1973 	PK11_SESSION *local_free_session;
       
  1974 	CK_BBOOL uselock = CK_TRUE;
       
  1975 
       
  1976 	if (session != NULL)
       
  1977 		local_free_session = session;
       
  1978 	else
       
  1979 		{
       
  1980 		(void) pthread_mutex_lock(session_cache[OP_RSA].lock);
       
  1981 		local_free_session = session_cache[OP_RSA].head;
       
  1982 		uselock = CK_FALSE;
       
  1983 		}
       
  1984 
       
  1985 	/*
       
  1986 	 * go through the list of sessions and delete key objects
       
  1987 	 */
       
  1988 	while ((sp = local_free_session) != NULL)
       
  1989 		{
       
  1990 		local_free_session = sp->next;
       
  1991 
       
  1992 		/*
       
  1993 		 * Do not terminate list traversal if one of the
       
  1994 		 * destroy operations fails.
       
  1995 		 */
       
  1996 		if (pk11_destroy_rsa_object_pub(sp, uselock) == 0)
       
  1997 			{
       
  1998 			ret = 0;
       
  1999 			continue;
       
  2000 			}
       
  2001 		if (pk11_destroy_rsa_object_priv(sp, uselock) == 0)
       
  2002 			{
       
  2003 			ret = 0;
       
  2004 			continue;
       
  2005 			}
       
  2006 		}
       
  2007 
       
  2008 	if (session == NULL)
       
  2009 		(void) pthread_mutex_unlock(session_cache[OP_RSA].lock);
       
  2010 
       
  2011 	return (ret);
       
  2012 	}
       
  2013 #endif	/* OPENSSL_NO_RSA */
       
  2014 
       
  2015 #ifndef OPENSSL_NO_DSA
       
  2016 /* Destroy DSA public key from single session. */
       
  2017 int
       
  2018 pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
       
  2019 	{
       
  2020 	int ret = 0;
       
  2021 
       
  2022 	if (sp->opdata_dsa_pub_key != CK_INVALID_HANDLE)
       
  2023 		{
       
  2024 		TRY_OBJ_DESTROY(sp, sp->opdata_dsa_pub_key,
       
  2025 		    ret, uselock, OP_DSA);
       
  2026 		sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
       
  2027 		sp->opdata_dsa_pub = NULL;
       
  2028 		if (sp->opdata_dsa_pub_num != NULL)
       
  2029 			{
       
  2030 			BN_free(sp->opdata_dsa_pub_num);
       
  2031 			sp->opdata_dsa_pub_num = NULL;
       
  2032 			}
       
  2033 		}
       
  2034 
       
  2035 	return (ret);
       
  2036 	}
       
  2037 
       
  2038 /* Destroy DSA private key from single session. */
       
  2039 int
       
  2040 pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
       
  2041 	{
       
  2042 	int ret = 0;
       
  2043 
       
  2044 	if (sp->opdata_dsa_priv_key != CK_INVALID_HANDLE)
       
  2045 		{
       
  2046 		TRY_OBJ_DESTROY(sp, sp->opdata_dsa_priv_key,
       
  2047 		    ret, uselock, OP_DSA);
       
  2048 		sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
       
  2049 		sp->opdata_dsa_priv = NULL;
       
  2050 		if (sp->opdata_dsa_priv_num != NULL)
       
  2051 			{
       
  2052 			BN_free(sp->opdata_dsa_priv_num);
       
  2053 			sp->opdata_dsa_priv_num = NULL;
       
  2054 			}
       
  2055 		}
       
  2056 
       
  2057 	return (ret);
       
  2058 	}
       
  2059 
       
  2060 /*
       
  2061  * Destroy DSA key object wrapper. If session is NULL, try to destroy all
       
  2062  * objects in the free list.
       
  2063  */
       
  2064 int
       
  2065 pk11_destroy_dsa_key_objects(PK11_SESSION *session)
       
  2066 	{
       
  2067 	int ret = 1;
       
  2068 	PK11_SESSION *sp = NULL;
       
  2069 	PK11_SESSION *local_free_session;
       
  2070 	CK_BBOOL uselock = CK_TRUE;
       
  2071 
       
  2072 	if (session != NULL)
       
  2073 		local_free_session = session;
       
  2074 	else
       
  2075 		{
       
  2076 		(void) pthread_mutex_lock(session_cache[OP_DSA].lock);
       
  2077 		local_free_session = session_cache[OP_DSA].head;
       
  2078 		uselock = CK_FALSE;
       
  2079 		}
       
  2080 
       
  2081 	/*
       
  2082 	 * go through the list of sessions and delete key objects
       
  2083 	 */
       
  2084 	while ((sp = local_free_session) != NULL)
       
  2085 		{
       
  2086 		local_free_session = sp->next;
       
  2087 
       
  2088 		/*
       
  2089 		 * Do not terminate list traversal if one of the
       
  2090 		 * destroy operations fails.
       
  2091 		 */
       
  2092 		if (pk11_destroy_dsa_object_pub(sp, uselock) == 0)
       
  2093 			{
       
  2094 			ret = 0;
       
  2095 			continue;
       
  2096 			}
       
  2097 		if (pk11_destroy_dsa_object_priv(sp, uselock) == 0)
       
  2098 			{
       
  2099 			ret = 0;
       
  2100 			continue;
       
  2101 			}
       
  2102 		}
       
  2103 
       
  2104 	if (session == NULL)
       
  2105 		(void) pthread_mutex_unlock(session_cache[OP_DSA].lock);
       
  2106 
       
  2107 	return (ret);
       
  2108 	}
       
  2109 #endif	/* OPENSSL_NO_DSA */
       
  2110 
       
  2111 #ifndef OPENSSL_NO_DH
       
  2112 /* Destroy DH key from single session. */
       
  2113 int
       
  2114 pk11_destroy_dh_object(PK11_SESSION *sp, CK_BBOOL uselock)
       
  2115 	{
       
  2116 	int ret = 0;
       
  2117 
       
  2118 	if (sp->opdata_dh_key != CK_INVALID_HANDLE)
       
  2119 		{
       
  2120 		TRY_OBJ_DESTROY(sp, sp->opdata_dh_key,
       
  2121 		    ret, uselock, OP_DH);
       
  2122 		sp->opdata_dh_key = CK_INVALID_HANDLE;
       
  2123 		sp->opdata_dh = NULL;
       
  2124 		if (sp->opdata_dh_priv_num != NULL)
       
  2125 			{
       
  2126 			BN_free(sp->opdata_dh_priv_num);
       
  2127 			sp->opdata_dh_priv_num = NULL;
       
  2128 			}
       
  2129 		}
       
  2130 
       
  2131 	return (ret);
       
  2132 	}
       
  2133 
       
  2134 /*
       
  2135  * Destroy DH key object wrapper.
       
  2136  *
       
  2137  * arg0: pointer to PKCS#11 engine session structure
       
  2138  *       if session is NULL, try to destroy all objects in the free list
       
  2139  */
       
  2140 int
       
  2141 pk11_destroy_dh_key_objects(PK11_SESSION *session)
       
  2142 	{
       
  2143 	int ret = 1;
       
  2144 	PK11_SESSION *sp = NULL;
       
  2145 	PK11_SESSION *local_free_session;
       
  2146 	CK_BBOOL uselock = CK_TRUE;
       
  2147 
       
  2148 	if (session != NULL)
       
  2149 		local_free_session = session;
       
  2150 	else
       
  2151 		{
       
  2152 		(void) pthread_mutex_lock(session_cache[OP_DH].lock);
       
  2153 		local_free_session = session_cache[OP_DH].head;
       
  2154 		uselock = CK_FALSE;
       
  2155 		}
       
  2156 
       
  2157 	while ((sp = local_free_session) != NULL)
       
  2158 		{
       
  2159 		local_free_session = sp->next;
       
  2160 
       
  2161 		/*
       
  2162 		 * Do not terminate list traversal if one of the
       
  2163 		 * destroy operations fails.
       
  2164 		 */
       
  2165 		if (pk11_destroy_dh_object(sp, uselock) == 0)
       
  2166 			{
       
  2167 			ret = 0;
       
  2168 			continue;
       
  2169 			}
       
  2170 		}
       
  2171 err:
       
  2172 	if (session == NULL)
       
  2173 		(void) pthread_mutex_unlock(session_cache[OP_DH].lock);
       
  2174 
       
  2175 	return (ret);
       
  2176 	}
       
  2177 #endif	/* OPENSSL_NO_DH */
       
  2178 
       
  2179 static int
       
  2180 pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh,
       
  2181     CK_BBOOL persistent)
       
  2182 	{
       
  2183 	CK_RV rv;
       
  2184 
       
  2185 	/*
       
  2186 	 * We never try to destroy persistent objects which are the objects
       
  2187 	 * stored in the keystore. Also, we always use read-only sessions so
       
  2188 	 * C_DestroyObject() would be returning CKR_SESSION_READ_ONLY here.
       
  2189 	 */
       
  2190 	if (persistent == CK_TRUE)
       
  2191 		return (1);
       
  2192 
       
  2193 	rv = pFuncList->C_DestroyObject(session, oh);
       
  2194 	if (rv != CKR_OK)
       
  2195 		{
       
  2196 		PK11err_add_data(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT,
       
  2197 		    rv);
       
  2198 		return (0);
       
  2199 		}
       
  2200 
       
  2201 	return (1);
       
  2202 	}
       
  2203 
       
  2204 
       
  2205 /* Symmetric ciphers and digests support functions */
       
  2206 
       
  2207 static int
       
  2208 cipher_nid_to_pk11(int nid)
       
  2209 	{
       
  2210 	int i;
       
  2211 
       
  2212 	for (i = 0; i < PK11_CIPHER_MAX; i++)
       
  2213 		if (ciphers[i].nid == nid)
       
  2214 			return (ciphers[i].id);
       
  2215 	return (-1);
       
  2216 	}
       
  2217 
       
  2218 static int
       
  2219 pk11_usable_ciphers(const int **nids)
       
  2220 	{
       
  2221 	if (cipher_count > 0)
       
  2222 		*nids = cipher_nids;
       
  2223 	else
       
  2224 		*nids = NULL;
       
  2225 	return (cipher_count);
       
  2226 	}
       
  2227 
       
  2228 static int
       
  2229 pk11_usable_digests(const int **nids)
       
  2230 	{
       
  2231 	if (digest_count > 0)
       
  2232 		*nids = digest_nids;
       
  2233 	else
       
  2234 		*nids = NULL;
       
  2235 	return (digest_count);
       
  2236 	}
       
  2237 
       
  2238 /*
       
  2239  * Init context for encryption or decryption using a symmetric key.
       
  2240  */
       
  2241 static int pk11_init_symmetric(EVP_CIPHER_CTX *ctx, PK11_CIPHER *pcipher,
       
  2242 	PK11_SESSION *sp, CK_MECHANISM_PTR pmech)
       
  2243 	{
       
  2244 	CK_RV rv;
       
  2245 	CK_AES_CTR_PARAMS ctr_params;
       
  2246 
       
  2247 	/*
       
  2248 	 * We expect pmech->mechanism to be already set and
       
  2249 	 * pParameter/ulParameterLen initialized to NULL/0 before
       
  2250 	 * pk11_init_symmetric() is called.
       
  2251 	 */
       
  2252 	OPENSSL_assert(pmech->mechanism != NULL);
       
  2253 	OPENSSL_assert(pmech->pParameter == NULL);
       
  2254 	OPENSSL_assert(pmech->ulParameterLen == 0);
       
  2255 
       
  2256 	if (ctx->cipher->nid == NID_aes_128_ctr ||
       
  2257 	    ctx->cipher->nid == NID_aes_192_ctr ||
       
  2258 	    ctx->cipher->nid == NID_aes_256_ctr)
       
  2259 		{
       
  2260 		pmech->pParameter = (void *)(&ctr_params);
       
  2261 		pmech->ulParameterLen = sizeof (ctr_params);
       
  2262 		/*
       
  2263 		 * For now, we are limited to the fixed length of the counter,
       
  2264 		 * it covers the whole counter block. That's what RFC 4344
       
  2265 		 * needs. For more information on internal structure of the
       
  2266 		 * counter block, see RFC 3686. If needed in the future, we can
       
  2267 		 * add code so that the counter length can be set via
       
  2268 		 * ENGINE_ctrl() function.
       
  2269 		 */
       
  2270 		ctr_params.ulCounterBits = AES_BLOCK_SIZE * 8;
       
  2271 		OPENSSL_assert(pcipher->iv_len == AES_BLOCK_SIZE);
       
  2272 		(void) memcpy(ctr_params.cb, ctx->iv, AES_BLOCK_SIZE);
       
  2273 		}
       
  2274 	else
       
  2275 		{
       
  2276 		if (pcipher->iv_len > 0)
       
  2277 			{
       
  2278 			pmech->pParameter = (void *)ctx->iv;
       
  2279 			pmech->ulParameterLen = pcipher->iv_len;
       
  2280 			}
       
  2281 		}
       
  2282 
       
  2283 	/* if we get here, the encryption needs to be reinitialized */
       
  2284 	if (ctx->encrypt)
       
  2285 		rv = pFuncList->C_EncryptInit(sp->session, pmech,
       
  2286 			sp->opdata_cipher_key);
       
  2287 	else
       
  2288 		rv = pFuncList->C_DecryptInit(sp->session, pmech,
       
  2289 			sp->opdata_cipher_key);
       
  2290 
       
  2291 	if (rv != CKR_OK)
       
  2292 		{
       
  2293 		PK11err_add_data(PK11_F_CIPHER_INIT, ctx->encrypt ?
       
  2294 		    PK11_R_ENCRYPTINIT : PK11_R_DECRYPTINIT, rv);
       
  2295 		pk11_return_session(sp, OP_CIPHER);
       
  2296 		return (0);
       
  2297 		}
       
  2298 
       
  2299 	return (1);
       
  2300 	}
       
  2301 
       
  2302 /* ARGSUSED */
       
  2303 static int
       
  2304 pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
       
  2305     const unsigned char *iv, int enc)
       
  2306 	{
       
  2307 	CK_MECHANISM mech;
       
  2308 	int index;
       
  2309 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
       
  2310 	PK11_SESSION *sp;
       
  2311 	PK11_CIPHER *p_ciph_table_row;
       
  2312 
       
  2313 	state->sp = NULL;
       
  2314 
       
  2315 	index = cipher_nid_to_pk11(ctx->cipher->nid);
       
  2316 	if (index < 0 || index >= PK11_CIPHER_MAX)
       
  2317 		return (0);
       
  2318 
       
  2319 	p_ciph_table_row = &ciphers[index];
       
  2320 	/*
       
  2321 	 * iv_len in the ctx->cipher structure is the maximum IV length for the
       
  2322 	 * current cipher and it must be less or equal to the IV length in our
       
  2323 	 * ciphers table. The key length must be in the allowed interval. From
       
  2324 	 * all cipher modes that the PKCS#11 engine supports only RC4 allows a
       
  2325 	 * key length to be in some range, all other NIDs have a precise key
       
  2326 	 * length. Every application can define its own EVP functions so this
       
  2327 	 * code serves as a sanity check.
       
  2328 	 *
       
  2329 	 * Note that the reason why the IV length in ctx->cipher might be
       
  2330 	 * greater than the actual length is that OpenSSL uses BLOCK_CIPHER_defs
       
  2331 	 * macro to define functions that return EVP structures for all DES
       
  2332 	 * modes. So, even ECB modes get 8 byte IV.
       
  2333 	 */
       
  2334 	if (ctx->cipher->iv_len < p_ciph_table_row->iv_len ||
       
  2335 	    ctx->key_len < p_ciph_table_row->min_key_len ||
       
  2336 	    ctx->key_len > p_ciph_table_row->max_key_len)
       
  2337 		{
       
  2338 		PK11err(PK11_F_CIPHER_INIT, PK11_R_KEY_OR_IV_LEN_PROBLEM);
       
  2339 		return (0);
       
  2340 		}
       
  2341 
       
  2342 	if ((sp = pk11_get_session(OP_CIPHER)) == NULL)
       
  2343 		return (0);
       
  2344 
       
  2345 	/* if applicable, the mechanism parameter is used for IV */
       
  2346 	mech.mechanism = p_ciph_table_row->mech_type;
       
  2347 	mech.pParameter = NULL;
       
  2348 	mech.ulParameterLen = 0;
       
  2349 
       
  2350 	/* The key object is destroyed here if it is not the current key. */
       
  2351 	(void) check_new_cipher_key(sp, key, ctx->key_len);
       
  2352 
       
  2353 	/*
       
  2354 	 * If the key is the same and the encryption is also the same, then
       
  2355 	 * just reuse it. However, we must not forget to reinitialize the
       
  2356 	 * context that was finalized in pk11_cipher_cleanup().
       
  2357 	 */
       
  2358 	if (sp->opdata_cipher_key != CK_INVALID_HANDLE &&
       
  2359 	    sp->opdata_encrypt == ctx->encrypt)
       
  2360 		{
       
  2361 		state->sp = sp;
       
  2362 		if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
       
  2363 			return (0);
       
  2364 
       
  2365 		return (1);
       
  2366 		}
       
  2367 
       
  2368 	/*
       
  2369 	 * Check if the key has been invalidated. If so, a new key object
       
  2370 	 * needs to be created.
       
  2371 	 */
       
  2372 	if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
       
  2373 		{
       
  2374 		sp->opdata_cipher_key = pk11_get_cipher_key(
       
  2375 			ctx, key, p_ciph_table_row->key_type, sp);
       
  2376 		}
       
  2377 
       
  2378 	if (sp->opdata_encrypt != ctx->encrypt && sp->opdata_encrypt != -1)
       
  2379 		{
       
  2380 		/*
       
  2381 		 * The previous encryption/decryption is different. Need to
       
  2382 		 * terminate the previous * active encryption/decryption here.
       
  2383 		 */
       
  2384 		if (!pk11_cipher_final(sp))
       
  2385 			{
       
  2386 			pk11_return_session(sp, OP_CIPHER);
       
  2387 			return (0);
       
  2388 			}
       
  2389 		}
       
  2390 
       
  2391 	if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
       
  2392 		{
       
  2393 		pk11_return_session(sp, OP_CIPHER);
       
  2394 		return (0);
       
  2395 		}
       
  2396 
       
  2397 	/* now initialize the context with a new key */
       
  2398 	if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
       
  2399 		return (0);
       
  2400 
       
  2401 	sp->opdata_encrypt = ctx->encrypt;
       
  2402 	state->sp = sp;
       
  2403 
       
  2404 	return (1);
       
  2405 	}
       
  2406 
       
  2407 /*
       
  2408  * When reusing the same key in an encryption/decryption session for a
       
  2409  * decryption/encryption session, we need to close the active session
       
  2410  * and recreate a new one. Note that the key is in the global session so
       
  2411  * that it needs not be recreated.
       
  2412  *
       
  2413  * It is more appropriate to use C_En/DecryptFinish here. At the time of this
       
  2414  * development, these two functions in the PKCS#11 libraries used return
       
  2415  * unexpected errors when passing in 0 length output. It may be a good
       
  2416  * idea to try them again if performance is a problem here and fix
       
  2417  * C_En/DecryptFinial if there are bugs there causing the problem.
       
  2418  */
       
  2419 static int
       
  2420 pk11_cipher_final(PK11_SESSION *sp)
       
  2421 	{
       
  2422 	CK_RV rv;
       
  2423 
       
  2424 	rv = pFuncList->C_CloseSession(sp->session);
       
  2425 	if (rv != CKR_OK)
       
  2426 		{
       
  2427 		PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_CLOSESESSION, rv);
       
  2428 		return (0);
       
  2429 		}
       
  2430 
       
  2431 	rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
       
  2432 		NULL_PTR, NULL_PTR, &sp->session);
       
  2433 	if (rv != CKR_OK)
       
  2434 		{
       
  2435 		PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_OPENSESSION, rv);
       
  2436 		return (0);
       
  2437 		}
       
  2438 
       
  2439 	return (1);
       
  2440 	}
       
  2441 
       
  2442 /*
       
  2443  * An engine interface function. The calling function allocates sufficient
       
  2444  * memory for the output buffer "out" to hold the results.
       
  2445  */
       
  2446 static int
       
  2447 pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
       
  2448 	const unsigned char *in, unsigned int inl)
       
  2449 	{
       
  2450 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
       
  2451 	PK11_SESSION *sp;
       
  2452 	CK_RV rv;
       
  2453 	unsigned long outl = inl;
       
  2454 
       
  2455 	if (state == NULL || state->sp == NULL)
       
  2456 		return (0);
       
  2457 
       
  2458 	sp = (PK11_SESSION *) state->sp;
       
  2459 
       
  2460 	if (!inl)
       
  2461 		return (1);
       
  2462 
       
  2463 	/* RC4 is the only stream cipher we support */
       
  2464 	if (ctx->cipher->nid != NID_rc4 && (inl % ctx->cipher->block_size) != 0)
       
  2465 		return (0);
       
  2466 
       
  2467 	if (ctx->encrypt)
       
  2468 		{
       
  2469 		rv = pFuncList->C_EncryptUpdate(sp->session,
       
  2470 			(unsigned char *)in, inl, out, &outl);
       
  2471 
       
  2472 		if (rv != CKR_OK)
       
  2473 			{
       
  2474 			PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
       
  2475 			    PK11_R_ENCRYPTUPDATE, rv);
       
  2476 			return (0);
       
  2477 			}
       
  2478 		}
       
  2479 	else
       
  2480 		{
       
  2481 		rv = pFuncList->C_DecryptUpdate(sp->session,
       
  2482 			(unsigned char *)in, inl, out, &outl);
       
  2483 
       
  2484 		if (rv != CKR_OK)
       
  2485 			{
       
  2486 			PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
       
  2487 			    PK11_R_DECRYPTUPDATE, rv);
       
  2488 			return (0);
       
  2489 			}
       
  2490 		}
       
  2491 
       
  2492 	/*
       
  2493 	 * For DES_CBC, DES3_CBC, AES_CBC, and RC4, the output size is always
       
  2494 	 * the same size of input.
       
  2495 	 * The application has guaranteed to call the block ciphers with
       
  2496 	 * correctly aligned buffers.
       
  2497 	 */
       
  2498 	if (inl != outl)
       
  2499 		return (0);
       
  2500 
       
  2501 	return (1);
       
  2502 	}
       
  2503 
       
  2504 /*
       
  2505  * Return the session to the pool. Calling C_EncryptFinal() and C_DecryptFinal()
       
  2506  * here is the right thing because in EVP_DecryptFinal_ex(), engine's
       
  2507  * do_cipher() is not even called, and in EVP_EncryptFinal_ex() it is called but
       
  2508  * the engine can't find out that it's the finalizing call. We wouldn't
       
  2509  * necessarily have to finalize the context here since reinitializing it with
       
  2510  * C_(Encrypt|Decrypt)Init() should be fine but for the sake of correctness,
       
  2511  * let's do it. Some implementations might leak memory if the previously used
       
  2512  * context is initialized without finalizing it first.
       
  2513  */
       
  2514 static int
       
  2515 pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx)
       
  2516 	{
       
  2517 	CK_RV rv;
       
  2518 	CK_ULONG len = EVP_MAX_BLOCK_LENGTH;
       
  2519 	CK_BYTE buf[EVP_MAX_BLOCK_LENGTH];
       
  2520 	PK11_CIPHER_STATE *state = ctx->cipher_data;
       
  2521 
       
  2522 	if (state != NULL && state->sp != NULL)
       
  2523 		{
       
  2524 		/*
       
  2525 		 * We are not interested in the data here, we just need to get
       
  2526 		 * rid of the context.
       
  2527 		 */
       
  2528 		if (ctx->encrypt)
       
  2529 			rv = pFuncList->C_EncryptFinal(
       
  2530 			    state->sp->session, buf, &len);
       
  2531 		else
       
  2532 			rv = pFuncList->C_DecryptFinal(
       
  2533 			    state->sp->session, buf, &len);
       
  2534 
       
  2535 		if (rv != CKR_OK)
       
  2536 			{
       
  2537 			PK11err_add_data(PK11_F_CIPHER_CLEANUP, ctx->encrypt ?
       
  2538 			    PK11_R_ENCRYPTFINAL : PK11_R_DECRYPTFINAL, rv);
       
  2539 			pk11_return_session(state->sp, OP_CIPHER);
       
  2540 			return (0);
       
  2541 			}
       
  2542 
       
  2543 		pk11_return_session(state->sp, OP_CIPHER);
       
  2544 		state->sp = NULL;
       
  2545 		}
       
  2546 
       
  2547 	return (1);
       
  2548 	}
       
  2549 
       
  2550 /*
       
  2551  * Registered by the ENGINE when used to find out how to deal with
       
  2552  * a particular NID in the ENGINE. This says what we'll do at the
       
  2553  * top level - note, that list is restricted by what we answer with
       
  2554  */
       
  2555 /* ARGSUSED */
       
  2556 static int
       
  2557 pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
       
  2558 	const int **nids, int nid)
       
  2559 	{
       
  2560 	if (!cipher)
       
  2561 		return (pk11_usable_ciphers(nids));
       
  2562 
       
  2563 	switch (nid)
       
  2564 		{
       
  2565 		case NID_des_ede3_cbc:
       
  2566 			*cipher = &pk11_3des_cbc;
       
  2567 			break;
       
  2568 		case NID_des_cbc:
       
  2569 			*cipher = &pk11_des_cbc;
       
  2570 			break;
       
  2571 		case NID_des_ede3_ecb:
       
  2572 			*cipher = &pk11_3des_ecb;
       
  2573 			break;
       
  2574 		case NID_des_ecb:
       
  2575 			*cipher = &pk11_des_ecb;
       
  2576 			break;
       
  2577 		case NID_aes_128_cbc:
       
  2578 			*cipher = &pk11_aes_128_cbc;
       
  2579 			break;
       
  2580 		case NID_aes_192_cbc:
       
  2581 			*cipher = &pk11_aes_192_cbc;
       
  2582 			break;
       
  2583 		case NID_aes_256_cbc:
       
  2584 			*cipher = &pk11_aes_256_cbc;
       
  2585 			break;
       
  2586 		case NID_aes_128_ecb:
       
  2587 			*cipher = &pk11_aes_128_ecb;
       
  2588 			break;
       
  2589 		case NID_aes_192_ecb:
       
  2590 			*cipher = &pk11_aes_192_ecb;
       
  2591 			break;
       
  2592 		case NID_aes_256_ecb:
       
  2593 			*cipher = &pk11_aes_256_ecb;
       
  2594 			break;
       
  2595 		case NID_aes_128_ctr:
       
  2596 			*cipher = &pk11_aes_128_ctr;
       
  2597 			break;
       
  2598 		case NID_aes_192_ctr:
       
  2599 			*cipher = &pk11_aes_192_ctr;
       
  2600 			break;
       
  2601 		case NID_aes_256_ctr:
       
  2602 			*cipher = &pk11_aes_256_ctr;
       
  2603 			break;
       
  2604 		case NID_bf_cbc:
       
  2605 			*cipher = &pk11_bf_cbc;
       
  2606 			break;
       
  2607 		case NID_rc4:
       
  2608 			*cipher = &pk11_rc4;
       
  2609 			break;
       
  2610 		default:
       
  2611 			*cipher = NULL;
       
  2612 			break;
       
  2613 		}
       
  2614 	return (*cipher != NULL);
       
  2615 	}
       
  2616 
       
  2617 /* ARGSUSED */
       
  2618 static int
       
  2619 pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
       
  2620 	const int **nids, int nid)
       
  2621 	{
       
  2622 	if (!digest)
       
  2623 		return (pk11_usable_digests(nids));
       
  2624 
       
  2625 	switch (nid)
       
  2626 		{
       
  2627 		case NID_md5:
       
  2628 			*digest = &pk11_md5;
       
  2629 			break;
       
  2630 		case NID_sha1:
       
  2631 			*digest = &pk11_sha1;
       
  2632 			break;
       
  2633 		case NID_sha224:
       
  2634 			*digest = &pk11_sha224;
       
  2635 			break;
       
  2636 		case NID_sha256:
       
  2637 			*digest = &pk11_sha256;
       
  2638 			break;
       
  2639 		case NID_sha384:
       
  2640 			*digest = &pk11_sha384;
       
  2641 			break;
       
  2642 		case NID_sha512:
       
  2643 			*digest = &pk11_sha512;
       
  2644 			break;
       
  2645 		default:
       
  2646 			*digest = NULL;
       
  2647 			break;
       
  2648 		}
       
  2649 	return (*digest != NULL);
       
  2650 	}
       
  2651 
       
  2652 
       
  2653 /* Create a secret key object in a PKCS#11 session */
       
  2654 static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
       
  2655 	const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp)
       
  2656 	{
       
  2657 	CK_RV rv;
       
  2658 	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
       
  2659 	CK_OBJECT_CLASS obj_key = CKO_SECRET_KEY;
       
  2660 	CK_ULONG ul_key_attr_count = 6;
       
  2661 
       
  2662 	CK_ATTRIBUTE  a_key_template[] =
       
  2663 		{
       
  2664 		{CKA_CLASS, (void*) NULL, sizeof (CK_OBJECT_CLASS)},
       
  2665 		{CKA_KEY_TYPE, (void*) NULL, sizeof (CK_KEY_TYPE)},
       
  2666 		{CKA_TOKEN, &pk11_false, sizeof (pk11_false)},
       
  2667 		{CKA_ENCRYPT, &pk11_true, sizeof (pk11_true)},
       
  2668 		{CKA_DECRYPT, &pk11_true, sizeof (pk11_true)},
       
  2669 		{CKA_VALUE, (void*) NULL, 0},
       
  2670 		};
       
  2671 
       
  2672 	/*
       
  2673 	 * Create secret key object in global_session. All other sessions
       
  2674 	 * can use the key handles. Here is why:
       
  2675 	 * OpenSSL will call EncryptInit and EncryptUpdate using a secret key.
       
  2676 	 * It may then call DecryptInit and DecryptUpdate using the same key.
       
  2677 	 * To use the same key object, we need to call EncryptFinal with
       
  2678 	 * a 0 length message. Currently, this does not work for 3DES
       
  2679 	 * mechanism. To get around this problem, we close the session and
       
  2680 	 * then create a new session to use the same key object. When a session
       
  2681 	 * is closed, all the object handles will be invalid. Thus, create key
       
  2682 	 * objects in a global session, an individual session may be closed to
       
  2683 	 * terminate the active operation.
       
  2684 	 */
       
  2685 	CK_SESSION_HANDLE session = global_session;
       
  2686 	a_key_template[0].pValue = &obj_key;
       
  2687 	a_key_template[1].pValue = &key_type;
       
  2688 	a_key_template[5].pValue = (void *) key;
       
  2689 	a_key_template[5].ulValueLen = (unsigned long) ctx->key_len;
       
  2690 
       
  2691 	rv = pFuncList->C_CreateObject(session,
       
  2692 		a_key_template, ul_key_attr_count, &h_key);
       
  2693 	if (rv != CKR_OK)
       
  2694 		{
       
  2695 		PK11err_add_data(PK11_F_GET_CIPHER_KEY, PK11_R_CREATEOBJECT,
       
  2696 		    rv);
       
  2697 		goto err;
       
  2698 		}
       
  2699 
       
  2700 	/*
       
  2701 	 * Save the key information used in this session.
       
  2702 	 * The max can be saved is PK11_KEY_LEN_MAX.
       
  2703 	 */
       
  2704 	sp->opdata_key_len = ctx->key_len > PK11_KEY_LEN_MAX ?
       
  2705 		PK11_KEY_LEN_MAX : ctx->key_len;
       
  2706 	(void) memcpy(sp->opdata_key, key, sp->opdata_key_len);
       
  2707 err:
       
  2708 
       
  2709 	return (h_key);
       
  2710 	}
       
  2711 
       
  2712 static int
       
  2713 md_nid_to_pk11(int nid)
       
  2714 	{
       
  2715 	int i;
       
  2716 
       
  2717 	for (i = 0; i < PK11_DIGEST_MAX; i++)
       
  2718 		if (digests[i].nid == nid)
       
  2719 			return (digests[i].id);
       
  2720 	return (-1);
       
  2721 	}
       
  2722 
       
  2723 static int
       
  2724 pk11_digest_init(EVP_MD_CTX *ctx)
       
  2725 	{
       
  2726 	CK_RV rv;
       
  2727 	CK_MECHANISM mech;
       
  2728 	int index;
       
  2729 	PK11_SESSION *sp;
       
  2730 	PK11_DIGEST *pdp;
       
  2731 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
       
  2732 
       
  2733 	state->sp = NULL;
       
  2734 
       
  2735 	index = md_nid_to_pk11(ctx->digest->type);
       
  2736 	if (index < 0 || index >= PK11_DIGEST_MAX)
       
  2737 		return (0);
       
  2738 
       
  2739 	pdp = &digests[index];
       
  2740 	if ((sp = pk11_get_session(OP_DIGEST)) == NULL)
       
  2741 		return (0);
       
  2742 
       
  2743 	/* at present, no parameter is needed for supported digests */
       
  2744 	mech.mechanism = pdp->mech_type;
       
  2745 	mech.pParameter = NULL;
       
  2746 	mech.ulParameterLen = 0;
       
  2747 
       
  2748 	rv = pFuncList->C_DigestInit(sp->session, &mech);
       
  2749 
       
  2750 	if (rv != CKR_OK)
       
  2751 		{
       
  2752 		PK11err_add_data(PK11_F_DIGEST_INIT, PK11_R_DIGESTINIT, rv);
       
  2753 		pk11_return_session(sp, OP_DIGEST);
       
  2754 		return (0);
       
  2755 		}
       
  2756 
       
  2757 	state->sp = sp;
       
  2758 
       
  2759 	return (1);
       
  2760 	}
       
  2761 
       
  2762 static int
       
  2763 pk11_digest_update(EVP_MD_CTX *ctx, const void *data, size_t count)
       
  2764 	{
       
  2765 	CK_RV rv;
       
  2766 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
       
  2767 
       
  2768 	/* 0 length message will cause a failure in C_DigestFinal */
       
  2769 	if (count == 0)
       
  2770 		return (1);
       
  2771 
       
  2772 	if (state == NULL || state->sp == NULL)
       
  2773 		return (0);
       
  2774 
       
  2775 	rv = pFuncList->C_DigestUpdate(state->sp->session, (CK_BYTE *) data,
       
  2776 		count);
       
  2777 
       
  2778 	if (rv != CKR_OK)
       
  2779 		{
       
  2780 		PK11err_add_data(PK11_F_DIGEST_UPDATE, PK11_R_DIGESTUPDATE, rv);
       
  2781 		pk11_return_session(state->sp, OP_DIGEST);
       
  2782 		state->sp = NULL;
       
  2783 		return (0);
       
  2784 		}
       
  2785 
       
  2786 	return (1);
       
  2787 	}
       
  2788 
       
  2789 static int
       
  2790 pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
       
  2791 	{
       
  2792 	CK_RV rv;
       
  2793 	unsigned long len;
       
  2794 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
       
  2795 	len = ctx->digest->md_size;
       
  2796 
       
  2797 	if (state == NULL || state->sp == NULL)
       
  2798 		return (0);
       
  2799 
       
  2800 	rv = pFuncList->C_DigestFinal(state->sp->session, md, &len);
       
  2801 
       
  2802 	if (rv != CKR_OK)
       
  2803 		{
       
  2804 		PK11err_add_data(PK11_F_DIGEST_FINAL, PK11_R_DIGESTFINAL, rv);
       
  2805 		pk11_return_session(state->sp, OP_DIGEST);
       
  2806 		state->sp = NULL;
       
  2807 		return (0);
       
  2808 		}
       
  2809 
       
  2810 	if (ctx->digest->md_size != len)
       
  2811 		return (0);
       
  2812 
       
  2813 	/*
       
  2814 	 * Final is called and digest is returned, so return the session
       
  2815 	 * to the pool
       
  2816 	 */
       
  2817 	pk11_return_session(state->sp, OP_DIGEST);
       
  2818 	state->sp = NULL;
       
  2819 
       
  2820 	return (1);
       
  2821 	}
       
  2822 
       
  2823 static int
       
  2824 pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
       
  2825 	{
       
  2826 	CK_RV rv;
       
  2827 	int ret = 0;
       
  2828 	PK11_CIPHER_STATE *state, *state_to;
       
  2829 	CK_BYTE_PTR pstate = NULL;
       
  2830 	CK_ULONG ul_state_len;
       
  2831 
       
  2832 	/* The copy-from state */
       
  2833 	state = (PK11_CIPHER_STATE *) from->md_data;
       
  2834 	if (state == NULL || state->sp == NULL)
       
  2835 		goto err;
       
  2836 
       
  2837 	/* Initialize the copy-to state */
       
  2838 	if (!pk11_digest_init(to))
       
  2839 		goto err;
       
  2840 	state_to = (PK11_CIPHER_STATE *) to->md_data;
       
  2841 
       
  2842 	/* Get the size of the operation state of the copy-from session */
       
  2843 	rv = pFuncList->C_GetOperationState(state->sp->session, NULL,
       
  2844 		&ul_state_len);
       
  2845 
       
  2846 	if (rv != CKR_OK)
       
  2847 		{
       
  2848 		PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
       
  2849 		    rv);
       
  2850 		goto err;
       
  2851 		}
       
  2852 	if (ul_state_len == 0)
       
  2853 		{
       
  2854 		goto err;
       
  2855 		}
       
  2856 
       
  2857 	pstate = OPENSSL_malloc(ul_state_len);
       
  2858 	if (pstate == NULL)
       
  2859 		{
       
  2860 		PK11err(PK11_F_DIGEST_COPY, PK11_R_MALLOC_FAILURE);
       
  2861 		goto err;
       
  2862 		}
       
  2863 
       
  2864 	/* Get the operation state of the copy-from session */
       
  2865 	rv = pFuncList->C_GetOperationState(state->sp->session, pstate,
       
  2866 		&ul_state_len);
       
  2867 
       
  2868 	if (rv != CKR_OK)
       
  2869 		{
       
  2870 		PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
       
  2871 		    rv);
       
  2872 		goto err;
       
  2873 		}
       
  2874 
       
  2875 	/* Set the operation state of the copy-to session */
       
  2876 	rv = pFuncList->C_SetOperationState(state_to->sp->session, pstate,
       
  2877 		ul_state_len, 0, 0);
       
  2878 
       
  2879 	if (rv != CKR_OK)
       
  2880 		{
       
  2881 		PK11err_add_data(PK11_F_DIGEST_COPY,
       
  2882 		    PK11_R_SET_OPERATION_STATE, rv);
       
  2883 		goto err;
       
  2884 		}
       
  2885 
       
  2886 	ret = 1;
       
  2887 err:
       
  2888 	if (pstate != NULL)
       
  2889 		OPENSSL_free(pstate);
       
  2890 
       
  2891 	return (ret);
       
  2892 	}
       
  2893 
       
  2894 /* Return any pending session state to the pool */
       
  2895 static int
       
  2896 pk11_digest_cleanup(EVP_MD_CTX *ctx)
       
  2897 	{
       
  2898 	PK11_CIPHER_STATE *state = ctx->md_data;
       
  2899 	unsigned char buf[EVP_MAX_MD_SIZE];
       
  2900 
       
  2901 	if (state != NULL && state->sp != NULL)
       
  2902 		{
       
  2903 		/*
       
  2904 		 * If state->sp is not NULL then pk11_digest_final() has not
       
  2905 		 * been called yet. We must call it now to free any memory
       
  2906 		 * that might have been allocated in the token when
       
  2907 		 * pk11_digest_init() was called. pk11_digest_final()
       
  2908 		 * will return the session to the cache.
       
  2909 		 */
       
  2910 		if (!pk11_digest_final(ctx, buf))
       
  2911 			return (0);
       
  2912 		}
       
  2913 
       
  2914 	return (1);
       
  2915 	}
       
  2916 
       
  2917 /*
       
  2918  * Check if the new key is the same as the key object in the session. If the key
       
  2919  * is the same, no need to create a new key object. Otherwise, the old key
       
  2920  * object needs to be destroyed and a new one will be created. Return 1 for
       
  2921  * cache hit, 0 for cache miss. Note that we must check the key length first
       
  2922  * otherwise we could end up reusing a different, longer key with the same
       
  2923  * prefix.
       
  2924  */
       
  2925 static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
       
  2926 	int key_len)
       
  2927 	{
       
  2928 	if (sp->opdata_key_len != key_len ||
       
  2929 	    memcmp(sp->opdata_key, key, key_len) != 0)
       
  2930 		{
       
  2931 		(void) pk11_destroy_cipher_key_objects(sp);
       
  2932 		return (0);
       
  2933 		}
       
  2934 	return (1);
       
  2935 	}
       
  2936 
       
  2937 /* Destroy one or more secret key objects. */
       
  2938 static int pk11_destroy_cipher_key_objects(PK11_SESSION *session)
       
  2939 	{
       
  2940 	int ret = 0;
       
  2941 	PK11_SESSION *sp = NULL;
       
  2942 	PK11_SESSION *local_free_session;
       
  2943 
       
  2944 	if (session != NULL)
       
  2945 		local_free_session = session;
       
  2946 	else
       
  2947 		{
       
  2948 		(void) pthread_mutex_lock(session_cache[OP_CIPHER].lock);
       
  2949 		local_free_session = session_cache[OP_CIPHER].head;
       
  2950 		}
       
  2951 
       
  2952 	while ((sp = local_free_session) != NULL)
       
  2953 		{
       
  2954 		local_free_session = sp->next;
       
  2955 
       
  2956 		if (sp->opdata_cipher_key != CK_INVALID_HANDLE)
       
  2957 			{
       
  2958 			/*
       
  2959 			 * The secret key object is created in the
       
  2960 			 * global_session. See pk11_get_cipher_key().
       
  2961 			 */
       
  2962 			if (pk11_destroy_object(global_session,
       
  2963 				sp->opdata_cipher_key, CK_FALSE) == 0)
       
  2964 				goto err;
       
  2965 			sp->opdata_cipher_key = CK_INVALID_HANDLE;
       
  2966 			}
       
  2967 		}
       
  2968 	ret = 1;
       
  2969 err:
       
  2970 
       
  2971 	if (session == NULL)
       
  2972 		(void) pthread_mutex_unlock(session_cache[OP_CIPHER].lock);
       
  2973 
       
  2974 	return (ret);
       
  2975 	}
       
  2976 
       
  2977 
       
  2978 /*
       
  2979  * Public key mechanisms optionally supported
       
  2980  *
       
  2981  * CKM_RSA_X_509
       
  2982  * CKM_RSA_PKCS
       
  2983  * CKM_DSA
       
  2984  *
       
  2985  * The first slot that supports at least one of those mechanisms is chosen as a
       
  2986  * public key slot.
       
  2987  *
       
  2988  * Symmetric ciphers optionally supported
       
  2989  *
       
  2990  * CKM_DES3_CBC
       
  2991  * CKM_DES_CBC
       
  2992  * CKM_AES_CBC
       
  2993  * CKM_DES3_ECB
       
  2994  * CKM_DES_ECB
       
  2995  * CKM_AES_ECB
       
  2996  * CKM_AES_CTR
       
  2997  * CKM_RC4
       
  2998  * CKM_BLOWFISH_CBC
       
  2999  *
       
  3000  * Digests optionally supported
       
  3001  *
       
  3002  * CKM_MD5
       
  3003  * CKM_SHA_1
       
  3004  * CKM_SHA224
       
  3005  * CKM_SHA256
       
  3006  * CKM_SHA384
       
  3007  * CKM_SHA512
       
  3008  *
       
  3009  * The output of this function is a set of global variables indicating which
       
  3010  * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
       
  3011  * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
       
  3012  * variables carry information about which slot was chosen for (a) public key
       
  3013  * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
       
  3014  */
       
  3015 static int
       
  3016 pk11_choose_slots(int *any_slot_found)
       
  3017 	{
       
  3018 	CK_SLOT_ID_PTR pSlotList = NULL_PTR;
       
  3019 	CK_ULONG ulSlotCount = 0;
       
  3020 	CK_MECHANISM_INFO mech_info;
       
  3021 	CK_TOKEN_INFO token_info;
       
  3022 	int i;
       
  3023 	CK_RV rv;
       
  3024 	CK_SLOT_ID best_pubkey_slot_sofar;
       
  3025 #ifdef DEBUG_SLOT_SELECTION
       
  3026 	CK_SLOT_ID best_cd_slot_sofar;
       
  3027 #endif
       
  3028 	int slot_n_cipher = -1;
       
  3029 	int slot_n_digest = -1;
       
  3030 	CK_SLOT_ID current_slot = 0;
       
  3031 	int current_slot_n_cipher = 0;
       
  3032 	int current_slot_n_digest = 0;
       
  3033 	int best_number_of_mechs = 0;
       
  3034 	int current_number_of_mechs = 0;
       
  3035 	int local_cipher_nids[PK11_CIPHER_MAX];
       
  3036 	int local_digest_nids[PK11_DIGEST_MAX];
       
  3037 
       
  3038 	/* let's initialize the output parameter */
       
  3039 	if (any_slot_found != NULL)
       
  3040 		*any_slot_found = 0;
       
  3041 
       
  3042 	/* Get slot list for memory allocation */
       
  3043 	rv = pFuncList->C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount);
       
  3044 
       
  3045 	if (rv != CKR_OK)
       
  3046 		{
       
  3047 		PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
       
  3048 		return (0);
       
  3049 		}
       
  3050 
       
  3051 	/* it's not an error if we didn't find any providers */
       
  3052 	if (ulSlotCount == 0)
       
  3053 		{
       
  3054 		DEBUG_SLOT_SEL("%s: no crypto providers found\n", PK11_DBG);
       
  3055 		return (1);
       
  3056 		}
       
  3057 
       
  3058 	pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
       
  3059 
       
  3060 	if (pSlotList == NULL)
       
  3061 		{
       
  3062 		PK11err(PK11_F_CHOOSE_SLOT, PK11_R_MALLOC_FAILURE);
       
  3063 		return (0);
       
  3064 		}
       
  3065 
       
  3066 	/* Get the slot list for processing */
       
  3067 	rv = pFuncList->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount);
       
  3068 	if (rv != CKR_OK)
       
  3069 		{
       
  3070 		PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
       
  3071 		OPENSSL_free(pSlotList);
       
  3072 		return (0);
       
  3073 		}
       
  3074 
       
  3075 	DEBUG_SLOT_SEL("%s: provider: %s\n", PK11_DBG, def_PK11_LIBNAME);
       
  3076 	DEBUG_SLOT_SEL("%s: number of slots: %d\n", PK11_DBG, ulSlotCount);
       
  3077 
       
  3078 	pubkey_SLOTID = pSlotList[0];
       
  3079 	for (i = 0; i < ulSlotCount; i++)
       
  3080 		{
       
  3081 		CK_BBOOL slot_has_rsa = CK_FALSE;
       
  3082 		CK_BBOOL slot_has_dsa = CK_FALSE;
       
  3083 		CK_BBOOL slot_has_dh = CK_FALSE;
       
  3084 		current_slot = pSlotList[i];
       
  3085 
       
  3086 		DEBUG_SLOT_SEL("%s: == checking slot: %d ==\n", PK11_DBG,
       
  3087 			current_slot);
       
  3088 		rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
       
  3089 		if (rv != CKR_OK)
       
  3090 			continue;
       
  3091 
       
  3092 		DEBUG_SLOT_SEL("%s: token label: %.32s\n", PK11_DBG,
       
  3093 		    token_info.label);
       
  3094 
       
  3095 		DEBUG_SLOT_SEL("%s: checking rand slots\n", PK11_DBG);
       
  3096 
       
  3097 		if (((token_info.flags & CKF_RNG) != 0) && !pk11_have_random)
       
  3098 			{
       
  3099 			DEBUG_SLOT_SEL(
       
  3100 			    "%s: this token has CKF_RNG flag\n", PK11_DBG);
       
  3101 			pk11_have_random = CK_TRUE;
       
  3102 			rand_SLOTID = current_slot;
       
  3103 			}
       
  3104 
       
  3105 		DEBUG_SLOT_SEL("%s: checking pubkey slots\n", PK11_DBG);
       
  3106 		current_number_of_mechs = 0;
       
  3107 
       
  3108 #ifndef OPENSSL_NO_RSA
       
  3109 		/*
       
  3110 		 * Check if this slot is capable of signing and
       
  3111 		 * verifying with CKM_RSA_PKCS.
       
  3112 		 */
       
  3113 		rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS,
       
  3114 			&mech_info);
       
  3115 
       
  3116 		if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
       
  3117 				(mech_info.flags & CKF_VERIFY)))
       
  3118 			{
       
  3119 			/*
       
  3120 			 * Check if this slot is capable of encryption,
       
  3121 			 * decryption, sign, and verify with CKM_RSA_X_509.
       
  3122 			 */
       
  3123 			rv = pFuncList->C_GetMechanismInfo(current_slot,
       
  3124 			    CKM_RSA_X_509, &mech_info);
       
  3125 
       
  3126 			if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
       
  3127 			    (mech_info.flags & CKF_VERIFY) &&
       
  3128 			    (mech_info.flags & CKF_ENCRYPT) &&
       
  3129 			    (mech_info.flags & CKF_VERIFY_RECOVER) &&
       
  3130 			    (mech_info.flags & CKF_DECRYPT)))
       
  3131 				{
       
  3132 				slot_has_rsa = CK_TRUE;
       
  3133 				current_number_of_mechs++;
       
  3134 				}
       
  3135 			}
       
  3136 #endif	/* OPENSSL_NO_RSA */
       
  3137 
       
  3138 #ifndef OPENSSL_NO_DSA
       
  3139 		/*
       
  3140 		 * Check if this slot is capable of signing and
       
  3141 		 * verifying with CKM_DSA.
       
  3142 		 */
       
  3143 		rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_DSA,
       
  3144 			&mech_info);
       
  3145 		if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
       
  3146 		    (mech_info.flags & CKF_VERIFY)))
       
  3147 			{
       
  3148 			slot_has_dsa = CK_TRUE;
       
  3149 			current_number_of_mechs++;
       
  3150 			}
       
  3151 
       
  3152 #endif	/* OPENSSL_NO_DSA */
       
  3153 
       
  3154 #ifndef OPENSSL_NO_DH
       
  3155 		/*
       
  3156 		 * Check if this slot is capable of DH key generataion and
       
  3157 		 * derivation.
       
  3158 		 */
       
  3159 		rv = pFuncList->C_GetMechanismInfo(current_slot,
       
  3160 		    CKM_DH_PKCS_KEY_PAIR_GEN, &mech_info);
       
  3161 
       
  3162 		if (rv == CKR_OK && (mech_info.flags & CKF_GENERATE_KEY_PAIR))
       
  3163 			{
       
  3164 			rv = pFuncList->C_GetMechanismInfo(current_slot,
       
  3165 				CKM_DH_PKCS_DERIVE, &mech_info);
       
  3166 			if (rv == CKR_OK && (mech_info.flags & CKF_DERIVE))
       
  3167 				{
       
  3168 				slot_has_dh = CK_TRUE;
       
  3169 				current_number_of_mechs++;
       
  3170 				}
       
  3171 			}
       
  3172 #endif	/* OPENSSL_NO_DH */
       
  3173 
       
  3174 		if (current_number_of_mechs > best_number_of_mechs)
       
  3175 			{
       
  3176 			best_pubkey_slot_sofar = current_slot;
       
  3177 			pk11_have_rsa = slot_has_rsa;
       
  3178 			pk11_have_dsa = slot_has_dsa;
       
  3179 			pk11_have_dh = slot_has_dh;
       
  3180 			best_number_of_mechs = current_number_of_mechs;
       
  3181 			/*
       
  3182 			 * Cache the flags for later use. We might need those if
       
  3183 			 * RSA keys by reference feature is used.
       
  3184 			 */
       
  3185 			pubkey_token_flags = token_info.flags;
       
  3186 			DEBUG_SLOT_SEL("%s: pubkey flags changed to "
       
  3187 			    "%lu.\n", PK11_DBG, pubkey_token_flags);
       
  3188 			}
       
  3189 
       
  3190 		DEBUG_SLOT_SEL("%s: checking cipher/digest\n", PK11_DBG);
       
  3191 
       
  3192 		current_slot_n_cipher = 0;
       
  3193 		current_slot_n_digest = 0;
       
  3194 		(void) memset(local_cipher_nids, 0, sizeof (local_cipher_nids));
       
  3195 		(void) memset(local_digest_nids, 0, sizeof (local_digest_nids));
       
  3196 
       
  3197 		pk11_find_symmetric_ciphers(pFuncList, current_slot,
       
  3198 		    &current_slot_n_cipher, local_cipher_nids);
       
  3199 
       
  3200 		pk11_find_digests(pFuncList, current_slot,
       
  3201 		    &current_slot_n_digest, local_digest_nids);
       
  3202 
       
  3203 		DEBUG_SLOT_SEL("%s: current_slot_n_cipher %d\n", PK11_DBG,
       
  3204 			current_slot_n_cipher);
       
  3205 		DEBUG_SLOT_SEL("%s: current_slot_n_digest %d\n", PK11_DBG,
       
  3206 			current_slot_n_digest);
       
  3207 
       
  3208 		/*
       
  3209 		 * If the current slot supports more ciphers/digests than
       
  3210 		 * the previous best one we change the current best to this one,
       
  3211 		 * otherwise leave it where it is.
       
  3212 		 */
       
  3213 		if ((current_slot_n_cipher + current_slot_n_digest) >
       
  3214 		    (slot_n_cipher + slot_n_digest))
       
  3215 			{
       
  3216 			DEBUG_SLOT_SEL("%s: changing best slot to %d\n",
       
  3217 				PK11_DBG, current_slot);
       
  3218 			SLOTID = current_slot;
       
  3219 #ifdef DEBUG_SLOT_SELECTION
       
  3220 			best_cd_slot_sofar = current_slot;
       
  3221 #endif
       
  3222 			cipher_count = slot_n_cipher = current_slot_n_cipher;
       
  3223 			digest_count = slot_n_digest = current_slot_n_digest;
       
  3224 			(void) memcpy(cipher_nids, local_cipher_nids,
       
  3225 			    sizeof (local_cipher_nids));
       
  3226 			(void) memcpy(digest_nids, local_digest_nids,
       
  3227 			    sizeof (local_digest_nids));
       
  3228 			}
       
  3229 
       
  3230 		DEBUG_SLOT_SEL("%s: best cipher/digest slot so far: %d\n",
       
  3231 			PK11_DBG, best_cd_slot_sofar);
       
  3232 		}
       
  3233 
       
  3234 	if (best_number_of_mechs == 0)
       
  3235 		{
       
  3236 		DEBUG_SLOT_SEL("%s: no rsa/dsa/dh\n", PK11_DBG);
       
  3237 		}
       
  3238 	else
       
  3239 		{
       
  3240 		pubkey_SLOTID = best_pubkey_slot_sofar;
       
  3241 		}
       
  3242 
       
  3243 	DEBUG_SLOT_SEL("%s: chosen pubkey slot: %d\n", PK11_DBG, pubkey_SLOTID);
       
  3244 	DEBUG_SLOT_SEL("%s: chosen rand slot: %d\n", PK11_DBG, rand_SLOTID);
       
  3245 	DEBUG_SLOT_SEL("%s: chosen cipher/digest slot: %d\n", PK11_DBG, SLOTID);
       
  3246 	DEBUG_SLOT_SEL("%s: pk11_have_rsa %d\n", PK11_DBG, pk11_have_rsa);
       
  3247 	DEBUG_SLOT_SEL("%s: pk11_have_dsa %d\n", PK11_DBG, pk11_have_dsa);
       
  3248 	DEBUG_SLOT_SEL("%s: pk11_have_dh %d\n", PK11_DBG, pk11_have_dh);
       
  3249 	DEBUG_SLOT_SEL("%s: pk11_have_random %d\n", PK11_DBG, pk11_have_random);
       
  3250 	DEBUG_SLOT_SEL("%s: cipher_count %d\n", PK11_DBG, cipher_count);
       
  3251 	DEBUG_SLOT_SEL("%s: digest_count %d\n", PK11_DBG, digest_count);
       
  3252 
       
  3253 	if (pSlotList != NULL)
       
  3254 		OPENSSL_free(pSlotList);
       
  3255 
       
  3256 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3257 	OPENSSL_free(hw_cnids);
       
  3258 	OPENSSL_free(hw_dnids);
       
  3259 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3260 
       
  3261 	if (any_slot_found != NULL)
       
  3262 		*any_slot_found = 1;
       
  3263 	return (1);
       
  3264 	}
       
  3265 
       
  3266 static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR pflist,
       
  3267     int slot_id, int *current_slot_n_cipher, int *local_cipher_nids,
       
  3268     PK11_CIPHER *cipher)
       
  3269 	{
       
  3270 	static CK_MECHANISM_INFO mech_info;
       
  3271 	static CK_RV rv;
       
  3272 	static CK_MECHANISM_TYPE last_checked_mech = (CK_MECHANISM_TYPE)-1;
       
  3273 
       
  3274 	DEBUG_SLOT_SEL("%s: checking mech: %x", PK11_DBG, cipher->mech_type);
       
  3275 	if (cipher->mech_type != last_checked_mech)
       
  3276 		{
       
  3277 		rv = pflist->C_GetMechanismInfo(slot_id, cipher->mech_type,
       
  3278 		    &mech_info);
       
  3279 		}
       
  3280 
       
  3281 	last_checked_mech = cipher->mech_type;
       
  3282 
       
  3283 	if (rv != CKR_OK)
       
  3284 		{
       
  3285 		DEBUG_SLOT_SEL(" not found\n");
       
  3286 		return;
       
  3287 		}
       
  3288 
       
  3289 	if ((mech_info.flags & CKF_ENCRYPT) &&
       
  3290 	    (mech_info.flags & CKF_DECRYPT))
       
  3291 		{
       
  3292 		if (mech_info.ulMinKeySize > cipher->min_key_len ||
       
  3293 		    mech_info.ulMaxKeySize < cipher->max_key_len)
       
  3294 			{
       
  3295 			DEBUG_SLOT_SEL(" engine key size range <%i-%i> does not"
       
  3296 			    " match mech range <%lu-%lu>\n",
       
  3297 			    cipher->min_key_len, cipher->max_key_len,
       
  3298 			    mech_info.ulMinKeySize, mech_info.ulMaxKeySize);
       
  3299 			return;
       
  3300 			}
       
  3301 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3302 		if (nid_in_table(cipher->nid, hw_cnids))
       
  3303 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3304 			{
       
  3305 			DEBUG_SLOT_SEL(" usable\n");
       
  3306 			local_cipher_nids[(*current_slot_n_cipher)++] =
       
  3307 			    cipher->nid;
       
  3308 			}
       
  3309 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3310 		else
       
  3311 			{
       
  3312 			DEBUG_SLOT_SEL(
       
  3313 			    " rejected, software implementation only\n");
       
  3314 			}
       
  3315 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3316 		}
       
  3317 	else
       
  3318 		{
       
  3319 		DEBUG_SLOT_SEL(" unusable\n");
       
  3320 		}
       
  3321 
       
  3322 	return;
       
  3323 	}
       
  3324 
       
  3325 static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist, int slot_id,
       
  3326     int *current_slot_n_digest, int *local_digest_nids, PK11_DIGEST *digest)
       
  3327 	{
       
  3328 	CK_MECHANISM_INFO mech_info;
       
  3329 	CK_RV rv;
       
  3330 
       
  3331 	DEBUG_SLOT_SEL("%s: checking mech: %x", PK11_DBG, digest->mech_type);
       
  3332 	rv = pflist->C_GetMechanismInfo(slot_id, digest->mech_type, &mech_info);
       
  3333 
       
  3334 	if (rv != CKR_OK)
       
  3335 		{
       
  3336 		DEBUG_SLOT_SEL(" not found\n");
       
  3337 		return;
       
  3338 		}
       
  3339 
       
  3340 	if (mech_info.flags & CKF_DIGEST)
       
  3341 		{
       
  3342 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3343 		if (nid_in_table(digest->nid, hw_dnids))
       
  3344 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3345 			{
       
  3346 			DEBUG_SLOT_SEL(" usable\n");
       
  3347 			local_digest_nids[(*current_slot_n_digest)++] =
       
  3348 			    digest->nid;
       
  3349 			}
       
  3350 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3351 		else
       
  3352 			{
       
  3353 			DEBUG_SLOT_SEL(
       
  3354 			    " rejected, software implementation only\n");
       
  3355 			}
       
  3356 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3357 		}
       
  3358 	else
       
  3359 		{
       
  3360 		DEBUG_SLOT_SEL(" unusable\n");
       
  3361 		}
       
  3362 
       
  3363 	return;
       
  3364 	}
       
  3365 
       
  3366 /* Find what symmetric ciphers this slot supports. */
       
  3367 static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist,
       
  3368     CK_SLOT_ID current_slot, int *current_slot_n_cipher, int *local_cipher_nids)
       
  3369 	{
       
  3370 	int i;
       
  3371 
       
  3372 	for (i = 0; i < PK11_CIPHER_MAX; ++i)
       
  3373 		{
       
  3374 		pk11_get_symmetric_cipher(pflist, current_slot,
       
  3375 		    current_slot_n_cipher, local_cipher_nids, &ciphers[i]);
       
  3376 		}
       
  3377 	}
       
  3378 
       
  3379 /* Find what digest algorithms this slot supports. */
       
  3380 static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
       
  3381     CK_SLOT_ID current_slot, int *current_slot_n_digest, int *local_digest_nids)
       
  3382 	{
       
  3383 	int i;
       
  3384 
       
  3385 	for (i = 0; i < PK11_DIGEST_MAX; ++i)
       
  3386 		{
       
  3387 		pk11_get_digest(pflist, current_slot, current_slot_n_digest,
       
  3388 		    local_digest_nids, &digests[i]);
       
  3389 		}
       
  3390 	}
       
  3391 
       
  3392 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3393 /*
       
  3394  * It would be great if we could use pkcs11_kernel directly since this library
       
  3395  * offers hardware slots only. That's the easiest way to achieve the situation
       
  3396  * where we use the hardware accelerators when present and OpenSSL native code
       
  3397  * otherwise. That presumes the fact that OpenSSL native code is faster than the
       
  3398  * code in the soft token. It's a logical assumption - Crypto Framework has some
       
  3399  * inherent overhead so going there for the software implementation of a
       
  3400  * mechanism should be logically slower in contrast to the OpenSSL native code,
       
  3401  * presuming that both implementations are of similar speed. For example, the
       
  3402  * soft token for AES is roughly three times slower than OpenSSL for 64 byte
       
  3403  * blocks and still 20% slower for 8KB blocks. So, if we want to ship products
       
  3404  * that use the PKCS#11 engine by default, we must somehow avoid that regression
       
  3405  * on machines without hardware acceleration. That's why switching to the
       
  3406  * pkcs11_kernel library seems like a very good idea.
       
  3407  *
       
  3408  * The problem is that OpenSSL built with SunStudio is roughly 2x slower for
       
  3409  * asymmetric operations (RSA/DSA/DH) than the soft token built with the same
       
  3410  * compiler. That means that if we switched to pkcs11_kernel from the libpkcs11
       
  3411  * library, we would have had a performance regression on machines without
       
  3412  * hardware acceleration for asymmetric operations for all applications that use
       
  3413  * the PKCS#11 engine. There is one such application - Apache web server since
       
  3414  * it's shipped configured to use the PKCS#11 engine by default. Having said
       
  3415  * that, we can't switch to the pkcs11_kernel library now and have to come with
       
  3416  * a solution that, on non-accelerated machines, uses the OpenSSL native code
       
  3417  * for all symmetric ciphers and digests while it uses the soft token for
       
  3418  * asymmetric operations.
       
  3419  *
       
  3420  * This is the idea: dlopen() pkcs11_kernel directly and find out what
       
  3421  * mechanisms are there. We don't care about duplications (more slots can
       
  3422  * support the same mechanism), we just want to know what mechanisms can be
       
  3423  * possibly supported in hardware on that particular machine. As said before,
       
  3424  * pkcs11_kernel will show you hardware providers only.
       
  3425  *
       
  3426  * Then, we rely on the fact that since we use libpkcs11 library we will find
       
  3427  * the metaslot. When we go through the metaslot's mechanisms for symmetric
       
  3428  * ciphers and digests, we check that any found mechanism is in the table
       
  3429  * created using the pkcs11_kernel library. So, as a result we have two arrays
       
  3430  * of mechanisms that were advertised as supported in hardware which was the
       
  3431  * goal of that whole exercise. Thus, we can use libpkcs11 but avoid soft token
       
  3432  * code for symmetric ciphers and digests. See pk11_choose_slots() for more
       
  3433  * information.
       
  3434  *
       
  3435  * This is Solaris specific code, if SOLARIS_HW_SLOT_SELECTION is not defined
       
  3436  * the code won't be used.
       
  3437  */
       
  3438 #if defined(__sparcv9) || defined(__x86_64) || defined(__amd64)
       
  3439 static const char pkcs11_kernel[] = "/usr/lib/security/64/pkcs11_kernel.so.1";
       
  3440 #else
       
  3441 static const char pkcs11_kernel[] = "/usr/lib/security/pkcs11_kernel.so.1";
       
  3442 #endif
       
  3443 
       
  3444 /*
       
  3445  * Check hardware capabilities of the machines. The output are two lists,
       
  3446  * hw_cnids and hw_dnids, that contain hardware mechanisms found in all hardware
       
  3447  * providers together. They are not sorted and may contain duplicate mechanisms.
       
  3448  */
       
  3449 static int check_hw_mechanisms(void)
       
  3450 	{
       
  3451 	int i;
       
  3452 	CK_RV rv;
       
  3453 	void *handle;
       
  3454 	CK_C_GetFunctionList p;
       
  3455 	CK_TOKEN_INFO token_info;
       
  3456 	CK_ULONG ulSlotCount = 0;
       
  3457 	int n_cipher = 0, n_digest = 0;
       
  3458 	CK_FUNCTION_LIST_PTR pflist = NULL;
       
  3459 	CK_SLOT_ID_PTR pSlotList = NULL_PTR;
       
  3460 	int *tmp_hw_cnids = NULL, *tmp_hw_dnids = NULL;
       
  3461 	int hw_ctable_size, hw_dtable_size;
       
  3462 
       
  3463 	DEBUG_SLOT_SEL("%s: SOLARIS_HW_SLOT_SELECTION code running\n",
       
  3464 	    PK11_DBG);
       
  3465 	/*
       
  3466 	 * Use RTLD_GROUP to limit the pkcs11_kernel provider to its own
       
  3467 	 * symbols, which prevents it from mistakenly accessing C_* functions
       
  3468 	 * from the top-level PKCS#11 library.
       
  3469 	 */
       
  3470 	if ((handle = dlopen(pkcs11_kernel, RTLD_LAZY | RTLD_GROUP)) == NULL)
       
  3471 		{
       
  3472 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
       
  3473 		goto err;
       
  3474 		}
       
  3475 
       
  3476 	if ((p = (CK_C_GetFunctionList)dlsym(handle,
       
  3477 	    PK11_GET_FUNCTION_LIST)) == NULL)
       
  3478 		{
       
  3479 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
       
  3480 		goto err;
       
  3481 		}
       
  3482 
       
  3483 	/* get the full function list from the loaded library */
       
  3484 	if (p(&pflist) != CKR_OK)
       
  3485 		{
       
  3486 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
       
  3487 		goto err;
       
  3488 		}
       
  3489 
       
  3490 	rv = pflist->C_Initialize(NULL_PTR);
       
  3491 	if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
       
  3492 		{
       
  3493 		PK11err_add_data(PK11_F_CHECK_HW_MECHANISMS,
       
  3494 		    PK11_R_INITIALIZE, rv);
       
  3495 		goto err;
       
  3496 		}
       
  3497 
       
  3498 	if (pflist->C_GetSlotList(0, NULL_PTR, &ulSlotCount) != CKR_OK)
       
  3499 		{
       
  3500 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
       
  3501 		goto err;
       
  3502 		}
       
  3503 
       
  3504 	/* no slots, set the hw mechanism tables as empty */
       
  3505 	if (ulSlotCount == 0)
       
  3506 		{
       
  3507 		DEBUG_SLOT_SEL("%s: no hardware mechanisms found\n", PK11_DBG);
       
  3508 		hw_cnids = OPENSSL_malloc(sizeof (int));
       
  3509 		hw_dnids = OPENSSL_malloc(sizeof (int));
       
  3510 		if (hw_cnids == NULL || hw_dnids == NULL)
       
  3511 			{
       
  3512 			PK11err(PK11_F_CHECK_HW_MECHANISMS,
       
  3513 			    PK11_R_MALLOC_FAILURE);
       
  3514 			return (0);
       
  3515 			}
       
  3516 		/* this means empty tables */
       
  3517 		hw_cnids[0] = NID_undef;
       
  3518 		hw_dnids[0] = NID_undef;
       
  3519 		return (1);
       
  3520 		}
       
  3521 
       
  3522 	pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
       
  3523 	if (pSlotList == NULL)
       
  3524 		{
       
  3525 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
       
  3526 		goto err;
       
  3527 		}
       
  3528 
       
  3529 	/* Get the slot list for processing */
       
  3530 	if (pflist->C_GetSlotList(0, pSlotList, &ulSlotCount) != CKR_OK)
       
  3531 		{
       
  3532 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
       
  3533 		goto err;
       
  3534 		}
       
  3535 
       
  3536 	/*
       
  3537 	 * We don't care about duplicate mechanisms in multiple slots and also
       
  3538 	 * reserve one slot for the terminal NID_undef which we use to stop the
       
  3539 	 * search.
       
  3540 	 */
       
  3541 	hw_ctable_size = ulSlotCount * PK11_CIPHER_MAX + 1;
       
  3542 	hw_dtable_size = ulSlotCount * PK11_DIGEST_MAX + 1;
       
  3543 	tmp_hw_cnids = OPENSSL_malloc(hw_ctable_size * sizeof (int));
       
  3544 	tmp_hw_dnids = OPENSSL_malloc(hw_dtable_size * sizeof (int));
       
  3545 	if (tmp_hw_cnids == NULL || tmp_hw_dnids == NULL)
       
  3546 		{
       
  3547 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
       
  3548 		goto err;
       
  3549 		}
       
  3550 
       
  3551 	/*
       
  3552 	 * Do not use memset since we should not rely on the fact that NID_undef
       
  3553 	 * is zero now.
       
  3554 	 */
       
  3555 	for (i = 0; i < hw_ctable_size; ++i)
       
  3556 		tmp_hw_cnids[i] = NID_undef;
       
  3557 	for (i = 0; i < hw_dtable_size; ++i)
       
  3558 		tmp_hw_dnids[i] = NID_undef;
       
  3559 
       
  3560 	DEBUG_SLOT_SEL("%s: provider: %s\n", PK11_DBG, pkcs11_kernel);
       
  3561 	DEBUG_SLOT_SEL("%s: found %d hardware slots\n", PK11_DBG, ulSlotCount);
       
  3562 	DEBUG_SLOT_SEL("%s: now looking for mechs supported in hw\n",
       
  3563 	    PK11_DBG);
       
  3564 
       
  3565 	for (i = 0; i < ulSlotCount; i++)
       
  3566 		{
       
  3567 		if (pflist->C_GetTokenInfo(pSlotList[i], &token_info) != CKR_OK)
       
  3568 			continue;
       
  3569 
       
  3570 		DEBUG_SLOT_SEL("%s: token label: %.32s\n", PK11_DBG,
       
  3571 		    token_info.label);
       
  3572 
       
  3573 		/*
       
  3574 		 * We are filling the hw mech tables here. Global tables are
       
  3575 		 * still NULL so all mechanisms are put into tmp tables.
       
  3576 		 */
       
  3577 		pk11_find_symmetric_ciphers(pflist, pSlotList[i],
       
  3578 		    &n_cipher, tmp_hw_cnids);
       
  3579 		pk11_find_digests(pflist, pSlotList[i],
       
  3580 		    &n_digest, tmp_hw_dnids);
       
  3581 		}
       
  3582 
       
  3583 	/*
       
  3584 	 * Since we are part of a library (libcrypto.so), calling this function
       
  3585 	 * may have side-effects. Also, C_Finalize() is triggered by
       
  3586 	 * dlclose(3C).
       
  3587 	 */
       
  3588 #if 0
       
  3589 	pflist->C_Finalize(NULL);
       
  3590 #endif
       
  3591 	OPENSSL_free(pSlotList);
       
  3592 	(void) dlclose(handle);
       
  3593 	hw_cnids = tmp_hw_cnids;
       
  3594 	hw_dnids = tmp_hw_dnids;
       
  3595 
       
  3596 	DEBUG_SLOT_SEL("%s: hw mechs check complete\n", PK11_DBG);
       
  3597 	return (1);
       
  3598 
       
  3599 err:
       
  3600 	if (pSlotList != NULL)
       
  3601 		OPENSSL_free(pSlotList);
       
  3602 	if (tmp_hw_cnids != NULL)
       
  3603 		OPENSSL_free(tmp_hw_cnids);
       
  3604 	if (tmp_hw_dnids != NULL)
       
  3605 		OPENSSL_free(tmp_hw_dnids);
       
  3606 
       
  3607 	return (0);
       
  3608 	}
       
  3609 
       
  3610 /*
       
  3611  * Check presence of a NID in the table of NIDs. The table may be NULL (i.e.,
       
  3612  * non-existent).
       
  3613  */
       
  3614 static int nid_in_table(int nid, int *nid_table)
       
  3615 	{
       
  3616 	int i = 0;
       
  3617 
       
  3618 	/*
       
  3619 	 * a special case. NULL means that we are initializing a new
       
  3620 	 * table.
       
  3621 	 */
       
  3622 	if (nid_table == NULL)
       
  3623 		return (1);
       
  3624 
       
  3625 	/*
       
  3626 	 * the table is never full, there is always at least one
       
  3627 	 * NID_undef.
       
  3628 	 */
       
  3629 	while (nid_table[i] != NID_undef)
       
  3630 		{
       
  3631 		if (nid_table[i++] == nid)
       
  3632 			{
       
  3633 			DEBUG_SLOT_SEL(" (NID %d in hw table, idx %d)", nid, i);
       
  3634 			return (1);
       
  3635 			}
       
  3636 		}
       
  3637 
       
  3638 	return (0);
       
  3639 	}
       
  3640 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3641 
       
  3642 #endif	/* OPENSSL_NO_HW_PK11 */
       
  3643 #endif	/* OPENSSL_NO_HW */