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