components/openssl/openssl-1.0.1/engines/pkcs11/e_pk11.c
branchs11u3-sru
changeset 7163 ee09edbd5876
parent 7159 59b406bc4a3a
child 7164 b2abbab8e6d5
equal deleted inserted replaced
7159:59b406bc4a3a 7163:ee09edbd5876
     1 /*
       
     2  * Copyright (c) 2004, 2015, 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 	/* invalidate the global session */
       
  1070 	global_session = CK_INVALID_HANDLE;
       
  1071 
       
  1072 	for (i = OP_MAX - 1; i >= 0; i--)
       
  1073 		{
       
  1074 		(void) pthread_mutex_unlock(session_cache[i].lock);
       
  1075 		}
       
  1076 	UNLOCK_OBJSTORE(OP_DH);
       
  1077 	UNLOCK_OBJSTORE(OP_DSA);
       
  1078 	UNLOCK_OBJSTORE(OP_RSA);
       
  1079 	(void) pthread_mutex_unlock(uri_lock);
       
  1080 	}
       
  1081 
       
  1082 /* Initialization function for the pk11 engine */
       
  1083 static int pk11_init(ENGINE *e)
       
  1084 {
       
  1085 	return (pk11_library_init(e));
       
  1086 }
       
  1087 
       
  1088 /*
       
  1089  * Helper function that unsets reference to current engine (pk11_engine = NULL).
       
  1090  *
       
  1091  * Use of local variable only seems clumsy, it needs to be this way!
       
  1092  * This is to prevent double free in the unlucky scenario:
       
  1093  *     ENGINE_free calls pk11_destroy calls pk11_finish calls ENGINE_free
       
  1094  * Setting pk11_engine to NULL prior to ENGINE_free() avoids this.
       
  1095  */
       
  1096 static void pk11_engine_free()
       
  1097 	{
       
  1098 	ENGINE* old_engine = pk11_engine;
       
  1099 
       
  1100 	if (old_engine) {
       
  1101 		pk11_engine = NULL;
       
  1102 	}
       
  1103 	}
       
  1104 
       
  1105 /*
       
  1106  * Initialization function. Sets up various PKCS#11 library components.
       
  1107  * It selects a slot based on predefined critiera. In the process, it also
       
  1108  * count how many ciphers and digests to support. Since the cipher and
       
  1109  * digest information is needed when setting default engine, this function
       
  1110  * needs to be called before calling ENGINE_set_default.
       
  1111  */
       
  1112 /* ARGSUSED */
       
  1113 static int pk11_library_init(ENGINE *e)
       
  1114 	{
       
  1115 	CK_C_GetFunctionList p;
       
  1116 	CK_RV rv = CKR_OK;
       
  1117 	CK_INFO info;
       
  1118 	CK_ULONG ul_state_len;
       
  1119 	int any_slot_found;
       
  1120 	int i;
       
  1121 
       
  1122 	if (e != pk11_engine)
       
  1123 		{
       
  1124 		pk11_engine_free();
       
  1125 		pk11_engine = e;
       
  1126 		}
       
  1127 
       
  1128 	/*
       
  1129 	 * pk11_library_initialized is set to 0 in pk11_finish() which is called
       
  1130 	 * from ENGINE_finish(). However, if there is still at least one
       
  1131 	 * existing functional reference to the engine (see engine(3) for more
       
  1132 	 * information), pk11_finish() is skipped. For example, this can happen
       
  1133 	 * if an application forgets to clear one cipher context. In case of a
       
  1134 	 * fork() when the application is finishing the engine so that it can be
       
  1135 	 * reinitialized in the child, forgotten functional reference causes
       
  1136 	 * pk11_library_initialized to stay 1. In that case we need the PID
       
  1137 	 * check so that we properly initialize the engine again.
       
  1138 	 */
       
  1139 	if (pk11_library_initialized)
       
  1140 		{
       
  1141 		if (pk11_pid == getpid())
       
  1142 			{
       
  1143 			return (1);
       
  1144 			}
       
  1145 		else
       
  1146 			{
       
  1147 			global_session = CK_INVALID_HANDLE;
       
  1148 			/*
       
  1149 			 * free the locks first to prevent memory leak in case
       
  1150 			 * the application calls fork() without finishing the
       
  1151 			 * engine first.
       
  1152 			 */
       
  1153 			pk11_free_all_locks();
       
  1154 			}
       
  1155 		}
       
  1156 
       
  1157 	/*
       
  1158 	 * If initialization of the locks fails pk11_init_all_locks()
       
  1159 	 * will do the cleanup.
       
  1160 	 */
       
  1161 	if (!pk11_init_all_locks())
       
  1162 		goto err;
       
  1163 	for (i = 0; i < OP_MAX; i++)
       
  1164 		session_cache[i].head = NULL;
       
  1165 	/*
       
  1166 	 * Initialize active lists. We only use active lists
       
  1167 	 * for asymmetric ciphers.
       
  1168 	 */
       
  1169 	for (i = 0; i < OP_MAX; i++)
       
  1170 		active_list[i] = NULL;
       
  1171 
       
  1172 	/* Attempt to load PKCS#11 library. */
       
  1173 	if (!pk11_dso)
       
  1174 		{
       
  1175 		pk11_dso = DSO_load(NULL, get_PK11_LIBNAME(), NULL, 0);
       
  1176 		if (pk11_dso == NULL)
       
  1177 			{
       
  1178 			PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
       
  1179 			goto err;
       
  1180 			}
       
  1181 		}
       
  1182 
       
  1183 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  1184 	if (check_hw_mechanisms() == 0)
       
  1185 		goto err;
       
  1186 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  1187 
       
  1188 	/* get the C_GetFunctionList function from the loaded library */
       
  1189 	p = (CK_C_GetFunctionList)DSO_bind_func(pk11_dso,
       
  1190 		PK11_GET_FUNCTION_LIST);
       
  1191 	if (!p)
       
  1192 		{
       
  1193 		PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
       
  1194 		goto err;
       
  1195 		}
       
  1196 
       
  1197 	/* get the full function list from the loaded library */
       
  1198 	rv = p(&pFuncList);
       
  1199 	if (rv != CKR_OK)
       
  1200 		{
       
  1201 		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE, rv);
       
  1202 		goto err;
       
  1203 		}
       
  1204 
       
  1205 	rv = pFuncList->C_Initialize(NULL_PTR);
       
  1206 	if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
       
  1207 		{
       
  1208 		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE, rv);
       
  1209 		goto err;
       
  1210 		}
       
  1211 
       
  1212 	rv = pFuncList->C_GetInfo(&info);
       
  1213 	if (rv != CKR_OK)
       
  1214 		{
       
  1215 		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_GETINFO, rv);
       
  1216 		goto err;
       
  1217 		}
       
  1218 
       
  1219 	if (pk11_choose_slots(&any_slot_found) == 0)
       
  1220 		goto err;
       
  1221 
       
  1222 	/*
       
  1223 	 * The library we use, set in def_PK11_LIBNAME, may not offer any
       
  1224 	 * slot(s). In that case, we must not proceed but we must not return an
       
  1225 	 * error. The reason is that applications that try to set up the PKCS#11
       
  1226 	 * engine don't exit on error during the engine initialization just
       
  1227 	 * because no slot was present.
       
  1228 	 */
       
  1229 	if (any_slot_found == 0)
       
  1230 		return (1);
       
  1231 
       
  1232 	if (global_session == CK_INVALID_HANDLE)
       
  1233 		{
       
  1234 		/* Open the global_session for the new process */
       
  1235 		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
       
  1236 			NULL_PTR, NULL_PTR, &global_session);
       
  1237 		if (rv != CKR_OK)
       
  1238 			{
       
  1239 			PK11err_add_data(PK11_F_LIBRARY_INIT,
       
  1240 			    PK11_R_OPENSESSION, rv);
       
  1241 			goto err;
       
  1242 			}
       
  1243 		}
       
  1244 
       
  1245 	/*
       
  1246 	 * Disable digest if C_GetOperationState is not supported since
       
  1247 	 * this function is required by OpenSSL digest copy function
       
  1248 	 */
       
  1249 	if (pFuncList->C_GetOperationState(global_session, NULL, &ul_state_len)
       
  1250 			== CKR_FUNCTION_NOT_SUPPORTED) {
       
  1251 		DEBUG_SLOT_SEL("%s: C_GetOperationState() not supported, "
       
  1252 		    "setting digest_count to 0\n", PK11_DBG);
       
  1253 		digest_count = 0;
       
  1254 	}
       
  1255 
       
  1256 	pk11_library_initialized = CK_TRUE;
       
  1257 	pk11_pid = getpid();
       
  1258 
       
  1259 	if (!pk11_atfork_initialized)
       
  1260 		{
       
  1261 		if (pthread_atfork(pk11_fork_prepare, pk11_fork_parent,
       
  1262 		    pk11_fork_child) != 0)
       
  1263 			{
       
  1264 			PK11err(PK11_F_LIBRARY_INIT, PK11_R_ATFORK_FAILED);
       
  1265 			goto err;
       
  1266 			}
       
  1267 		pk11_atfork_initialized = CK_TRUE;
       
  1268 		}
       
  1269 
       
  1270 	return (1);
       
  1271 
       
  1272 err:
       
  1273 	return (0);
       
  1274 	}
       
  1275 
       
  1276 /* Destructor (complements the "ENGINE_pk11()" constructor) */
       
  1277 /* ARGSUSED */
       
  1278 static int pk11_destroy(ENGINE *e)
       
  1279 	{
       
  1280 	int rtn = 1;
       
  1281 
       
  1282 	free_PK11_LIBNAME();
       
  1283 	ERR_unload_pk11_strings();
       
  1284 	if (pk11_library_initialized == CK_TRUE)
       
  1285 		rtn = pk11_finish(e);
       
  1286 
       
  1287 	return (rtn);
       
  1288 	}
       
  1289 
       
  1290 /*
       
  1291  * Termination function to clean up the session, the token, and the pk11
       
  1292  * library.
       
  1293  */
       
  1294 /* ARGSUSED */
       
  1295 static int pk11_finish(ENGINE *e)
       
  1296 	{
       
  1297 	int i;
       
  1298 
       
  1299 	/*
       
  1300 	 * Make sure, right engine instance is being destroyed.
       
  1301 	 * Engine e may be the wrong instance if
       
  1302 	 * 	1) either someone calls ENGINE_load_pk11 twice
       
  1303 	 * 	2) or last ref. to an already finished engine is being destroyed
       
  1304 	 */
       
  1305 	if (e != pk11_engine)
       
  1306 		goto err;
       
  1307 
       
  1308 	if (pk11_dso == NULL)
       
  1309 		{
       
  1310 		PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
       
  1311 		goto err;
       
  1312 		}
       
  1313 
       
  1314 	OPENSSL_assert(pFuncList != NULL);
       
  1315 
       
  1316 	if (pk11_free_all_sessions() == 0)
       
  1317 		goto err;
       
  1318 
       
  1319 	/* free all active lists */
       
  1320 	for (i = 0; i < OP_MAX; i++)
       
  1321 		pk11_free_active_list(i);
       
  1322 
       
  1323 	/* Global session is not present when there are no slots. */
       
  1324 	if (global_session != CK_INVALID_HANDLE)
       
  1325 		{
       
  1326 		pFuncList->C_CloseSession(global_session);
       
  1327 		global_session = CK_INVALID_HANDLE;
       
  1328 		}
       
  1329 
       
  1330 	/*
       
  1331 	 * Since we are part of a library (libcrypto.so), calling this function
       
  1332 	 * may have side-effects.
       
  1333 	 */
       
  1334 #if 0
       
  1335 	pFuncList->C_Finalize(NULL);
       
  1336 #endif
       
  1337 	if (!DSO_free(pk11_dso))
       
  1338 		{
       
  1339 		PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
       
  1340 		goto err;
       
  1341 		}
       
  1342 	pk11_dso = NULL;
       
  1343 	pFuncList = NULL;
       
  1344 	pk11_library_initialized = CK_FALSE;
       
  1345 	pk11_pid = 0;
       
  1346 	pk11_engine_free();
       
  1347 	/*
       
  1348 	 * There is no way how to unregister atfork handlers (other than
       
  1349 	 * unloading the library) so we just free the locks. For this reason
       
  1350 	 * the atfork handlers check if the engine is initialized and bail out
       
  1351 	 * immediately if not. This is necessary in case a process finishes
       
  1352 	 * the engine before calling fork().
       
  1353 	 */
       
  1354 	pk11_free_all_locks();
       
  1355 
       
  1356 	return (1);
       
  1357 
       
  1358 err:
       
  1359 	return (0);
       
  1360 	}
       
  1361 
       
  1362 /* Standard engine interface function to set the dynamic library path */
       
  1363 /* ARGSUSED */
       
  1364 static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
       
  1365 	{
       
  1366 	int initialized = ((pk11_dso == NULL) ? 0 : 1);
       
  1367 
       
  1368 	switch (cmd)
       
  1369 		{
       
  1370 	case PK11_CMD_SO_PATH:
       
  1371 		if (p == NULL)
       
  1372 			{
       
  1373 			PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
       
  1374 			return (0);
       
  1375 			}
       
  1376 
       
  1377 		if (initialized)
       
  1378 			{
       
  1379 			PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
       
  1380 			return (0);
       
  1381 			}
       
  1382 
       
  1383 		return (set_PK11_LIBNAME((const char *)p));
       
  1384 	default:
       
  1385 		break;
       
  1386 		}
       
  1387 
       
  1388 	PK11err(PK11_F_CTRL, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
       
  1389 
       
  1390 	return (0);
       
  1391 	}
       
  1392 
       
  1393 
       
  1394 /* Required function by the engine random interface. It does nothing here */
       
  1395 static void pk11_rand_cleanup(void)
       
  1396 	{
       
  1397 	return;
       
  1398 	}
       
  1399 
       
  1400 /* ARGSUSED */
       
  1401 static void pk11_rand_add(const void *buf, int num, double add)
       
  1402 	{
       
  1403 	PK11_SESSION *sp;
       
  1404 
       
  1405 	if ((sp = pk11_get_session(OP_RAND)) == NULL)
       
  1406 		return;
       
  1407 
       
  1408 	/*
       
  1409 	 * Ignore any errors (e.g. CKR_RANDOM_SEED_NOT_SUPPORTED) since
       
  1410 	 * the calling functions do not care anyway
       
  1411 	 */
       
  1412 	pFuncList->C_SeedRandom(sp->session, (unsigned char *) buf, num);
       
  1413 	pk11_return_session(sp, OP_RAND);
       
  1414 
       
  1415 	return;
       
  1416 	}
       
  1417 
       
  1418 static void pk11_rand_seed(const void *buf, int num)
       
  1419 	{
       
  1420 	pk11_rand_add(buf, num, 0);
       
  1421 	}
       
  1422 
       
  1423 static int pk11_rand_bytes(unsigned char *buf, int num)
       
  1424 	{
       
  1425 	CK_RV rv;
       
  1426 	PK11_SESSION *sp;
       
  1427 
       
  1428 	if ((sp = pk11_get_session(OP_RAND)) == NULL)
       
  1429 		return (0);
       
  1430 
       
  1431 	rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
       
  1432 	if (rv != CKR_OK)
       
  1433 		{
       
  1434 		PK11err_add_data(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM, rv);
       
  1435 		pk11_return_session(sp, OP_RAND);
       
  1436 		return (0);
       
  1437 		}
       
  1438 
       
  1439 	pk11_return_session(sp, OP_RAND);
       
  1440 	return (1);
       
  1441 	}
       
  1442 
       
  1443 /* Required function by the engine random interface. It does nothing here */
       
  1444 static int pk11_rand_status(void)
       
  1445 	{
       
  1446 	return (1);
       
  1447 	}
       
  1448 
       
  1449 /* Free all BIGNUM structures from PK11_SESSION. */
       
  1450 static void pk11_free_nums(PK11_SESSION *sp, PK11_OPTYPE optype)
       
  1451 	{
       
  1452 	switch (optype)
       
  1453 		{
       
  1454 #ifndef	OPENSSL_NO_RSA
       
  1455 		case OP_RSA:
       
  1456 			if (sp->opdata_rsa_n_num != NULL)
       
  1457 				{
       
  1458 				BN_free(sp->opdata_rsa_n_num);
       
  1459 				sp->opdata_rsa_n_num = NULL;
       
  1460 				}
       
  1461 			if (sp->opdata_rsa_e_num != NULL)
       
  1462 				{
       
  1463 				BN_free(sp->opdata_rsa_e_num);
       
  1464 				sp->opdata_rsa_e_num = NULL;
       
  1465 				}
       
  1466 			if (sp->opdata_rsa_d_num != NULL)
       
  1467 				{
       
  1468 				BN_free(sp->opdata_rsa_d_num);
       
  1469 				sp->opdata_rsa_d_num = NULL;
       
  1470 				}
       
  1471 			break;
       
  1472 #endif
       
  1473 #ifndef	OPENSSL_NO_DSA
       
  1474 		case OP_DSA:
       
  1475 			if (sp->opdata_dsa_pub_num != NULL)
       
  1476 				{
       
  1477 				BN_free(sp->opdata_dsa_pub_num);
       
  1478 				sp->opdata_dsa_pub_num = NULL;
       
  1479 				}
       
  1480 			if (sp->opdata_dsa_priv_num != NULL)
       
  1481 				{
       
  1482 				BN_free(sp->opdata_dsa_priv_num);
       
  1483 				sp->opdata_dsa_priv_num = NULL;
       
  1484 				}
       
  1485 			break;
       
  1486 #endif
       
  1487 #ifndef	OPENSSL_NO_DH
       
  1488 		case OP_DH:
       
  1489 			if (sp->opdata_dh_priv_num != NULL)
       
  1490 				{
       
  1491 				BN_free(sp->opdata_dh_priv_num);
       
  1492 				sp->opdata_dh_priv_num = NULL;
       
  1493 				}
       
  1494 			break;
       
  1495 #endif
       
  1496 		default:
       
  1497 			break;
       
  1498 		}
       
  1499 	}
       
  1500 
       
  1501 /*
       
  1502  * Get new PK11_SESSION structure ready for use. Every process must have
       
  1503  * its own freelist of PK11_SESSION structures so handle fork() here
       
  1504  * by destroying the old and creating new freelist.
       
  1505  * The returned PK11_SESSION structure is disconnected from the freelist.
       
  1506  */
       
  1507 PK11_SESSION *
       
  1508 pk11_get_session(PK11_OPTYPE optype)
       
  1509 	{
       
  1510 	PK11_SESSION *sp = NULL, *sp1, *freelist;
       
  1511 	pthread_mutex_t *freelist_lock;
       
  1512 	static pid_t pid = 0;
       
  1513 	pid_t new_pid;
       
  1514 	CK_RV rv;
       
  1515 
       
  1516 	switch (optype)
       
  1517 		{
       
  1518 		case OP_RSA:
       
  1519 		case OP_DSA:
       
  1520 		case OP_DH:
       
  1521 		case OP_RAND:
       
  1522 		case OP_DIGEST:
       
  1523 		case OP_CIPHER:
       
  1524 			freelist_lock = session_cache[optype].lock;
       
  1525 			break;
       
  1526 		default:
       
  1527 			PK11err(PK11_F_GET_SESSION,
       
  1528 				PK11_R_INVALID_OPERATION_TYPE);
       
  1529 			return (NULL);
       
  1530 		}
       
  1531 	(void) pthread_mutex_lock(freelist_lock);
       
  1532 
       
  1533 	/*
       
  1534 	 * Will use it to find out if we forked. We cannot use the PID field in
       
  1535 	 * the session structure because we could get a newly allocated session
       
  1536 	 * here, with no PID information.
       
  1537 	 */
       
  1538 	if (pid == 0)
       
  1539 		pid = getpid();
       
  1540 
       
  1541 	freelist = session_cache[optype].head;
       
  1542 	sp = freelist;
       
  1543 
       
  1544 	/*
       
  1545 	 * If the free list is empty, allocate new uninitialized (filled
       
  1546 	 * with zeroes) PK11_SESSION structure otherwise return first
       
  1547 	 * structure from the freelist.
       
  1548 	 */
       
  1549 	if (sp == NULL)
       
  1550 		{
       
  1551 		if ((sp = OPENSSL_malloc(sizeof (PK11_SESSION))) == NULL)
       
  1552 			{
       
  1553 			PK11err(PK11_F_GET_SESSION,
       
  1554 				PK11_R_MALLOC_FAILURE);
       
  1555 			goto err;
       
  1556 			}
       
  1557 		(void) memset(sp, 0, sizeof (PK11_SESSION));
       
  1558 
       
  1559 		/*
       
  1560 		 * It is a new session so it will look like a cache miss to the
       
  1561 		 * code below. So, we must not try to to destroy its members so
       
  1562 		 * mark them as unused.
       
  1563 		 */
       
  1564 		sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
       
  1565 		sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
       
  1566 		}
       
  1567 	else
       
  1568 		freelist = sp->next;
       
  1569 
       
  1570 	/*
       
  1571 	 * Check whether we have forked. In that case, we must get rid of all
       
  1572 	 * inherited sessions and start allocating new ones.
       
  1573 	 */
       
  1574 	if (pid != (new_pid = getpid()))
       
  1575 		{
       
  1576 		pid = new_pid;
       
  1577 
       
  1578 		/*
       
  1579 		 * We are a new process and thus need to free any inherited
       
  1580 		 * PK11_SESSION objects aside from the first session (sp) which
       
  1581 		 * is the only PK11_SESSION structure we will reuse (for the
       
  1582 		 * head of the list).
       
  1583 		 */
       
  1584 		while ((sp1 = freelist) != NULL)
       
  1585 			{
       
  1586 			freelist = sp1->next;
       
  1587 			/*
       
  1588 			 * NOTE: we do not want to call pk11_free_all_sessions()
       
  1589 			 * here because it would close underlying PKCS#11
       
  1590 			 * sessions and destroy all objects.
       
  1591 			 */
       
  1592 			pk11_free_nums(sp1, optype);
       
  1593 			OPENSSL_free(sp1);
       
  1594 			}
       
  1595 
       
  1596 		/* we have to free the active list as well. */
       
  1597 		pk11_free_active_list(optype);
       
  1598 
       
  1599 		/* Initialize the process */
       
  1600 		rv = pFuncList->C_Initialize(NULL_PTR);
       
  1601 		if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
       
  1602 			{
       
  1603 			PK11err_add_data(PK11_F_GET_SESSION, PK11_R_INITIALIZE,
       
  1604 			    rv);
       
  1605 			OPENSSL_free(sp);
       
  1606 			sp = NULL;
       
  1607 			goto err;
       
  1608 			}
       
  1609 
       
  1610 		/*
       
  1611 		 * Choose slot here since the slot table is different on this
       
  1612 		 * process. If we are here then we must have found at least one
       
  1613 		 * usable slot before so we don't need to check any_slot_found.
       
  1614 		 * See pk11_library_init()'s usage of this function for more
       
  1615 		 * information.
       
  1616 		 */
       
  1617 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  1618 		if (check_hw_mechanisms() == 0)
       
  1619 			goto err;
       
  1620 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  1621 		if (pk11_choose_slots(NULL) == 0)
       
  1622 			goto err;
       
  1623 
       
  1624 		/* Open the global_session for the new process */
       
  1625 		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
       
  1626 			NULL_PTR, NULL_PTR, &global_session);
       
  1627 		if (rv != CKR_OK)
       
  1628 			{
       
  1629 			PK11err_add_data(PK11_F_GET_SESSION, PK11_R_OPENSESSION,
       
  1630 			    rv);
       
  1631 			OPENSSL_free(sp);
       
  1632 			sp = NULL;
       
  1633 			goto err;
       
  1634 			}
       
  1635 
       
  1636 		/*
       
  1637 		 * It is an inherited session from our parent so it needs
       
  1638 		 * re-initialization.
       
  1639 		 */
       
  1640 		if (pk11_setup_session(sp, optype) == 0)
       
  1641 			{
       
  1642 			OPENSSL_free(sp);
       
  1643 			sp = NULL;
       
  1644 			goto err;
       
  1645 			}
       
  1646 		if (pk11_token_relogin(sp->session) == 0)
       
  1647 			{
       
  1648 			/*
       
  1649 			 * We will keep the session in the cache list and let
       
  1650 			 * the caller cope with the situation.
       
  1651 			 */
       
  1652 			freelist = sp;
       
  1653 			sp = NULL;
       
  1654 			goto err;
       
  1655 			}
       
  1656 		}
       
  1657 
       
  1658 	if (sp->pid == 0)
       
  1659 		{
       
  1660 		/* It is a new session and needs initialization. */
       
  1661 		if (pk11_setup_session(sp, optype) == 0)
       
  1662 			{
       
  1663 			OPENSSL_free(sp);
       
  1664 			sp = NULL;
       
  1665 			}
       
  1666 		}
       
  1667 
       
  1668 	/* set new head for the list of PK11_SESSION objects */
       
  1669 	session_cache[optype].head = freelist;
       
  1670 
       
  1671 err:
       
  1672 	if (sp != NULL)
       
  1673 		sp->next = NULL;
       
  1674 
       
  1675 	(void) pthread_mutex_unlock(freelist_lock);
       
  1676 
       
  1677 	return (sp);
       
  1678 	}
       
  1679 
       
  1680 
       
  1681 void
       
  1682 pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype)
       
  1683 	{
       
  1684 	pthread_mutex_t *freelist_lock;
       
  1685 	PK11_SESSION *freelist;
       
  1686 
       
  1687 	/*
       
  1688 	 * If this is a session from the parent it will be taken care of and
       
  1689 	 * freed in pk11_get_session() as part of the post-fork clean up the
       
  1690 	 * next time we will ask for a new session.
       
  1691 	 */
       
  1692 	if (sp == NULL || sp->pid != getpid())
       
  1693 		return;
       
  1694 
       
  1695 	switch (optype)
       
  1696 		{
       
  1697 		case OP_RSA:
       
  1698 		case OP_DSA:
       
  1699 		case OP_DH:
       
  1700 		case OP_RAND:
       
  1701 		case OP_DIGEST:
       
  1702 		case OP_CIPHER:
       
  1703 			freelist_lock = session_cache[optype].lock;
       
  1704 			break;
       
  1705 		default:
       
  1706 			PK11err(PK11_F_RETURN_SESSION,
       
  1707 				PK11_R_INVALID_OPERATION_TYPE);
       
  1708 			return;
       
  1709 		}
       
  1710 
       
  1711 	(void) pthread_mutex_lock(freelist_lock);
       
  1712 	freelist = session_cache[optype].head;
       
  1713 	sp->next = freelist;
       
  1714 	session_cache[optype].head = sp;
       
  1715 	(void) pthread_mutex_unlock(freelist_lock);
       
  1716 	}
       
  1717 
       
  1718 
       
  1719 /* Destroy all objects. This function is called when the engine is finished */
       
  1720 static int pk11_free_all_sessions()
       
  1721 	{
       
  1722 	int ret = 1;
       
  1723 	int type;
       
  1724 
       
  1725 #ifndef OPENSSL_NO_RSA
       
  1726 	(void) pk11_destroy_rsa_key_objects(NULL);
       
  1727 #endif	/* OPENSSL_NO_RSA */
       
  1728 #ifndef OPENSSL_NO_DSA
       
  1729 	(void) pk11_destroy_dsa_key_objects(NULL);
       
  1730 #endif	/* OPENSSL_NO_DSA */
       
  1731 #ifndef OPENSSL_NO_DH
       
  1732 	(void) pk11_destroy_dh_key_objects(NULL);
       
  1733 #endif	/* OPENSSL_NO_DH */
       
  1734 	(void) pk11_destroy_cipher_key_objects(NULL);
       
  1735 
       
  1736 	/*
       
  1737 	 * We try to release as much as we can but any error means that we will
       
  1738 	 * return 0 on exit.
       
  1739 	 */
       
  1740 	for (type = 0; type < OP_MAX; type++)
       
  1741 		{
       
  1742 		if (pk11_free_session_list(type) == 0)
       
  1743 			ret = 0;
       
  1744 		}
       
  1745 
       
  1746 	return (ret);
       
  1747 	}
       
  1748 
       
  1749 /*
       
  1750  * Destroy session structures from the linked list specified. Free as many
       
  1751  * sessions as possible but any failure in C_CloseSession() means that we
       
  1752  * return an error on return.
       
  1753  */
       
  1754 static int pk11_free_session_list(PK11_OPTYPE optype)
       
  1755 	{
       
  1756 	CK_RV rv;
       
  1757 	PK11_SESSION *sp = NULL;
       
  1758 	PK11_SESSION *freelist = NULL;
       
  1759 	pid_t mypid = getpid();
       
  1760 	pthread_mutex_t *freelist_lock;
       
  1761 	int ret = 1;
       
  1762 
       
  1763 	switch (optype)
       
  1764 		{
       
  1765 		case OP_RSA:
       
  1766 		case OP_DSA:
       
  1767 		case OP_DH:
       
  1768 		case OP_RAND:
       
  1769 		case OP_DIGEST:
       
  1770 		case OP_CIPHER:
       
  1771 			freelist_lock = session_cache[optype].lock;
       
  1772 			break;
       
  1773 		default:
       
  1774 			PK11err(PK11_F_FREE_ALL_SESSIONS,
       
  1775 				PK11_R_INVALID_OPERATION_TYPE);
       
  1776 			return (0);
       
  1777 		}
       
  1778 
       
  1779 	(void) pthread_mutex_lock(freelist_lock);
       
  1780 	freelist = session_cache[optype].head;
       
  1781 	while ((sp = freelist) != NULL)
       
  1782 		{
       
  1783 		if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
       
  1784 			{
       
  1785 			rv = pFuncList->C_CloseSession(sp->session);
       
  1786 			if (rv != CKR_OK)
       
  1787 				{
       
  1788 				PK11err_add_data(PK11_F_FREE_ALL_SESSIONS,
       
  1789 					PK11_R_CLOSESESSION, rv);
       
  1790 				ret = 0;
       
  1791 				}
       
  1792 			}
       
  1793 		freelist = sp->next;
       
  1794 		pk11_free_nums(sp, optype);
       
  1795 		OPENSSL_free(sp);
       
  1796 		}
       
  1797 
       
  1798 	(void) pthread_mutex_unlock(freelist_lock);
       
  1799 	return (ret);
       
  1800 	}
       
  1801 
       
  1802 
       
  1803 static int
       
  1804 pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype)
       
  1805 	{
       
  1806 	CK_RV rv;
       
  1807 	CK_SLOT_ID myslot;
       
  1808 
       
  1809 	switch (optype)
       
  1810 		{
       
  1811 		case OP_RSA:
       
  1812 		case OP_DSA:
       
  1813 		case OP_DH:
       
  1814 			myslot = pubkey_SLOTID;
       
  1815 			break;
       
  1816 		case OP_RAND:
       
  1817 			myslot = rand_SLOTID;
       
  1818 			break;
       
  1819 		case OP_DIGEST:
       
  1820 		case OP_CIPHER:
       
  1821 			myslot = SLOTID;
       
  1822 			break;
       
  1823 		default:
       
  1824 			PK11err(PK11_F_SETUP_SESSION,
       
  1825 			    PK11_R_INVALID_OPERATION_TYPE);
       
  1826 			return (0);
       
  1827 		}
       
  1828 
       
  1829 	sp->session = CK_INVALID_HANDLE;
       
  1830 	DEBUG_SLOT_SEL("%s: myslot=%d optype=%d\n", PK11_DBG, myslot, optype);
       
  1831 	rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
       
  1832 		NULL_PTR, NULL_PTR, &sp->session);
       
  1833 	if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
       
  1834 		{
       
  1835 		/*
       
  1836 		 * We are probably a child process so force the
       
  1837 		 * reinitialize of the session
       
  1838 		 */
       
  1839 		pk11_library_initialized = CK_FALSE;
       
  1840 		if (!pk11_library_init(NULL))
       
  1841 			return (0);
       
  1842 		rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
       
  1843 			NULL_PTR, NULL_PTR, &sp->session);
       
  1844 		}
       
  1845 	if (rv != CKR_OK)
       
  1846 		{
       
  1847 		PK11err_add_data(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION, rv);
       
  1848 		return (0);
       
  1849 		}
       
  1850 
       
  1851 	sp->pid = getpid();
       
  1852 
       
  1853 	switch (optype)
       
  1854 		{
       
  1855 #ifndef OPENSSL_NO_RSA
       
  1856 		case OP_RSA:
       
  1857 			sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
       
  1858 			sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
       
  1859 			sp->opdata_rsa_pub = NULL;
       
  1860 			sp->opdata_rsa_n_num = NULL;
       
  1861 			sp->opdata_rsa_e_num = NULL;
       
  1862 			sp->opdata_rsa_priv = NULL;
       
  1863 			sp->opdata_rsa_d_num = NULL;
       
  1864 			break;
       
  1865 #endif	/* OPENSSL_NO_RSA */
       
  1866 #ifndef OPENSSL_NO_DSA
       
  1867 		case OP_DSA:
       
  1868 			sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
       
  1869 			sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
       
  1870 			sp->opdata_dsa_pub = NULL;
       
  1871 			sp->opdata_dsa_pub_num = NULL;
       
  1872 			sp->opdata_dsa_priv = NULL;
       
  1873 			sp->opdata_dsa_priv_num = NULL;
       
  1874 			break;
       
  1875 #endif	/* OPENSSL_NO_DSA */
       
  1876 #ifndef OPENSSL_NO_DH
       
  1877 		case OP_DH:
       
  1878 			sp->opdata_dh_key = CK_INVALID_HANDLE;
       
  1879 			sp->opdata_dh = NULL;
       
  1880 			sp->opdata_dh_priv_num = NULL;
       
  1881 			break;
       
  1882 #endif	/* OPENSSL_NO_DH */
       
  1883 		case OP_CIPHER:
       
  1884 			sp->opdata_cipher_key = CK_INVALID_HANDLE;
       
  1885 			sp->opdata_encrypt = -1;
       
  1886 			break;
       
  1887 		}
       
  1888 
       
  1889 	/*
       
  1890 	 * We always initialize the session as containing a non-persistent
       
  1891 	 * object. The key load functions set it to persistent if that is so.
       
  1892 	 */
       
  1893 	sp->persistent = CK_FALSE;
       
  1894 	return (1);
       
  1895 	}
       
  1896 
       
  1897 #ifndef OPENSSL_NO_RSA
       
  1898 /*
       
  1899  * Destroy all non-NULL RSA parameters. For the RSA keys by reference code,
       
  1900  * public components 'n'/'e' are the key components we use to check for the
       
  1901  * cache hit even for the private keys. So, no matter whether we are destroying
       
  1902  * a public or a private key, we always free what we can.
       
  1903  */
       
  1904 static void
       
  1905 destroy_all_rsa_params(PK11_SESSION *sp)
       
  1906 	{
       
  1907 	if (sp->opdata_rsa_n_num != NULL)
       
  1908 		{
       
  1909 		BN_free(sp->opdata_rsa_n_num);
       
  1910 		sp->opdata_rsa_n_num = NULL;
       
  1911 		}
       
  1912 	if (sp->opdata_rsa_e_num != NULL)
       
  1913 		{
       
  1914 		BN_free(sp->opdata_rsa_e_num);
       
  1915 		sp->opdata_rsa_e_num = NULL;
       
  1916 		}
       
  1917 	if (sp->opdata_rsa_d_num != NULL)
       
  1918 		{
       
  1919 		BN_free(sp->opdata_rsa_d_num);
       
  1920 		sp->opdata_rsa_d_num = NULL;
       
  1921 		}
       
  1922 	}
       
  1923 
       
  1924 /* Destroy RSA public key from single session. */
       
  1925 int
       
  1926 pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
       
  1927 	{
       
  1928 	int ret = 0;
       
  1929 
       
  1930 	if (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE)
       
  1931 		{
       
  1932 		TRY_OBJ_DESTROY(sp, sp->opdata_rsa_pub_key,
       
  1933 		    ret, uselock, OP_RSA);
       
  1934 		sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
       
  1935 		sp->opdata_rsa_pub = NULL;
       
  1936 		destroy_all_rsa_params(sp);
       
  1937 		}
       
  1938 
       
  1939 	return (ret);
       
  1940 	}
       
  1941 
       
  1942 /* Destroy RSA private key from single session. */
       
  1943 int
       
  1944 pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
       
  1945 	{
       
  1946 	int ret = 0;
       
  1947 
       
  1948 	if (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE)
       
  1949 		{
       
  1950 		TRY_OBJ_DESTROY(sp, sp->opdata_rsa_priv_key,
       
  1951 		    ret, uselock, OP_RSA);
       
  1952 		sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
       
  1953 		sp->opdata_rsa_priv = NULL;
       
  1954 		destroy_all_rsa_params(sp);
       
  1955 		}
       
  1956 
       
  1957 	return (ret);
       
  1958 	}
       
  1959 
       
  1960 /*
       
  1961  * Destroy RSA key object wrapper. If session is NULL, try to destroy all
       
  1962  * objects in the free list.
       
  1963  */
       
  1964 int
       
  1965 pk11_destroy_rsa_key_objects(PK11_SESSION *session)
       
  1966 	{
       
  1967 	int ret = 1;
       
  1968 	PK11_SESSION *sp = NULL;
       
  1969 	PK11_SESSION *local_free_session;
       
  1970 	CK_BBOOL uselock = CK_TRUE;
       
  1971 
       
  1972 	if (session != NULL)
       
  1973 		local_free_session = session;
       
  1974 	else
       
  1975 		{
       
  1976 		(void) pthread_mutex_lock(session_cache[OP_RSA].lock);
       
  1977 		local_free_session = session_cache[OP_RSA].head;
       
  1978 		uselock = CK_FALSE;
       
  1979 		}
       
  1980 
       
  1981 	/*
       
  1982 	 * go through the list of sessions and delete key objects
       
  1983 	 */
       
  1984 	while ((sp = local_free_session) != NULL)
       
  1985 		{
       
  1986 		local_free_session = sp->next;
       
  1987 
       
  1988 		/*
       
  1989 		 * Do not terminate list traversal if one of the
       
  1990 		 * destroy operations fails.
       
  1991 		 */
       
  1992 		if (pk11_destroy_rsa_object_pub(sp, uselock) == 0)
       
  1993 			{
       
  1994 			ret = 0;
       
  1995 			continue;
       
  1996 			}
       
  1997 		if (pk11_destroy_rsa_object_priv(sp, uselock) == 0)
       
  1998 			{
       
  1999 			ret = 0;
       
  2000 			continue;
       
  2001 			}
       
  2002 		}
       
  2003 
       
  2004 	if (session == NULL)
       
  2005 		(void) pthread_mutex_unlock(session_cache[OP_RSA].lock);
       
  2006 
       
  2007 	return (ret);
       
  2008 	}
       
  2009 #endif	/* OPENSSL_NO_RSA */
       
  2010 
       
  2011 #ifndef OPENSSL_NO_DSA
       
  2012 /* Destroy DSA public key from single session. */
       
  2013 int
       
  2014 pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
       
  2015 	{
       
  2016 	int ret = 0;
       
  2017 
       
  2018 	if (sp->opdata_dsa_pub_key != CK_INVALID_HANDLE)
       
  2019 		{
       
  2020 		TRY_OBJ_DESTROY(sp, sp->opdata_dsa_pub_key,
       
  2021 		    ret, uselock, OP_DSA);
       
  2022 		sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
       
  2023 		sp->opdata_dsa_pub = NULL;
       
  2024 		if (sp->opdata_dsa_pub_num != NULL)
       
  2025 			{
       
  2026 			BN_free(sp->opdata_dsa_pub_num);
       
  2027 			sp->opdata_dsa_pub_num = NULL;
       
  2028 			}
       
  2029 		}
       
  2030 
       
  2031 	return (ret);
       
  2032 	}
       
  2033 
       
  2034 /* Destroy DSA private key from single session. */
       
  2035 int
       
  2036 pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
       
  2037 	{
       
  2038 	int ret = 0;
       
  2039 
       
  2040 	if (sp->opdata_dsa_priv_key != CK_INVALID_HANDLE)
       
  2041 		{
       
  2042 		TRY_OBJ_DESTROY(sp, sp->opdata_dsa_priv_key,
       
  2043 		    ret, uselock, OP_DSA);
       
  2044 		sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
       
  2045 		sp->opdata_dsa_priv = NULL;
       
  2046 		if (sp->opdata_dsa_priv_num != NULL)
       
  2047 			{
       
  2048 			BN_free(sp->opdata_dsa_priv_num);
       
  2049 			sp->opdata_dsa_priv_num = NULL;
       
  2050 			}
       
  2051 		}
       
  2052 
       
  2053 	return (ret);
       
  2054 	}
       
  2055 
       
  2056 /*
       
  2057  * Destroy DSA key object wrapper. If session is NULL, try to destroy all
       
  2058  * objects in the free list.
       
  2059  */
       
  2060 int
       
  2061 pk11_destroy_dsa_key_objects(PK11_SESSION *session)
       
  2062 	{
       
  2063 	int ret = 1;
       
  2064 	PK11_SESSION *sp = NULL;
       
  2065 	PK11_SESSION *local_free_session;
       
  2066 	CK_BBOOL uselock = CK_TRUE;
       
  2067 
       
  2068 	if (session != NULL)
       
  2069 		local_free_session = session;
       
  2070 	else
       
  2071 		{
       
  2072 		(void) pthread_mutex_lock(session_cache[OP_DSA].lock);
       
  2073 		local_free_session = session_cache[OP_DSA].head;
       
  2074 		uselock = CK_FALSE;
       
  2075 		}
       
  2076 
       
  2077 	/*
       
  2078 	 * go through the list of sessions and delete key objects
       
  2079 	 */
       
  2080 	while ((sp = local_free_session) != NULL)
       
  2081 		{
       
  2082 		local_free_session = sp->next;
       
  2083 
       
  2084 		/*
       
  2085 		 * Do not terminate list traversal if one of the
       
  2086 		 * destroy operations fails.
       
  2087 		 */
       
  2088 		if (pk11_destroy_dsa_object_pub(sp, uselock) == 0)
       
  2089 			{
       
  2090 			ret = 0;
       
  2091 			continue;
       
  2092 			}
       
  2093 		if (pk11_destroy_dsa_object_priv(sp, uselock) == 0)
       
  2094 			{
       
  2095 			ret = 0;
       
  2096 			continue;
       
  2097 			}
       
  2098 		}
       
  2099 
       
  2100 	if (session == NULL)
       
  2101 		(void) pthread_mutex_unlock(session_cache[OP_DSA].lock);
       
  2102 
       
  2103 	return (ret);
       
  2104 	}
       
  2105 #endif	/* OPENSSL_NO_DSA */
       
  2106 
       
  2107 #ifndef OPENSSL_NO_DH
       
  2108 /* Destroy DH key from single session. */
       
  2109 int
       
  2110 pk11_destroy_dh_object(PK11_SESSION *sp, CK_BBOOL uselock)
       
  2111 	{
       
  2112 	int ret = 0;
       
  2113 
       
  2114 	if (sp->opdata_dh_key != CK_INVALID_HANDLE)
       
  2115 		{
       
  2116 		TRY_OBJ_DESTROY(sp, sp->opdata_dh_key,
       
  2117 		    ret, uselock, OP_DH);
       
  2118 		sp->opdata_dh_key = CK_INVALID_HANDLE;
       
  2119 		sp->opdata_dh = NULL;
       
  2120 		if (sp->opdata_dh_priv_num != NULL)
       
  2121 			{
       
  2122 			BN_free(sp->opdata_dh_priv_num);
       
  2123 			sp->opdata_dh_priv_num = NULL;
       
  2124 			}
       
  2125 		}
       
  2126 
       
  2127 	return (ret);
       
  2128 	}
       
  2129 
       
  2130 /*
       
  2131  * Destroy DH key object wrapper.
       
  2132  *
       
  2133  * arg0: pointer to PKCS#11 engine session structure
       
  2134  *       if session is NULL, try to destroy all objects in the free list
       
  2135  */
       
  2136 int
       
  2137 pk11_destroy_dh_key_objects(PK11_SESSION *session)
       
  2138 	{
       
  2139 	int ret = 1;
       
  2140 	PK11_SESSION *sp = NULL;
       
  2141 	PK11_SESSION *local_free_session;
       
  2142 	CK_BBOOL uselock = CK_TRUE;
       
  2143 
       
  2144 	if (session != NULL)
       
  2145 		local_free_session = session;
       
  2146 	else
       
  2147 		{
       
  2148 		(void) pthread_mutex_lock(session_cache[OP_DH].lock);
       
  2149 		local_free_session = session_cache[OP_DH].head;
       
  2150 		uselock = CK_FALSE;
       
  2151 		}
       
  2152 
       
  2153 	while ((sp = local_free_session) != NULL)
       
  2154 		{
       
  2155 		local_free_session = sp->next;
       
  2156 
       
  2157 		/*
       
  2158 		 * Do not terminate list traversal if one of the
       
  2159 		 * destroy operations fails.
       
  2160 		 */
       
  2161 		if (pk11_destroy_dh_object(sp, uselock) == 0)
       
  2162 			{
       
  2163 			ret = 0;
       
  2164 			continue;
       
  2165 			}
       
  2166 		}
       
  2167 	if (session == NULL)
       
  2168 		(void) pthread_mutex_unlock(session_cache[OP_DH].lock);
       
  2169 
       
  2170 	return (ret);
       
  2171 	}
       
  2172 #endif	/* OPENSSL_NO_DH */
       
  2173 
       
  2174 static int
       
  2175 pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh,
       
  2176     CK_BBOOL persistent)
       
  2177 	{
       
  2178 	CK_RV rv;
       
  2179 
       
  2180 	/*
       
  2181 	 * We never try to destroy persistent objects which are the objects
       
  2182 	 * stored in the keystore. Also, we always use read-only sessions so
       
  2183 	 * C_DestroyObject() would be returning CKR_SESSION_READ_ONLY here.
       
  2184 	 */
       
  2185 	if (persistent == CK_TRUE)
       
  2186 		return (1);
       
  2187 
       
  2188 	rv = pFuncList->C_DestroyObject(session, oh);
       
  2189 	if (rv != CKR_OK)
       
  2190 		{
       
  2191 		PK11err_add_data(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT,
       
  2192 		    rv);
       
  2193 		return (0);
       
  2194 		}
       
  2195 
       
  2196 	return (1);
       
  2197 	}
       
  2198 
       
  2199 
       
  2200 /* Symmetric ciphers and digests support functions */
       
  2201 
       
  2202 static int
       
  2203 cipher_nid_to_pk11(int nid)
       
  2204 	{
       
  2205 	int i;
       
  2206 
       
  2207 	for (i = 0; i < PK11_CIPHER_MAX; i++)
       
  2208 		if (ciphers[i].nid == nid)
       
  2209 			return (ciphers[i].id);
       
  2210 	return (-1);
       
  2211 	}
       
  2212 
       
  2213 static int
       
  2214 pk11_usable_ciphers(const int **nids)
       
  2215 	{
       
  2216 	if (cipher_count > 0)
       
  2217 		*nids = cipher_nids;
       
  2218 	else
       
  2219 		*nids = NULL;
       
  2220 	return (cipher_count);
       
  2221 	}
       
  2222 
       
  2223 static int
       
  2224 pk11_usable_digests(const int **nids)
       
  2225 	{
       
  2226 	if (digest_count > 0)
       
  2227 		*nids = digest_nids;
       
  2228 	else
       
  2229 		*nids = NULL;
       
  2230 	return (digest_count);
       
  2231 	}
       
  2232 
       
  2233 /*
       
  2234  * Init context for encryption or decryption using a symmetric key.
       
  2235  */
       
  2236 static int pk11_init_symmetric(EVP_CIPHER_CTX *ctx, PK11_CIPHER *pcipher,
       
  2237 	PK11_SESSION *sp, CK_MECHANISM_PTR pmech)
       
  2238 	{
       
  2239 	CK_RV rv;
       
  2240 	CK_AES_CTR_PARAMS ctr_params;
       
  2241 
       
  2242 	/*
       
  2243 	 * We expect pmech->mechanism to be already set and
       
  2244 	 * pParameter/ulParameterLen initialized to NULL/0 before
       
  2245 	 * pk11_init_symmetric() is called.
       
  2246 	 */
       
  2247 	OPENSSL_assert(pmech->mechanism != NULL);
       
  2248 	OPENSSL_assert(pmech->pParameter == NULL);
       
  2249 	OPENSSL_assert(pmech->ulParameterLen == 0);
       
  2250 
       
  2251 	if (ctx->cipher->nid == NID_aes_128_ctr ||
       
  2252 	    ctx->cipher->nid == NID_aes_192_ctr ||
       
  2253 	    ctx->cipher->nid == NID_aes_256_ctr)
       
  2254 		{
       
  2255 		pmech->pParameter = (void *)(&ctr_params);
       
  2256 		pmech->ulParameterLen = sizeof (ctr_params);
       
  2257 		/*
       
  2258 		 * For now, we are limited to the fixed length of the counter,
       
  2259 		 * it covers the whole counter block. That's what RFC 4344
       
  2260 		 * needs. For more information on internal structure of the
       
  2261 		 * counter block, see RFC 3686. If needed in the future, we can
       
  2262 		 * add code so that the counter length can be set via
       
  2263 		 * ENGINE_ctrl() function.
       
  2264 		 */
       
  2265 		ctr_params.ulCounterBits = AES_BLOCK_SIZE * 8;
       
  2266 		OPENSSL_assert(pcipher->iv_len == AES_BLOCK_SIZE);
       
  2267 		(void) memcpy(ctr_params.cb, ctx->iv, AES_BLOCK_SIZE);
       
  2268 		}
       
  2269 	else
       
  2270 		{
       
  2271 		if (pcipher->iv_len > 0)
       
  2272 			{
       
  2273 			pmech->pParameter = (void *)ctx->iv;
       
  2274 			pmech->ulParameterLen = pcipher->iv_len;
       
  2275 			}
       
  2276 		}
       
  2277 
       
  2278 	/* if we get here, the encryption needs to be reinitialized */
       
  2279 	if (ctx->encrypt)
       
  2280 		rv = pFuncList->C_EncryptInit(sp->session, pmech,
       
  2281 			sp->opdata_cipher_key);
       
  2282 	else
       
  2283 		rv = pFuncList->C_DecryptInit(sp->session, pmech,
       
  2284 			sp->opdata_cipher_key);
       
  2285 
       
  2286 	if (rv != CKR_OK)
       
  2287 		{
       
  2288 		PK11err_add_data(PK11_F_CIPHER_INIT, ctx->encrypt ?
       
  2289 		    PK11_R_ENCRYPTINIT : PK11_R_DECRYPTINIT, rv);
       
  2290 		pk11_return_session(sp, OP_CIPHER);
       
  2291 		return (0);
       
  2292 		}
       
  2293 
       
  2294 	return (1);
       
  2295 	}
       
  2296 
       
  2297 /* ARGSUSED */
       
  2298 static int
       
  2299 pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
       
  2300     const unsigned char *iv, int enc)
       
  2301 	{
       
  2302 	CK_MECHANISM mech;
       
  2303 	int index;
       
  2304 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
       
  2305 	PK11_SESSION *sp;
       
  2306 	PK11_CIPHER *p_ciph_table_row;
       
  2307 
       
  2308 	state->sp = NULL;
       
  2309 
       
  2310 	index = cipher_nid_to_pk11(ctx->cipher->nid);
       
  2311 	if (index < 0 || index >= PK11_CIPHER_MAX)
       
  2312 		return (0);
       
  2313 
       
  2314 	p_ciph_table_row = &ciphers[index];
       
  2315 	/*
       
  2316 	 * iv_len in the ctx->cipher structure is the maximum IV length for the
       
  2317 	 * current cipher and it must be less or equal to the IV length in our
       
  2318 	 * ciphers table. The key length must be in the allowed interval. From
       
  2319 	 * all cipher modes that the PKCS#11 engine supports only RC4 allows a
       
  2320 	 * key length to be in some range, all other NIDs have a precise key
       
  2321 	 * length. Every application can define its own EVP functions so this
       
  2322 	 * code serves as a sanity check.
       
  2323 	 *
       
  2324 	 * Note that the reason why the IV length in ctx->cipher might be
       
  2325 	 * greater than the actual length is that OpenSSL uses BLOCK_CIPHER_defs
       
  2326 	 * macro to define functions that return EVP structures for all DES
       
  2327 	 * modes. So, even ECB modes get 8 byte IV.
       
  2328 	 */
       
  2329 	if (ctx->cipher->iv_len < p_ciph_table_row->iv_len ||
       
  2330 	    ctx->key_len < p_ciph_table_row->min_key_len ||
       
  2331 	    ctx->key_len > p_ciph_table_row->max_key_len) {
       
  2332 		PK11err(PK11_F_CIPHER_INIT, PK11_R_KEY_OR_IV_LEN_PROBLEM);
       
  2333 		return (0);
       
  2334 	}
       
  2335 
       
  2336 	if ((sp = pk11_get_session(OP_CIPHER)) == NULL)
       
  2337 		return (0);
       
  2338 
       
  2339 	/* if applicable, the mechanism parameter is used for IV */
       
  2340 	mech.mechanism = p_ciph_table_row->mech_type;
       
  2341 	mech.pParameter = NULL;
       
  2342 	mech.ulParameterLen = 0;
       
  2343 
       
  2344 	/* The key object is destroyed here if it is not the current key. */
       
  2345 	(void) check_new_cipher_key(sp, key, ctx->key_len);
       
  2346 
       
  2347 	/*
       
  2348 	 * If the key is the same and the encryption is also the same, then
       
  2349 	 * just reuse it. However, we must not forget to reinitialize the
       
  2350 	 * context that was finalized in pk11_cipher_cleanup().
       
  2351 	 */
       
  2352 	if (sp->opdata_cipher_key != CK_INVALID_HANDLE &&
       
  2353 	    sp->opdata_encrypt == ctx->encrypt)
       
  2354 		{
       
  2355 		state->sp = sp;
       
  2356 		if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
       
  2357 			return (0);
       
  2358 
       
  2359 		return (1);
       
  2360 		}
       
  2361 
       
  2362 	/*
       
  2363 	 * Check if the key has been invalidated. If so, a new key object
       
  2364 	 * needs to be created.
       
  2365 	 */
       
  2366 	if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
       
  2367 		{
       
  2368 		sp->opdata_cipher_key = pk11_get_cipher_key(
       
  2369 			ctx, key, p_ciph_table_row->key_type, sp);
       
  2370 		}
       
  2371 
       
  2372 	if (sp->opdata_encrypt != ctx->encrypt && sp->opdata_encrypt != -1)
       
  2373 		{
       
  2374 		/*
       
  2375 		 * The previous encryption/decryption is different. Need to
       
  2376 		 * terminate the previous * active encryption/decryption here.
       
  2377 		 */
       
  2378 		if (!pk11_cipher_final(sp))
       
  2379 			{
       
  2380 			pk11_return_session(sp, OP_CIPHER);
       
  2381 			return (0);
       
  2382 			}
       
  2383 		}
       
  2384 
       
  2385 	if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
       
  2386 		{
       
  2387 		pk11_return_session(sp, OP_CIPHER);
       
  2388 		return (0);
       
  2389 		}
       
  2390 
       
  2391 	/* now initialize the context with a new key */
       
  2392 	if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
       
  2393 		return (0);
       
  2394 
       
  2395 	sp->opdata_encrypt = ctx->encrypt;
       
  2396 	state->sp = sp;
       
  2397 
       
  2398 	return (1);
       
  2399 	}
       
  2400 
       
  2401 /*
       
  2402  * When reusing the same key in an encryption/decryption session for a
       
  2403  * decryption/encryption session, we need to close the active session
       
  2404  * and recreate a new one. Note that the key is in the global session so
       
  2405  * that it needs not be recreated.
       
  2406  *
       
  2407  * It is more appropriate to use C_En/DecryptFinish here. At the time of this
       
  2408  * development, these two functions in the PKCS#11 libraries used return
       
  2409  * unexpected errors when passing in 0 length output. It may be a good
       
  2410  * idea to try them again if performance is a problem here and fix
       
  2411  * C_En/DecryptFinial if there are bugs there causing the problem.
       
  2412  */
       
  2413 static int
       
  2414 pk11_cipher_final(PK11_SESSION *sp)
       
  2415 	{
       
  2416 	CK_RV rv;
       
  2417 
       
  2418 	rv = pFuncList->C_CloseSession(sp->session);
       
  2419 	if (rv != CKR_OK)
       
  2420 		{
       
  2421 		PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_CLOSESESSION, rv);
       
  2422 		return (0);
       
  2423 		}
       
  2424 
       
  2425 	rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
       
  2426 		NULL_PTR, NULL_PTR, &sp->session);
       
  2427 	if (rv != CKR_OK)
       
  2428 		{
       
  2429 		PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_OPENSESSION, rv);
       
  2430 		return (0);
       
  2431 		}
       
  2432 
       
  2433 	return (1);
       
  2434 	}
       
  2435 
       
  2436 /*
       
  2437  * An engine interface function. The calling function allocates sufficient
       
  2438  * memory for the output buffer "out" to hold the results.
       
  2439  */
       
  2440 static int
       
  2441 pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
       
  2442 	const unsigned char *in, size_t inl)
       
  2443 	{
       
  2444 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
       
  2445 	PK11_SESSION *sp;
       
  2446 	CK_RV rv;
       
  2447 	unsigned long outl = inl;
       
  2448 
       
  2449 	if (state == NULL || state->sp == NULL)
       
  2450 		return (0);
       
  2451 
       
  2452 	sp = (PK11_SESSION *) state->sp;
       
  2453 
       
  2454 	if (!inl)
       
  2455 		return (1);
       
  2456 
       
  2457 	/* RC4 is the only stream cipher we support */
       
  2458 	if (ctx->cipher->nid != NID_rc4 && (inl % ctx->cipher->block_size) != 0)
       
  2459 		return (0);
       
  2460 
       
  2461 	if (ctx->encrypt)
       
  2462 		{
       
  2463 		rv = pFuncList->C_EncryptUpdate(sp->session,
       
  2464 			(unsigned char *)in, inl, out, &outl);
       
  2465 
       
  2466 		if (rv != CKR_OK)
       
  2467 			{
       
  2468 			PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
       
  2469 			    PK11_R_ENCRYPTUPDATE, rv);
       
  2470 			return (0);
       
  2471 			}
       
  2472 		}
       
  2473 	else
       
  2474 		{
       
  2475 		rv = pFuncList->C_DecryptUpdate(sp->session,
       
  2476 			(unsigned char *)in, inl, out, &outl);
       
  2477 
       
  2478 		if (rv != CKR_OK)
       
  2479 			{
       
  2480 			PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
       
  2481 			    PK11_R_DECRYPTUPDATE, rv);
       
  2482 			return (0);
       
  2483 			}
       
  2484 		}
       
  2485 
       
  2486 	/*
       
  2487 	 * For DES_CBC, DES3_CBC, AES_CBC, and RC4, the output size is always
       
  2488 	 * the same size of input.
       
  2489 	 * The application has guaranteed to call the block ciphers with
       
  2490 	 * correctly aligned buffers.
       
  2491 	 */
       
  2492 	if (inl != outl)
       
  2493 		return (0);
       
  2494 
       
  2495 	return (1);
       
  2496 	}
       
  2497 
       
  2498 /*
       
  2499  * Return the session to the pool. Calling C_EncryptFinal() and C_DecryptFinal()
       
  2500  * here is the right thing because in EVP_DecryptFinal_ex(), engine's
       
  2501  * do_cipher() is not even called, and in EVP_EncryptFinal_ex() it is called but
       
  2502  * the engine can't find out that it's the finalizing call. We wouldn't
       
  2503  * necessarily have to finalize the context here since reinitializing it with
       
  2504  * C_(Encrypt|Decrypt)Init() should be fine but for the sake of correctness,
       
  2505  * let's do it. Some implementations might leak memory if the previously used
       
  2506  * context is initialized without finalizing it first.
       
  2507  */
       
  2508 static int
       
  2509 pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx)
       
  2510 	{
       
  2511 	CK_RV rv;
       
  2512 	CK_ULONG len = EVP_MAX_BLOCK_LENGTH;
       
  2513 	CK_BYTE buf[EVP_MAX_BLOCK_LENGTH];
       
  2514 	PK11_CIPHER_STATE *state = ctx->cipher_data;
       
  2515 
       
  2516 	if (state != NULL && state->sp != NULL)
       
  2517 		{
       
  2518 		/*
       
  2519 		 * We are not interested in the data here, we just need to get
       
  2520 		 * rid of the context.
       
  2521 		 */
       
  2522 		if (ctx->encrypt)
       
  2523 			rv = pFuncList->C_EncryptFinal(
       
  2524 			    state->sp->session, buf, &len);
       
  2525 		else
       
  2526 			rv = pFuncList->C_DecryptFinal(
       
  2527 			    state->sp->session, buf, &len);
       
  2528 
       
  2529 		if (rv != CKR_OK)
       
  2530 			{
       
  2531 			PK11err_add_data(PK11_F_CIPHER_CLEANUP, ctx->encrypt ?
       
  2532 			    PK11_R_ENCRYPTFINAL : PK11_R_DECRYPTFINAL, rv);
       
  2533 			pk11_return_session(state->sp, OP_CIPHER);
       
  2534 			return (0);
       
  2535 			}
       
  2536 
       
  2537 		pk11_return_session(state->sp, OP_CIPHER);
       
  2538 		state->sp = NULL;
       
  2539 		}
       
  2540 
       
  2541 	return (1);
       
  2542 	}
       
  2543 
       
  2544 /*
       
  2545  * Registered by the ENGINE when used to find out how to deal with
       
  2546  * a particular NID in the ENGINE. This says what we'll do at the
       
  2547  * top level - note, that list is restricted by what we answer with
       
  2548  */
       
  2549 /* ARGSUSED */
       
  2550 static int
       
  2551 pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
       
  2552 	const int **nids, int nid)
       
  2553 	{
       
  2554 	if (!cipher)
       
  2555 		return (pk11_usable_ciphers(nids));
       
  2556 
       
  2557 	switch (nid)
       
  2558 		{
       
  2559 		case NID_des_ede3_cbc:
       
  2560 			*cipher = &pk11_3des_cbc;
       
  2561 			break;
       
  2562 		case NID_des_cbc:
       
  2563 			*cipher = &pk11_des_cbc;
       
  2564 			break;
       
  2565 		case NID_des_ede3_ecb:
       
  2566 			*cipher = &pk11_3des_ecb;
       
  2567 			break;
       
  2568 		case NID_des_ecb:
       
  2569 			*cipher = &pk11_des_ecb;
       
  2570 			break;
       
  2571 		case NID_aes_128_cbc:
       
  2572 			*cipher = &pk11_aes_128_cbc;
       
  2573 			break;
       
  2574 		case NID_aes_192_cbc:
       
  2575 			*cipher = &pk11_aes_192_cbc;
       
  2576 			break;
       
  2577 		case NID_aes_256_cbc:
       
  2578 			*cipher = &pk11_aes_256_cbc;
       
  2579 			break;
       
  2580 		case NID_aes_128_ecb:
       
  2581 			*cipher = &pk11_aes_128_ecb;
       
  2582 			break;
       
  2583 		case NID_aes_192_ecb:
       
  2584 			*cipher = &pk11_aes_192_ecb;
       
  2585 			break;
       
  2586 		case NID_aes_256_ecb:
       
  2587 			*cipher = &pk11_aes_256_ecb;
       
  2588 			break;
       
  2589 		case NID_aes_128_ctr:
       
  2590 			*cipher = &pk11_aes_128_ctr;
       
  2591 			break;
       
  2592 		case NID_aes_192_ctr:
       
  2593 			*cipher = &pk11_aes_192_ctr;
       
  2594 			break;
       
  2595 		case NID_aes_256_ctr:
       
  2596 			*cipher = &pk11_aes_256_ctr;
       
  2597 			break;
       
  2598 		case NID_bf_cbc:
       
  2599 			*cipher = &pk11_bf_cbc;
       
  2600 			break;
       
  2601 		case NID_rc4:
       
  2602 			*cipher = &pk11_rc4;
       
  2603 			break;
       
  2604 		default:
       
  2605 			*cipher = NULL;
       
  2606 			break;
       
  2607 		}
       
  2608 	return (*cipher != NULL);
       
  2609 	}
       
  2610 
       
  2611 /* ARGSUSED */
       
  2612 static int
       
  2613 pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
       
  2614 	const int **nids, int nid)
       
  2615 	{
       
  2616 	if (!digest)
       
  2617 		return (pk11_usable_digests(nids));
       
  2618 
       
  2619 	switch (nid)
       
  2620 		{
       
  2621 		case NID_md5:
       
  2622 			*digest = &pk11_md5;
       
  2623 			break;
       
  2624 		/*
       
  2625 		 * A special case. For "openssl dgst -dss1 -engine pkcs11 ...",
       
  2626 		 * OpenSSL calls EVP_get_digestbyname() on "dss1" which ends up
       
  2627 		 * calling pk11_engine_digests() for NID_dsa. Internally, if an
       
  2628 		 * engine is not used, OpenSSL uses SHA1_Init() as expected for
       
  2629 		 * DSA. So, we must return pk11_sha1() for NID_dsa as well. Note
       
  2630 		 * that this must have changed between 0.9.8 and 1.0.0 since we
       
  2631 		 * did not have the problem with the 0.9.8 version.
       
  2632 		 */
       
  2633 		case NID_sha1:
       
  2634 		case NID_dsa:
       
  2635 			*digest = &pk11_sha1;
       
  2636 			break;
       
  2637 		case NID_sha224:
       
  2638 			*digest = &pk11_sha224;
       
  2639 			break;
       
  2640 		case NID_sha256:
       
  2641 			*digest = &pk11_sha256;
       
  2642 			break;
       
  2643 		case NID_sha384:
       
  2644 			*digest = &pk11_sha384;
       
  2645 			break;
       
  2646 		case NID_sha512:
       
  2647 			*digest = &pk11_sha512;
       
  2648 			break;
       
  2649 		default:
       
  2650 			*digest = NULL;
       
  2651 			break;
       
  2652 		}
       
  2653 	return (*digest != NULL);
       
  2654 	}
       
  2655 
       
  2656 
       
  2657 /* Create a secret key object in a PKCS#11 session */
       
  2658 static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
       
  2659 	const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp)
       
  2660 	{
       
  2661 	CK_RV rv;
       
  2662 	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
       
  2663 	CK_OBJECT_CLASS obj_key = CKO_SECRET_KEY;
       
  2664 	CK_ULONG ul_key_attr_count = 6;
       
  2665 
       
  2666 	CK_ATTRIBUTE  a_key_template[] =
       
  2667 		{
       
  2668 		{CKA_CLASS, (void*) NULL, sizeof (CK_OBJECT_CLASS)},
       
  2669 		{CKA_KEY_TYPE, (void*) NULL, sizeof (CK_KEY_TYPE)},
       
  2670 		{CKA_TOKEN, &pk11_false, sizeof (pk11_false)},
       
  2671 		{CKA_ENCRYPT, &pk11_true, sizeof (pk11_true)},
       
  2672 		{CKA_DECRYPT, &pk11_true, sizeof (pk11_true)},
       
  2673 		{CKA_VALUE, (void*) NULL, 0},
       
  2674 		};
       
  2675 
       
  2676 	/*
       
  2677 	 * Create secret key object in global_session. All other sessions
       
  2678 	 * can use the key handles. Here is why:
       
  2679 	 * OpenSSL will call EncryptInit and EncryptUpdate using a secret key.
       
  2680 	 * It may then call DecryptInit and DecryptUpdate using the same key.
       
  2681 	 * To use the same key object, we need to call EncryptFinal with
       
  2682 	 * a 0 length message. Currently, this does not work for 3DES
       
  2683 	 * mechanism. To get around this problem, we close the session and
       
  2684 	 * then create a new session to use the same key object. When a session
       
  2685 	 * is closed, all the object handles will be invalid. Thus, create key
       
  2686 	 * objects in a global session, an individual session may be closed to
       
  2687 	 * terminate the active operation.
       
  2688 	 */
       
  2689 	CK_SESSION_HANDLE session = global_session;
       
  2690 	a_key_template[0].pValue = &obj_key;
       
  2691 	a_key_template[1].pValue = &key_type;
       
  2692 	a_key_template[5].pValue = (void *) key;
       
  2693 	a_key_template[5].ulValueLen = (unsigned long) ctx->key_len;
       
  2694 
       
  2695 	rv = pFuncList->C_CreateObject(session,
       
  2696 		a_key_template, ul_key_attr_count, &h_key);
       
  2697 	if (rv != CKR_OK)
       
  2698 		{
       
  2699 		PK11err_add_data(PK11_F_GET_CIPHER_KEY, PK11_R_CREATEOBJECT,
       
  2700 		    rv);
       
  2701 		goto err;
       
  2702 		}
       
  2703 
       
  2704 	/*
       
  2705 	 * Save the key information used in this session.
       
  2706 	 * The max can be saved is PK11_KEY_LEN_MAX.
       
  2707 	 */
       
  2708 	sp->opdata_key_len = ctx->key_len > PK11_KEY_LEN_MAX ?
       
  2709 		PK11_KEY_LEN_MAX : ctx->key_len;
       
  2710 	(void) memcpy(sp->opdata_key, key, sp->opdata_key_len);
       
  2711 err:
       
  2712 
       
  2713 	return (h_key);
       
  2714 	}
       
  2715 
       
  2716 static int
       
  2717 md_nid_to_pk11(int nid)
       
  2718 	{
       
  2719 	int i;
       
  2720 
       
  2721 	for (i = 0; i < PK11_DIGEST_MAX; i++)
       
  2722 		if (digests[i].nid == nid)
       
  2723 			return (digests[i].id);
       
  2724 	return (-1);
       
  2725 	}
       
  2726 
       
  2727 static int
       
  2728 pk11_digest_init(EVP_MD_CTX *ctx)
       
  2729 	{
       
  2730 	CK_RV rv;
       
  2731 	CK_MECHANISM mech;
       
  2732 	int index;
       
  2733 	PK11_SESSION *sp;
       
  2734 	PK11_DIGEST *pdp;
       
  2735 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
       
  2736 
       
  2737 	state->sp = NULL;
       
  2738 
       
  2739 	index = md_nid_to_pk11(ctx->digest->type);
       
  2740 	if (index < 0 || index >= PK11_DIGEST_MAX)
       
  2741 		return (0);
       
  2742 
       
  2743 	pdp = &digests[index];
       
  2744 	if ((sp = pk11_get_session(OP_DIGEST)) == NULL)
       
  2745 		return (0);
       
  2746 
       
  2747 	/* at present, no parameter is needed for supported digests */
       
  2748 	mech.mechanism = pdp->mech_type;
       
  2749 	mech.pParameter = NULL;
       
  2750 	mech.ulParameterLen = 0;
       
  2751 
       
  2752 	rv = pFuncList->C_DigestInit(sp->session, &mech);
       
  2753 
       
  2754 	if (rv != CKR_OK)
       
  2755 		{
       
  2756 		PK11err_add_data(PK11_F_DIGEST_INIT, PK11_R_DIGESTINIT, rv);
       
  2757 		pk11_return_session(sp, OP_DIGEST);
       
  2758 		return (0);
       
  2759 		}
       
  2760 
       
  2761 	state->sp = sp;
       
  2762 
       
  2763 	return (1);
       
  2764 	}
       
  2765 
       
  2766 static int
       
  2767 pk11_digest_update(EVP_MD_CTX *ctx, const void *data, size_t count)
       
  2768 	{
       
  2769 	CK_RV rv;
       
  2770 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
       
  2771 
       
  2772 	/* 0 length message will cause a failure in C_DigestFinal */
       
  2773 	if (count == 0)
       
  2774 		return (1);
       
  2775 
       
  2776 	if (state == NULL || state->sp == NULL)
       
  2777 		return (0);
       
  2778 
       
  2779 	rv = pFuncList->C_DigestUpdate(state->sp->session, (CK_BYTE *) data,
       
  2780 		count);
       
  2781 
       
  2782 	if (rv != CKR_OK)
       
  2783 		{
       
  2784 		PK11err_add_data(PK11_F_DIGEST_UPDATE, PK11_R_DIGESTUPDATE, rv);
       
  2785 		pk11_return_session(state->sp, OP_DIGEST);
       
  2786 		state->sp = NULL;
       
  2787 		return (0);
       
  2788 		}
       
  2789 
       
  2790 	return (1);
       
  2791 	}
       
  2792 
       
  2793 static int
       
  2794 pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
       
  2795 	{
       
  2796 	CK_RV rv;
       
  2797 	unsigned long len;
       
  2798 	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
       
  2799 	len = ctx->digest->md_size;
       
  2800 
       
  2801 	if (state == NULL || state->sp == NULL)
       
  2802 		return (0);
       
  2803 
       
  2804 	rv = pFuncList->C_DigestFinal(state->sp->session, md, &len);
       
  2805 
       
  2806 	if (rv != CKR_OK)
       
  2807 		{
       
  2808 		PK11err_add_data(PK11_F_DIGEST_FINAL, PK11_R_DIGESTFINAL, rv);
       
  2809 		pk11_return_session(state->sp, OP_DIGEST);
       
  2810 		state->sp = NULL;
       
  2811 		return (0);
       
  2812 		}
       
  2813 
       
  2814 	if (ctx->digest->md_size != len)
       
  2815 		return (0);
       
  2816 
       
  2817 	/*
       
  2818 	 * Final is called and digest is returned, so return the session
       
  2819 	 * to the pool
       
  2820 	 */
       
  2821 	pk11_return_session(state->sp, OP_DIGEST);
       
  2822 	state->sp = NULL;
       
  2823 
       
  2824 	return (1);
       
  2825 	}
       
  2826 
       
  2827 static int
       
  2828 pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
       
  2829 	{
       
  2830 	CK_RV rv;
       
  2831 	int ret = 0;
       
  2832 	PK11_CIPHER_STATE *state, *state_to;
       
  2833 	CK_BYTE_PTR pstate = NULL;
       
  2834 	CK_ULONG ul_state_len;
       
  2835 
       
  2836 	if (from->md_data == NULL || to->digest->ctx_size == 0)
       
  2837 		return (1);
       
  2838 
       
  2839 	/* The copy-from state */
       
  2840 	state = (PK11_CIPHER_STATE *) from->md_data;
       
  2841 	if (state->sp == NULL)
       
  2842 		goto err;
       
  2843 
       
  2844 	/* Initialize the copy-to state */
       
  2845 	if (!pk11_digest_init(to))
       
  2846 		goto err;
       
  2847 	state_to = (PK11_CIPHER_STATE *) to->md_data;
       
  2848 
       
  2849 	/* Get the size of the operation state of the copy-from session */
       
  2850 	rv = pFuncList->C_GetOperationState(state->sp->session, NULL,
       
  2851 		&ul_state_len);
       
  2852 
       
  2853 	if (rv != CKR_OK)
       
  2854 		{
       
  2855 		PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
       
  2856 		    rv);
       
  2857 		goto err;
       
  2858 		}
       
  2859 	if (ul_state_len == 0)
       
  2860 		{
       
  2861 		goto err;
       
  2862 		}
       
  2863 
       
  2864 	pstate = OPENSSL_malloc(ul_state_len);
       
  2865 	if (pstate == NULL)
       
  2866 		{
       
  2867 		PK11err(PK11_F_DIGEST_COPY, PK11_R_MALLOC_FAILURE);
       
  2868 		goto err;
       
  2869 		}
       
  2870 
       
  2871 	/* Get the operation state of the copy-from session */
       
  2872 	rv = pFuncList->C_GetOperationState(state->sp->session, pstate,
       
  2873 		&ul_state_len);
       
  2874 
       
  2875 	if (rv != CKR_OK)
       
  2876 		{
       
  2877 		PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
       
  2878 		    rv);
       
  2879 		goto err;
       
  2880 		}
       
  2881 
       
  2882 	/* Set the operation state of the copy-to session */
       
  2883 	rv = pFuncList->C_SetOperationState(state_to->sp->session, pstate,
       
  2884 		ul_state_len, 0, 0);
       
  2885 
       
  2886 	if (rv != CKR_OK)
       
  2887 		{
       
  2888 		PK11err_add_data(PK11_F_DIGEST_COPY,
       
  2889 		    PK11_R_SET_OPERATION_STATE, rv);
       
  2890 		goto err;
       
  2891 		}
       
  2892 
       
  2893 	ret = 1;
       
  2894 err:
       
  2895 	if (pstate != NULL)
       
  2896 		OPENSSL_free(pstate);
       
  2897 
       
  2898 	return (ret);
       
  2899 	}
       
  2900 
       
  2901 /* Return any pending session state to the pool */
       
  2902 static int
       
  2903 pk11_digest_cleanup(EVP_MD_CTX *ctx)
       
  2904 	{
       
  2905 	PK11_CIPHER_STATE *state = ctx->md_data;
       
  2906 	unsigned char buf[EVP_MAX_MD_SIZE];
       
  2907 
       
  2908 	if (state != NULL && state->sp != NULL)
       
  2909 		{
       
  2910 		/*
       
  2911 		 * If state->sp is not NULL then pk11_digest_final() has not
       
  2912 		 * been called yet. We must call it now to free any memory
       
  2913 		 * that might have been allocated in the token when
       
  2914 		 * pk11_digest_init() was called. pk11_digest_final()
       
  2915 		 * will return the session to the cache.
       
  2916 		 */
       
  2917 		if (!pk11_digest_final(ctx, buf))
       
  2918 			return (0);
       
  2919 		}
       
  2920 
       
  2921 	return (1);
       
  2922 	}
       
  2923 
       
  2924 /*
       
  2925  * Check if the new key is the same as the key object in the session. If the key
       
  2926  * is the same, no need to create a new key object. Otherwise, the old key
       
  2927  * object needs to be destroyed and a new one will be created. Return 1 for
       
  2928  * cache hit, 0 for cache miss. Note that we must check the key length first
       
  2929  * otherwise we could end up reusing a different, longer key with the same
       
  2930  * prefix.
       
  2931  */
       
  2932 static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
       
  2933 	int key_len)
       
  2934 	{
       
  2935 	if (sp->opdata_key_len != key_len ||
       
  2936 	    memcmp(sp->opdata_key, key, key_len) != 0)
       
  2937 		{
       
  2938 		(void) pk11_destroy_cipher_key_objects(sp);
       
  2939 		return (0);
       
  2940 		}
       
  2941 	return (1);
       
  2942 	}
       
  2943 
       
  2944 /* Destroy one or more secret key objects. */
       
  2945 static int pk11_destroy_cipher_key_objects(PK11_SESSION *session)
       
  2946 	{
       
  2947 	int ret = 0;
       
  2948 	PK11_SESSION *sp = NULL;
       
  2949 	PK11_SESSION *local_free_session;
       
  2950 
       
  2951 	if (session != NULL)
       
  2952 		local_free_session = session;
       
  2953 	else
       
  2954 		{
       
  2955 		(void) pthread_mutex_lock(session_cache[OP_CIPHER].lock);
       
  2956 		local_free_session = session_cache[OP_CIPHER].head;
       
  2957 		}
       
  2958 
       
  2959 	while ((sp = local_free_session) != NULL)
       
  2960 		{
       
  2961 		local_free_session = sp->next;
       
  2962 
       
  2963 		if (sp->opdata_cipher_key != CK_INVALID_HANDLE)
       
  2964 			{
       
  2965 			/*
       
  2966 			 * The secret key object is created in the
       
  2967 			 * global_session. See pk11_get_cipher_key().
       
  2968 			 */
       
  2969 			if (pk11_destroy_object(global_session,
       
  2970 				sp->opdata_cipher_key, CK_FALSE) == 0)
       
  2971 				goto err;
       
  2972 			sp->opdata_cipher_key = CK_INVALID_HANDLE;
       
  2973 			}
       
  2974 		}
       
  2975 	ret = 1;
       
  2976 err:
       
  2977 
       
  2978 	if (session == NULL)
       
  2979 		(void) pthread_mutex_unlock(session_cache[OP_CIPHER].lock);
       
  2980 
       
  2981 	return (ret);
       
  2982 	}
       
  2983 
       
  2984 
       
  2985 /*
       
  2986  * Public key mechanisms optionally supported
       
  2987  *
       
  2988  * CKM_RSA_X_509
       
  2989  * CKM_RSA_PKCS
       
  2990  * CKM_DSA
       
  2991  *
       
  2992  * The first slot that supports at least one of those mechanisms is chosen as a
       
  2993  * public key slot.
       
  2994  *
       
  2995  * Symmetric ciphers optionally supported
       
  2996  *
       
  2997  * CKM_DES3_CBC
       
  2998  * CKM_DES_CBC
       
  2999  * CKM_AES_CBC
       
  3000  * CKM_DES3_ECB
       
  3001  * CKM_DES_ECB
       
  3002  * CKM_AES_ECB
       
  3003  * CKM_AES_CTR
       
  3004  * CKM_RC4
       
  3005  * CKM_BLOWFISH_CBC
       
  3006  *
       
  3007  * Digests optionally supported
       
  3008  *
       
  3009  * CKM_MD5
       
  3010  * CKM_SHA_1
       
  3011  * CKM_SHA224
       
  3012  * CKM_SHA256
       
  3013  * CKM_SHA384
       
  3014  * CKM_SHA512
       
  3015  *
       
  3016  * The output of this function is a set of global variables indicating which
       
  3017  * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
       
  3018  * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
       
  3019  * variables carry information about which slot was chosen for (a) public key
       
  3020  * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
       
  3021  */
       
  3022 static int
       
  3023 pk11_choose_slots(int *any_slot_found)
       
  3024 	{
       
  3025 	CK_SLOT_ID_PTR pSlotList = NULL_PTR;
       
  3026 	CK_ULONG ulSlotCount = 0;
       
  3027 	CK_MECHANISM_INFO mech_info;
       
  3028 	CK_TOKEN_INFO token_info;
       
  3029 	int i;
       
  3030 	CK_RV rv;
       
  3031 	CK_SLOT_ID best_slot_sofar;
       
  3032 	CK_BBOOL found_candidate_slot = CK_FALSE;
       
  3033 	int slot_n_cipher = 0;
       
  3034 	int slot_n_digest = 0;
       
  3035 	CK_SLOT_ID current_slot = 0;
       
  3036 	int current_slot_n_cipher = 0;
       
  3037 	int current_slot_n_digest = 0;
       
  3038 
       
  3039 	int local_cipher_nids[PK11_CIPHER_MAX];
       
  3040 	int local_digest_nids[PK11_DIGEST_MAX];
       
  3041 
       
  3042 	/* let's initialize the output parameter */
       
  3043 	if (any_slot_found != NULL)
       
  3044 		*any_slot_found = 0;
       
  3045 
       
  3046 	/* Get slot list for memory allocation */
       
  3047 	rv = pFuncList->C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount);
       
  3048 
       
  3049 	if (rv != CKR_OK)
       
  3050 		{
       
  3051 		PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
       
  3052 		return (0);
       
  3053 		}
       
  3054 
       
  3055 	/* it's not an error if we didn't find any providers */
       
  3056 	if (ulSlotCount == 0)
       
  3057 		{
       
  3058 		DEBUG_SLOT_SEL("%s: no crypto providers found\n", PK11_DBG);
       
  3059 		return (1);
       
  3060 		}
       
  3061 
       
  3062 	pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
       
  3063 
       
  3064 	if (pSlotList == NULL)
       
  3065 		{
       
  3066 		PK11err(PK11_F_CHOOSE_SLOT, PK11_R_MALLOC_FAILURE);
       
  3067 		return (0);
       
  3068 		}
       
  3069 
       
  3070 	/* Get the slot list for processing */
       
  3071 	rv = pFuncList->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount);
       
  3072 	if (rv != CKR_OK)
       
  3073 		{
       
  3074 		PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
       
  3075 		OPENSSL_free(pSlotList);
       
  3076 		return (0);
       
  3077 		}
       
  3078 
       
  3079 	DEBUG_SLOT_SEL("%s: provider: %s\n", PK11_DBG, def_PK11_LIBNAME);
       
  3080 	DEBUG_SLOT_SEL("%s: number of slots: %d\n", PK11_DBG, ulSlotCount);
       
  3081 
       
  3082 	DEBUG_SLOT_SEL("%s: == checking rand slots ==\n", PK11_DBG);
       
  3083 	for (i = 0; i < ulSlotCount; i++)
       
  3084 		{
       
  3085 		current_slot = pSlotList[i];
       
  3086 
       
  3087 		DEBUG_SLOT_SEL("%s: checking slot: %d\n", PK11_DBG, i);
       
  3088 		/* Check if slot has random support. */
       
  3089 		rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
       
  3090 		if (rv != CKR_OK)
       
  3091 			continue;
       
  3092 
       
  3093 		DEBUG_SLOT_SEL("%s: token label: %.32s\n", PK11_DBG,
       
  3094 		    token_info.label);
       
  3095 
       
  3096 		if (token_info.flags & CKF_RNG)
       
  3097 			{
       
  3098 			DEBUG_SLOT_SEL(
       
  3099 			    "%s: this token has CKF_RNG flag\n", PK11_DBG);
       
  3100 			pk11_have_random = CK_TRUE;
       
  3101 			rand_SLOTID = current_slot;
       
  3102 			break;
       
  3103 			}
       
  3104 		}
       
  3105 
       
  3106 	DEBUG_SLOT_SEL("%s: == checking pubkey slots ==\n", PK11_DBG);
       
  3107 
       
  3108 	pubkey_SLOTID = pSlotList[0];
       
  3109 	for (i = 0; i < ulSlotCount; i++)
       
  3110 		{
       
  3111 		CK_BBOOL slot_has_rsa = CK_FALSE;
       
  3112 		CK_BBOOL slot_has_dsa = CK_FALSE;
       
  3113 		CK_BBOOL slot_has_dh = CK_FALSE;
       
  3114 		current_slot = pSlotList[i];
       
  3115 
       
  3116 		DEBUG_SLOT_SEL("%s: checking slot: %d\n", PK11_DBG, i);
       
  3117 		rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
       
  3118 		if (rv != CKR_OK)
       
  3119 			continue;
       
  3120 
       
  3121 		DEBUG_SLOT_SEL("%s: token label: %.32s\n", PK11_DBG,
       
  3122 		    token_info.label);
       
  3123 
       
  3124 #ifndef OPENSSL_NO_RSA
       
  3125 		/*
       
  3126 		 * Check if this slot is capable of signing and
       
  3127 		 * verifying with CKM_RSA_PKCS.
       
  3128 		 */
       
  3129 		rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS,
       
  3130 			&mech_info);
       
  3131 
       
  3132 		if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
       
  3133 				(mech_info.flags & CKF_VERIFY)))
       
  3134 			{
       
  3135 			/*
       
  3136 			 * Check if this slot is capable of encryption,
       
  3137 			 * decryption, sign, and verify with CKM_RSA_X_509.
       
  3138 			 */
       
  3139 			rv = pFuncList->C_GetMechanismInfo(current_slot,
       
  3140 			    CKM_RSA_X_509, &mech_info);
       
  3141 
       
  3142 			if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
       
  3143 			    (mech_info.flags & CKF_VERIFY) &&
       
  3144 			    (mech_info.flags & CKF_ENCRYPT) &&
       
  3145 			    (mech_info.flags & CKF_VERIFY_RECOVER) &&
       
  3146 			    (mech_info.flags & CKF_DECRYPT)))
       
  3147 				{
       
  3148 				slot_has_rsa = CK_TRUE;
       
  3149 				}
       
  3150 			}
       
  3151 #endif	/* OPENSSL_NO_RSA */
       
  3152 
       
  3153 #ifndef OPENSSL_NO_DSA
       
  3154 		/*
       
  3155 		 * Check if this slot is capable of signing and
       
  3156 		 * verifying with CKM_DSA.
       
  3157 		 */
       
  3158 		rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_DSA,
       
  3159 			&mech_info);
       
  3160 		if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
       
  3161 		    (mech_info.flags & CKF_VERIFY)))
       
  3162 			{
       
  3163 			slot_has_dsa = CK_TRUE;
       
  3164 			}
       
  3165 
       
  3166 #endif	/* OPENSSL_NO_DSA */
       
  3167 
       
  3168 #ifndef OPENSSL_NO_DH
       
  3169 		/*
       
  3170 		 * Check if this slot is capable of DH key generataion and
       
  3171 		 * derivation.
       
  3172 		 */
       
  3173 		rv = pFuncList->C_GetMechanismInfo(current_slot,
       
  3174 		    CKM_DH_PKCS_KEY_PAIR_GEN, &mech_info);
       
  3175 
       
  3176 		if (rv == CKR_OK && (mech_info.flags & CKF_GENERATE_KEY_PAIR))
       
  3177 			{
       
  3178 			rv = pFuncList->C_GetMechanismInfo(current_slot,
       
  3179 				CKM_DH_PKCS_DERIVE, &mech_info);
       
  3180 			if (rv == CKR_OK && (mech_info.flags & CKF_DERIVE))
       
  3181 				{
       
  3182 				slot_has_dh = CK_TRUE;
       
  3183 				}
       
  3184 			}
       
  3185 #endif	/* OPENSSL_NO_DH */
       
  3186 
       
  3187 		if (!found_candidate_slot &&
       
  3188 		    (slot_has_rsa || slot_has_dsa || slot_has_dh))
       
  3189 			{
       
  3190 			DEBUG_SLOT_SEL(
       
  3191 			    "%s: potential slot: %d\n", PK11_DBG, current_slot);
       
  3192 			best_slot_sofar = current_slot;
       
  3193 			pk11_have_rsa = slot_has_rsa;
       
  3194 			pk11_have_dsa = slot_has_dsa;
       
  3195 			pk11_have_dh = slot_has_dh;
       
  3196 			found_candidate_slot = CK_TRUE;
       
  3197 			/*
       
  3198 			 * Cache the flags for later use. We might need those if
       
  3199 			 * RSA keys by reference feature is used.
       
  3200 			 */
       
  3201 			pubkey_token_flags = token_info.flags;
       
  3202 			DEBUG_SLOT_SEL(
       
  3203 			    "%s: setting found_candidate_slot to CK_TRUE\n",
       
  3204 			    PK11_DBG);
       
  3205 			DEBUG_SLOT_SEL("%s: best slot so far: %d\n", PK11_DBG,
       
  3206 			    best_slot_sofar);
       
  3207 			DEBUG_SLOT_SEL("%s: pubkey flags changed to "
       
  3208 			    "%lu.\n", PK11_DBG, pubkey_token_flags);
       
  3209 			}
       
  3210 		else
       
  3211 			{
       
  3212 			DEBUG_SLOT_SEL("%s: no rsa/dsa/dh\n", PK11_DBG);
       
  3213 			}
       
  3214 		} /* for */
       
  3215 
       
  3216 	if (found_candidate_slot == CK_TRUE)
       
  3217 		{
       
  3218 		pubkey_SLOTID = best_slot_sofar;
       
  3219 		}
       
  3220 
       
  3221 	found_candidate_slot = CK_FALSE;
       
  3222 	best_slot_sofar = 0;
       
  3223 
       
  3224 	DEBUG_SLOT_SEL("%s: == checking cipher/digest ==\n", PK11_DBG);
       
  3225 
       
  3226 	SLOTID = pSlotList[0];
       
  3227 	for (i = 0; i < ulSlotCount; i++)
       
  3228 		{
       
  3229 		DEBUG_SLOT_SEL("%s: checking slot: %d\n", PK11_DBG, i);
       
  3230 
       
  3231 		current_slot = pSlotList[i];
       
  3232 		current_slot_n_cipher = 0;
       
  3233 		current_slot_n_digest = 0;
       
  3234 		(void) memset(local_cipher_nids, 0, sizeof (local_cipher_nids));
       
  3235 		(void) memset(local_digest_nids, 0, sizeof (local_digest_nids));
       
  3236 
       
  3237 		pk11_find_symmetric_ciphers(pFuncList, current_slot,
       
  3238 		    &current_slot_n_cipher, local_cipher_nids);
       
  3239 
       
  3240 		pk11_find_digests(pFuncList, current_slot,
       
  3241 		    &current_slot_n_digest, local_digest_nids);
       
  3242 
       
  3243 		DEBUG_SLOT_SEL("%s: current_slot_n_cipher %d\n", PK11_DBG,
       
  3244 			current_slot_n_cipher);
       
  3245 		DEBUG_SLOT_SEL("%s: current_slot_n_digest %d\n", PK11_DBG,
       
  3246 			current_slot_n_digest);
       
  3247 		DEBUG_SLOT_SEL("%s: best cipher/digest slot so far: %d\n",
       
  3248 			PK11_DBG, best_slot_sofar);
       
  3249 
       
  3250 		/*
       
  3251 		 * If the current slot supports more ciphers/digests than
       
  3252 		 * the previous best one we change the current best to this one,
       
  3253 		 * otherwise leave it where it is.
       
  3254 		 */
       
  3255 		if ((current_slot_n_cipher + current_slot_n_digest) >
       
  3256 		    (slot_n_cipher + slot_n_digest))
       
  3257 			{
       
  3258 			DEBUG_SLOT_SEL("%s: changing best slot to %d\n",
       
  3259 				PK11_DBG, current_slot);
       
  3260 			best_slot_sofar = SLOTID = current_slot;
       
  3261 			cipher_count = slot_n_cipher = current_slot_n_cipher;
       
  3262 			digest_count = slot_n_digest = current_slot_n_digest;
       
  3263 			(void) memcpy(cipher_nids, local_cipher_nids,
       
  3264 			    sizeof (local_cipher_nids));
       
  3265 			(void) memcpy(digest_nids, local_digest_nids,
       
  3266 			    sizeof (local_digest_nids));
       
  3267 			}
       
  3268 		}
       
  3269 
       
  3270 	DEBUG_SLOT_SEL("%s: chosen pubkey slot: %d\n", PK11_DBG, pubkey_SLOTID);
       
  3271 	DEBUG_SLOT_SEL("%s: chosen rand slot: %d\n", PK11_DBG, rand_SLOTID);
       
  3272 	DEBUG_SLOT_SEL("%s: chosen cipher/digest slot: %d\n", PK11_DBG, SLOTID);
       
  3273 	DEBUG_SLOT_SEL("%s: pk11_have_rsa %d\n", PK11_DBG, pk11_have_rsa);
       
  3274 	DEBUG_SLOT_SEL("%s: pk11_have_dsa %d\n", PK11_DBG, pk11_have_dsa);
       
  3275 	DEBUG_SLOT_SEL("%s: pk11_have_dh %d\n", PK11_DBG, pk11_have_dh);
       
  3276 	DEBUG_SLOT_SEL("%s: pk11_have_random %d\n", PK11_DBG, pk11_have_random);
       
  3277 	DEBUG_SLOT_SEL("%s: cipher_count %d\n", PK11_DBG, cipher_count);
       
  3278 	DEBUG_SLOT_SEL("%s: digest_count %d\n", PK11_DBG, digest_count);
       
  3279 
       
  3280 	if (pSlotList != NULL)
       
  3281 		OPENSSL_free(pSlotList);
       
  3282 
       
  3283 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3284 	OPENSSL_free(hw_cnids);
       
  3285 	OPENSSL_free(hw_dnids);
       
  3286 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3287 
       
  3288 	if (any_slot_found != NULL)
       
  3289 		*any_slot_found = 1;
       
  3290 	return (1);
       
  3291 	}
       
  3292 
       
  3293 static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR pflist,
       
  3294     int slot_id, int *current_slot_n_cipher, int *local_cipher_nids,
       
  3295     PK11_CIPHER *cipher)
       
  3296 	{
       
  3297 	CK_MECHANISM_INFO mech_info;
       
  3298 	CK_RV rv;
       
  3299 
       
  3300 	DEBUG_SLOT_SEL("%s: checking mech: %x", PK11_DBG, cipher->mech_type);
       
  3301 	rv = pflist->C_GetMechanismInfo(slot_id, cipher->mech_type, &mech_info);
       
  3302 
       
  3303 	if (rv != CKR_OK)
       
  3304 		{
       
  3305 		DEBUG_SLOT_SEL(" not found\n");
       
  3306 		return;
       
  3307 		}
       
  3308 
       
  3309 	if ((mech_info.flags & CKF_ENCRYPT) &&
       
  3310 	    (mech_info.flags & CKF_DECRYPT))
       
  3311 		{
       
  3312 		if (mech_info.ulMinKeySize > cipher->min_key_len ||
       
  3313 		    mech_info.ulMaxKeySize < cipher->max_key_len)
       
  3314 			{
       
  3315 			DEBUG_SLOT_SEL(" engine key size range <%i-%i> does not"
       
  3316 			    " match mech range <%lu-%lu>\n",
       
  3317 			    cipher->min_key_len, cipher->max_key_len,
       
  3318 			    mech_info.ulMinKeySize, mech_info.ulMaxKeySize);
       
  3319 			return;
       
  3320 			}
       
  3321 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3322 		if (nid_in_table(cipher->nid, hw_cnids))
       
  3323 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3324 			{
       
  3325 			DEBUG_SLOT_SEL(" usable\n");
       
  3326 			local_cipher_nids[(*current_slot_n_cipher)++] =
       
  3327 			    cipher->nid;
       
  3328 			}
       
  3329 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3330 		else
       
  3331 			{
       
  3332 			DEBUG_SLOT_SEL(
       
  3333 			    " rejected, software implementation only\n");
       
  3334 			}
       
  3335 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3336 		}
       
  3337 	else
       
  3338 		{
       
  3339 		DEBUG_SLOT_SEL(" unusable\n");
       
  3340 		}
       
  3341 
       
  3342 	return;
       
  3343 	}
       
  3344 
       
  3345 static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist, int slot_id,
       
  3346     int *current_slot_n_digest, int *local_digest_nids, PK11_DIGEST *digest)
       
  3347 	{
       
  3348 	CK_MECHANISM_INFO mech_info;
       
  3349 	CK_RV rv;
       
  3350 
       
  3351 	DEBUG_SLOT_SEL("%s: checking mech: %x", PK11_DBG, digest->mech_type);
       
  3352 	rv = pflist->C_GetMechanismInfo(slot_id, digest->mech_type, &mech_info);
       
  3353 
       
  3354 	if (rv != CKR_OK)
       
  3355 		{
       
  3356 		DEBUG_SLOT_SEL(" not found\n");
       
  3357 		return;
       
  3358 		}
       
  3359 
       
  3360 	if (mech_info.flags & CKF_DIGEST)
       
  3361 		{
       
  3362 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3363 		if (nid_in_table(digest->nid, hw_dnids))
       
  3364 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3365 			{
       
  3366 			DEBUG_SLOT_SEL(" usable\n");
       
  3367 			local_digest_nids[(*current_slot_n_digest)++] =
       
  3368 			    digest->nid;
       
  3369 			}
       
  3370 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3371 		else
       
  3372 			{
       
  3373 			DEBUG_SLOT_SEL(
       
  3374 			    " rejected, software implementation only\n");
       
  3375 			}
       
  3376 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3377 		}
       
  3378 	else
       
  3379 		{
       
  3380 		DEBUG_SLOT_SEL(" unusable\n");
       
  3381 		}
       
  3382 
       
  3383 	return;
       
  3384 	}
       
  3385 
       
  3386 /* Find what symmetric ciphers this slot supports. */
       
  3387 static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist,
       
  3388     CK_SLOT_ID current_slot, int *current_slot_n_cipher, int *local_cipher_nids)
       
  3389 	{
       
  3390 	int i;
       
  3391 
       
  3392 	for (i = 0; i < PK11_CIPHER_MAX; ++i)
       
  3393 		{
       
  3394 		pk11_get_symmetric_cipher(pflist, current_slot,
       
  3395 		    current_slot_n_cipher, local_cipher_nids, &ciphers[i]);
       
  3396 		}
       
  3397 	}
       
  3398 
       
  3399 /* Find what digest algorithms this slot supports. */
       
  3400 static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
       
  3401     CK_SLOT_ID current_slot, int *current_slot_n_digest, int *local_digest_nids)
       
  3402 	{
       
  3403 	int i;
       
  3404 
       
  3405 	for (i = 0; i < PK11_DIGEST_MAX; ++i)
       
  3406 		{
       
  3407 		pk11_get_digest(pflist, current_slot, current_slot_n_digest,
       
  3408 		    local_digest_nids, &digests[i]);
       
  3409 		}
       
  3410 	}
       
  3411 
       
  3412 #ifdef	SOLARIS_HW_SLOT_SELECTION
       
  3413 /*
       
  3414  * It would be great if we could use pkcs11_kernel directly since this library
       
  3415  * offers hardware slots only. That's the easiest way to achieve the situation
       
  3416  * where we use the hardware accelerators when present and OpenSSL native code
       
  3417  * otherwise. That presumes the fact that OpenSSL native code is faster than the
       
  3418  * code in the soft token. It's a logical assumption - Crypto Framework has some
       
  3419  * inherent overhead so going there for the software implementation of a
       
  3420  * mechanism should be logically slower in contrast to the OpenSSL native code,
       
  3421  * presuming that both implementations are of similar speed. For example, the
       
  3422  * soft token for AES is roughly three times slower than OpenSSL for 64 byte
       
  3423  * blocks and still 20% slower for 8KB blocks. So, if we want to ship products
       
  3424  * that use the PKCS#11 engine by default, we must somehow avoid that regression
       
  3425  * on machines without hardware acceleration. That's why switching to the
       
  3426  * pkcs11_kernel library seems like a very good idea.
       
  3427  *
       
  3428  * The problem is that OpenSSL built with SunStudio is roughly 2x slower for
       
  3429  * asymmetric operations (RSA/DSA/DH) than the soft token built with the same
       
  3430  * compiler. That means that if we switched to pkcs11_kernel from the libpkcs11
       
  3431  * library, we would have had a performance regression on machines without
       
  3432  * hardware acceleration for asymmetric operations for all applications that use
       
  3433  * the PKCS#11 engine. There is one such application - Apache web server since
       
  3434  * it's shipped configured to use the PKCS#11 engine by default. Having said
       
  3435  * that, we can't switch to the pkcs11_kernel library now and have to come with
       
  3436  * a solution that, on non-accelerated machines, uses the OpenSSL native code
       
  3437  * for all symmetric ciphers and digests while it uses the soft token for
       
  3438  * asymmetric operations.
       
  3439  *
       
  3440  * This is the idea: dlopen() pkcs11_kernel directly and find out what
       
  3441  * mechanisms are there. We don't care about duplications (more slots can
       
  3442  * support the same mechanism), we just want to know what mechanisms can be
       
  3443  * possibly supported in hardware on that particular machine. As said before,
       
  3444  * pkcs11_kernel will show you hardware providers only.
       
  3445  *
       
  3446  * Then, we rely on the fact that since we use libpkcs11 library we will find
       
  3447  * the metaslot. When we go through the metaslot's mechanisms for symmetric
       
  3448  * ciphers and digests, we check that any found mechanism is in the table
       
  3449  * created using the pkcs11_kernel library. So, as a result we have two arrays
       
  3450  * of mechanisms that were advertised as supported in hardware which was the
       
  3451  * goal of that whole exercise. Thus, we can use libpkcs11 but avoid soft token
       
  3452  * code for symmetric ciphers and digests. See pk11_choose_slots() for more
       
  3453  * information.
       
  3454  *
       
  3455  * This is Solaris specific code, if SOLARIS_HW_SLOT_SELECTION is not defined
       
  3456  * the code won't be used.
       
  3457  */
       
  3458 #if defined(__sparcv9) || defined(__x86_64) || defined(__amd64)
       
  3459 static const char pkcs11_kernel[] = "/usr/lib/security/64/pkcs11_kernel.so.1";
       
  3460 #else
       
  3461 static const char pkcs11_kernel[] = "/usr/lib/security/pkcs11_kernel.so.1";
       
  3462 #endif
       
  3463 
       
  3464 /*
       
  3465  * Check hardware capabilities of the machines. The output are two lists,
       
  3466  * hw_cnids and hw_dnids, that contain hardware mechanisms found in all hardware
       
  3467  * providers together. They are not sorted and may contain duplicate mechanisms.
       
  3468  */
       
  3469 static int check_hw_mechanisms(void)
       
  3470 	{
       
  3471 	int i;
       
  3472 	CK_RV rv;
       
  3473 	void *handle;
       
  3474 	CK_C_GetFunctionList p;
       
  3475 	CK_TOKEN_INFO token_info;
       
  3476 	CK_ULONG ulSlotCount = 0;
       
  3477 	int n_cipher = 0, n_digest = 0;
       
  3478 	CK_FUNCTION_LIST_PTR pflist = NULL;
       
  3479 	CK_SLOT_ID_PTR pSlotList = NULL_PTR;
       
  3480 	int *tmp_hw_cnids = NULL, *tmp_hw_dnids = NULL;
       
  3481 	int hw_ctable_size, hw_dtable_size;
       
  3482 
       
  3483 	DEBUG_SLOT_SEL("%s: SOLARIS_HW_SLOT_SELECTION code running\n",
       
  3484 	    PK11_DBG);
       
  3485 	/*
       
  3486 	 * Use RTLD_GROUP to limit the pkcs11_kernel provider to its own
       
  3487 	 * symbols, which prevents it from mistakenly accessing C_* functions
       
  3488 	 * from the top-level PKCS#11 library.
       
  3489 	 */
       
  3490 	if ((handle = dlopen(pkcs11_kernel, RTLD_LAZY | RTLD_GROUP)) == NULL)
       
  3491 		{
       
  3492 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
       
  3493 		goto err;
       
  3494 		}
       
  3495 
       
  3496 	if ((p = (CK_C_GetFunctionList)dlsym(handle,
       
  3497 	    PK11_GET_FUNCTION_LIST)) == NULL)
       
  3498 		{
       
  3499 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
       
  3500 		goto err;
       
  3501 		}
       
  3502 
       
  3503 	/* get the full function list from the loaded library */
       
  3504 	if (p(&pflist) != CKR_OK)
       
  3505 		{
       
  3506 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
       
  3507 		goto err;
       
  3508 		}
       
  3509 
       
  3510 	rv = pflist->C_Initialize(NULL_PTR);
       
  3511 	if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
       
  3512 		{
       
  3513 		PK11err_add_data(PK11_F_CHECK_HW_MECHANISMS,
       
  3514 		    PK11_R_INITIALIZE, rv);
       
  3515 		goto err;
       
  3516 		}
       
  3517 
       
  3518 	if (pflist->C_GetSlotList(0, NULL_PTR, &ulSlotCount) != CKR_OK)
       
  3519 		{
       
  3520 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
       
  3521 		goto err;
       
  3522 		}
       
  3523 
       
  3524 	/* no slots, set the hw mechanism tables as empty */
       
  3525 	if (ulSlotCount == 0)
       
  3526 		{
       
  3527 		DEBUG_SLOT_SEL("%s: no hardware mechanisms found\n", PK11_DBG);
       
  3528 		hw_cnids = OPENSSL_malloc(sizeof (int));
       
  3529 		hw_dnids = OPENSSL_malloc(sizeof (int));
       
  3530 		if (hw_cnids == NULL || hw_dnids == NULL)
       
  3531 			{
       
  3532 			PK11err(PK11_F_CHECK_HW_MECHANISMS,
       
  3533 			    PK11_R_MALLOC_FAILURE);
       
  3534 			return (0);
       
  3535 			}
       
  3536 		/* this means empty tables */
       
  3537 		hw_cnids[0] = NID_undef;
       
  3538 		hw_dnids[0] = NID_undef;
       
  3539 		return (1);
       
  3540 		}
       
  3541 
       
  3542 	pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
       
  3543 	if (pSlotList == NULL)
       
  3544 		{
       
  3545 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
       
  3546 		goto err;
       
  3547 		}
       
  3548 
       
  3549 	/* Get the slot list for processing */
       
  3550 	if (pflist->C_GetSlotList(0, pSlotList, &ulSlotCount) != CKR_OK)
       
  3551 		{
       
  3552 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
       
  3553 		goto err;
       
  3554 		}
       
  3555 
       
  3556 	/*
       
  3557 	 * We don't care about duplicate mechanisms in multiple slots and also
       
  3558 	 * reserve one slot for the terminal NID_undef which we use to stop the
       
  3559 	 * search.
       
  3560 	 */
       
  3561 	hw_ctable_size = ulSlotCount * PK11_CIPHER_MAX + 1;
       
  3562 	hw_dtable_size = ulSlotCount * PK11_DIGEST_MAX + 1;
       
  3563 	tmp_hw_cnids = OPENSSL_malloc(hw_ctable_size * sizeof (int));
       
  3564 	tmp_hw_dnids = OPENSSL_malloc(hw_dtable_size * sizeof (int));
       
  3565 	if (tmp_hw_cnids == NULL || tmp_hw_dnids == NULL)
       
  3566 		{
       
  3567 		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
       
  3568 		goto err;
       
  3569 		}
       
  3570 
       
  3571 	/*
       
  3572 	 * Do not use memset since we should not rely on the fact that NID_undef
       
  3573 	 * is zero now.
       
  3574 	 */
       
  3575 	for (i = 0; i < hw_ctable_size; ++i)
       
  3576 		tmp_hw_cnids[i] = NID_undef;
       
  3577 	for (i = 0; i < hw_dtable_size; ++i)
       
  3578 		tmp_hw_dnids[i] = NID_undef;
       
  3579 
       
  3580 	DEBUG_SLOT_SEL("%s: provider: %s\n", PK11_DBG, pkcs11_kernel);
       
  3581 	DEBUG_SLOT_SEL("%s: found %d hardware slots\n", PK11_DBG, ulSlotCount);
       
  3582 	DEBUG_SLOT_SEL("%s: now looking for mechs supported in hw\n",
       
  3583 	    PK11_DBG);
       
  3584 
       
  3585 	for (i = 0; i < ulSlotCount; i++)
       
  3586 		{
       
  3587 		if (pflist->C_GetTokenInfo(pSlotList[i], &token_info) != CKR_OK)
       
  3588 			continue;
       
  3589 
       
  3590 		DEBUG_SLOT_SEL("%s: token label: %.32s\n", PK11_DBG,
       
  3591 		    token_info.label);
       
  3592 
       
  3593 		/*
       
  3594 		 * We are filling the hw mech tables here. Global tables are
       
  3595 		 * still NULL so all mechanisms are put into tmp tables.
       
  3596 		 */
       
  3597 		pk11_find_symmetric_ciphers(pflist, pSlotList[i],
       
  3598 		    &n_cipher, tmp_hw_cnids);
       
  3599 		pk11_find_digests(pflist, pSlotList[i],
       
  3600 		    &n_digest, tmp_hw_dnids);
       
  3601 		}
       
  3602 
       
  3603 	/*
       
  3604 	 * Since we are part of a library (libcrypto.so), calling this function
       
  3605 	 * may have side-effects. Also, C_Finalize() is triggered by
       
  3606 	 * dlclose(3C).
       
  3607 	 */
       
  3608 #if 0
       
  3609 	pflist->C_Finalize(NULL);
       
  3610 #endif
       
  3611 	OPENSSL_free(pSlotList);
       
  3612 	(void) dlclose(handle);
       
  3613 	hw_cnids = tmp_hw_cnids;
       
  3614 	hw_dnids = tmp_hw_dnids;
       
  3615 
       
  3616 	DEBUG_SLOT_SEL("%s: hw mechs check complete\n", PK11_DBG);
       
  3617 	return (1);
       
  3618 
       
  3619 err:
       
  3620 	if (pSlotList != NULL)
       
  3621 		OPENSSL_free(pSlotList);
       
  3622 	if (tmp_hw_cnids != NULL)
       
  3623 		OPENSSL_free(tmp_hw_cnids);
       
  3624 	if (tmp_hw_dnids != NULL)
       
  3625 		OPENSSL_free(tmp_hw_dnids);
       
  3626 
       
  3627 	return (0);
       
  3628 	}
       
  3629 
       
  3630 /*
       
  3631  * Check presence of a NID in the table of NIDs unless the mechanism is
       
  3632  * supported directly in a CPU instruction set. The table may be NULL (i.e.,
       
  3633  * non-existent).
       
  3634  */
       
  3635 static int nid_in_table(int nid, int *nid_table)
       
  3636 	{
       
  3637 	int i = 0;
       
  3638 
       
  3639 	/*
       
  3640 	 * Special case first. NULL means that we are initializing a new table.
       
  3641 	 */
       
  3642 	if (nid_table == NULL)
       
  3643 		return (1);
       
  3644 
       
  3645 #if defined(__x86)
       
  3646 	/*
       
  3647 	 * On Intel, if we have AES-NI instruction set we route AES to the
       
  3648 	 * Crypto Framework. Intel CPUs do not have other instruction sets for
       
  3649 	 * HW crypto acceleration so we check the HW NID table for any other
       
  3650 	 * mechanism.
       
  3651 	 */
       
  3652 	if (hw_aes_instruction_set_present() == 1)
       
  3653 		{
       
  3654 		switch (nid)
       
  3655 			{
       
  3656 			case NID_aes_128_ecb:
       
  3657 			case NID_aes_192_ecb:
       
  3658 			case NID_aes_256_ecb:
       
  3659 			case NID_aes_128_cbc:
       
  3660 			case NID_aes_192_cbc:
       
  3661 			case NID_aes_256_cbc:
       
  3662 			case NID_aes_128_ctr:
       
  3663 			case NID_aes_192_ctr:
       
  3664 			case NID_aes_256_ctr:
       
  3665 				return (1);
       
  3666 			}
       
  3667 		}
       
  3668 #elif defined(__sparc)
       
  3669 	if (hw_aes_instruction_set_present() == 1)
       
  3670 		return (1);
       
  3671 #endif
       
  3672 
       
  3673 	/* The table is never full, there is always at least one NID_undef. */
       
  3674 	while (nid_table[i] != NID_undef)
       
  3675 		{
       
  3676 		if (nid_table[i++] == nid)
       
  3677 			{
       
  3678 			DEBUG_SLOT_SEL(" (NID %d in hw table, idx %d)", nid, i);
       
  3679 			return (1);
       
  3680 			}
       
  3681 		}
       
  3682 
       
  3683 	return (0);
       
  3684 	}
       
  3685 
       
  3686 /* Do we have an AES instruction set? */
       
  3687 static int
       
  3688 hw_aes_instruction_set_present(void)
       
  3689 	{
       
  3690 	static int present = -1;
       
  3691 
       
  3692 	if (present == -1)
       
  3693 		{
       
  3694 		uint_t ui = 0;
       
  3695 
       
  3696 		(void) getisax(&ui, 1);
       
  3697 
       
  3698 #if defined(__amd64) || defined(__i386)
       
  3699 		present = (ui & (AV_386_AES)) > 0;
       
  3700 #elif defined(__sparc)
       
  3701 		present = (ui & (AV_SPARC_AES|AV_SPARC_FJAES)) > 0;
       
  3702 #endif
       
  3703 		}
       
  3704 
       
  3705 	return (present);
       
  3706 	}
       
  3707 
       
  3708 #endif	/* SOLARIS_HW_SLOT_SELECTION */
       
  3709 
       
  3710 #endif	/* OPENSSL_NO_HW_PK11 */
       
  3711 #endif	/* OPENSSL_NO_HW */