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