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