2 * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
5 #pragma ident "@(#)hw_pk11.c 1.6 10/09/23 SMI"
7 /* crypto/engine/hw_pk11.c */
9 * This product includes software developed by the OpenSSL Project for
10 * use in the OpenSSL Toolkit (http://www.openssl.org/).
12 * This project also referenced hw_pkcs11-0.9.7b.patch written by
16 * ====================================================================
17 * Copyright (c) 2000-2001 The OpenSSL Project. All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in
28 * the documentation and/or other materials provided with the
31 * 3. All advertising materials mentioning features or use of this
32 * software must display the following acknowledgment:
33 * "This product includes software developed by the OpenSSL Project
34 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
36 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
37 * endorse or promote products derived from this software without
38 * prior written permission. For written permission, please contact
39 * licensing@OpenSSL.org.
41 * 5. Products derived from this software may not be called "OpenSSL"
42 * nor may "OpenSSL" appear in their names without prior written
43 * permission of the OpenSSL Project.
45 * 6. Redistributions of any form whatsoever must retain the following
47 * "This product includes software developed by the OpenSSL Project
48 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
50 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
51 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
53 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
54 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
55 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
56 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
57 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
59 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
60 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
61 * OF THE POSSIBILITY OF SUCH DAMAGE.
62 * ====================================================================
64 * This product includes cryptographic software written by Eric Young
65 * (eay@cryptsoft.com). This product includes software written by Tim
66 * Hudson (tjh@cryptsoft.com).
73 #include <sys/types.h>
77 #include <openssl/e_os2.h>
78 #include <openssl/crypto.h>
79 #include <openssl/engine.h>
80 #include <openssl/dso.h>
81 #include <openssl/err.h>
82 #include <openssl/bn.h>
83 #include <openssl/md5.h>
84 #include <openssl/pem.h>
85 #ifndef OPENSSL_NO_RSA
86 #include <openssl/rsa.h>
88 #ifndef OPENSSL_NO_DSA
89 #include <openssl/dsa.h>
92 #include <openssl/dh.h>
94 #include <openssl/rand.h>
95 #include <openssl/objects.h>
96 #include <openssl/x509.h>
97 #include <openssl/aes.h>
102 #ifndef OPENSSL_NO_HW
103 #ifndef OPENSSL_NO_HW_PK11
105 /* label for debug messages printed on stderr */
106 #define PK11_DBG "PKCS#11 ENGINE DEBUG"
107 /* prints a lot of debug messages on stderr about slot selection process */
108 #undef DEBUG_SLOT_SELECTION
110 * Solaris specific code. See comment at check_hw_mechanisms() for more
113 #if defined(__SVR4) && defined(__sun)
114 #define SOLARIS_HW_SLOT_SELECTION
118 * AES counter mode is not supported in the OpenSSL EVP API yet and neither
119 * there are official OIDs for mechanisms based on this mode. With our changes,
120 * an application can define its own EVP calls for AES counter mode and then
121 * it can make use of hardware acceleration through this engine. However, it's
122 * better if we keep AES CTR support code under ifdef's.
124 #define SOLARIS_AES_CTR
126 #include <security/cryptoki.h>
127 #include <security/pkcs11.h>
129 #include "hw_pk11_uri.h"
131 #define PK11_ENGINE_LIB_NAME "PKCS#11 engine"
132 #include "hw_pk11_err.c"
134 #ifdef SOLARIS_AES_CTR
136 * NIDs for AES counter mode that will be defined during the engine
139 int NID_aes_128_ctr
= NID_undef
;
140 int NID_aes_192_ctr
= NID_undef
;
141 int NID_aes_256_ctr
= NID_undef
;
142 #endif /* SOLARIS_AES_CTR */
145 * We use this lock to prevent multiple C_Login()s, guard getpassphrase(),
146 * uri_struct manipulation, and static token info. All of that is used by the
147 * RSA keys by reference feature.
149 pthread_mutex_t
*uri_lock
;
151 #ifdef SOLARIS_HW_SLOT_SELECTION
153 * Tables for symmetric ciphers and digest mechs found in the pkcs11_kernel
154 * library. See comment at check_hw_mechanisms() for more information.
158 #endif /* SOLARIS_HW_SLOT_SELECTION */
160 /* PKCS#11 session caches and their locks for all operation types */
161 static PK11_CACHE session_cache
[OP_MAX
];
164 * We cache the flags so that we do not have to run C_GetTokenInfo() again when
165 * logging into the token.
167 CK_FLAGS pubkey_token_flags
;
170 * As stated in v2.20, 11.7 Object Management Function, in section for
171 * C_FindObjectsInit(), at most one search operation may be active at a given
172 * time in a given session. Therefore, C_Find{,Init,Final}Objects() should be
173 * grouped together to form one atomic search operation. This is already
174 * ensured by the property of unique PKCS#11 session handle used for each
175 * PK11_SESSION object.
177 * This is however not the biggest concern - maintaining consistency of the
178 * underlying object store is more important. The same section of the spec also
179 * says that one thread can be in the middle of a search operation while another
180 * thread destroys the object matching the search template which would result in
181 * invalid handle returned from the search operation.
183 * Hence, the following locks are used for both protection of the object stores.
184 * They are also used for active list protection.
186 pthread_mutex_t
*find_lock
[OP_MAX
] = { NULL
};
189 * lists of asymmetric key handles which are active (referenced by at least one
190 * PK11_SESSION structure, either held by a thread or present in free_session
191 * list) for given algorithm type
193 PK11_active
*active_list
[OP_MAX
] = { NULL
};
196 * Create all secret key objects in a global session so that they are available
197 * to use for other sessions. These other sessions may be opened or closed
198 * without losing the secret key objects.
200 static CK_SESSION_HANDLE global_session
= CK_INVALID_HANDLE
;
202 /* ENGINE level stuff */
203 static int pk11_init(ENGINE
*e
);
204 static int pk11_library_init(ENGINE
*e
);
205 static int pk11_finish(ENGINE
*e
);
206 static int pk11_ctrl(ENGINE
*e
, int cmd
, long i
, void *p
, void (*f
)());
207 static int pk11_destroy(ENGINE
*e
);
210 static void pk11_rand_seed(const void *buf
, int num
);
211 static void pk11_rand_add(const void *buf
, int num
, double add_entropy
);
212 static void pk11_rand_cleanup(void);
213 static int pk11_rand_bytes(unsigned char *buf
, int num
);
214 static int pk11_rand_status(void);
216 /* These functions are also used in other files */
217 PK11_SESSION
*pk11_get_session(PK11_OPTYPE optype
);
218 void pk11_return_session(PK11_SESSION
*sp
, PK11_OPTYPE optype
);
220 /* active list manipulation functions used in this file */
221 extern int pk11_active_delete(CK_OBJECT_HANDLE h
, PK11_OPTYPE type
);
222 extern void pk11_free_active_list(PK11_OPTYPE type
);
224 #ifndef OPENSSL_NO_RSA
225 int pk11_destroy_rsa_key_objects(PK11_SESSION
*session
);
226 int pk11_destroy_rsa_object_pub(PK11_SESSION
*sp
, CK_BBOOL uselock
);
227 int pk11_destroy_rsa_object_priv(PK11_SESSION
*sp
, CK_BBOOL uselock
);
229 #ifndef OPENSSL_NO_DSA
230 int pk11_destroy_dsa_key_objects(PK11_SESSION
*session
);
231 int pk11_destroy_dsa_object_pub(PK11_SESSION
*sp
, CK_BBOOL uselock
);
232 int pk11_destroy_dsa_object_priv(PK11_SESSION
*sp
, CK_BBOOL uselock
);
234 #ifndef OPENSSL_NO_DH
235 int pk11_destroy_dh_key_objects(PK11_SESSION
*session
);
236 int pk11_destroy_dh_object(PK11_SESSION
*session
, CK_BBOOL uselock
);
239 /* Local helper functions */
240 static int pk11_free_all_sessions(void);
241 static int pk11_free_session_list(PK11_OPTYPE optype
);
242 static int pk11_setup_session(PK11_SESSION
*sp
, PK11_OPTYPE optype
);
243 static int pk11_destroy_cipher_key_objects(PK11_SESSION
*session
);
244 static int pk11_destroy_object(CK_SESSION_HANDLE handle
, CK_OBJECT_HANDLE oh
,
245 CK_BBOOL persistent
);
246 static const char *get_PK11_LIBNAME(void);
247 static void free_PK11_LIBNAME(void);
248 static long set_PK11_LIBNAME(const char *name
);
250 /* Symmetric cipher and digest support functions */
251 static int cipher_nid_to_pk11(int nid
);
252 #ifdef SOLARIS_AES_CTR
253 static int pk11_add_NID(char *sn
, char *ln
);
254 static int pk11_add_aes_ctr_NIDs(void);
255 #endif /* SOLARIS_AES_CTR */
256 static int pk11_usable_ciphers(const int **nids
);
257 static int pk11_usable_digests(const int **nids
);
258 static int pk11_cipher_init(EVP_CIPHER_CTX
*ctx
, const unsigned char *key
,
259 const unsigned char *iv
, int enc
);
260 static int pk11_cipher_final(PK11_SESSION
*sp
);
261 static int pk11_cipher_do_cipher(EVP_CIPHER_CTX
*ctx
, unsigned char *out
,
262 const unsigned char *in
, unsigned int inl
);
263 static int pk11_cipher_cleanup(EVP_CIPHER_CTX
*ctx
);
264 static int pk11_engine_ciphers(ENGINE
*e
, const EVP_CIPHER
**cipher
,
265 const int **nids
, int nid
);
266 static int pk11_engine_digests(ENGINE
*e
, const EVP_MD
**digest
,
267 const int **nids
, int nid
);
268 static CK_OBJECT_HANDLE
pk11_get_cipher_key(EVP_CIPHER_CTX
*ctx
,
269 const unsigned char *key
, CK_KEY_TYPE key_type
, PK11_SESSION
*sp
);
270 static int check_new_cipher_key(PK11_SESSION
*sp
, const unsigned char *key
,
272 static int md_nid_to_pk11(int nid
);
273 static int pk11_digest_init(EVP_MD_CTX
*ctx
);
274 static int pk11_digest_update(EVP_MD_CTX
*ctx
, const void *data
,
276 static int pk11_digest_final(EVP_MD_CTX
*ctx
, unsigned char *md
);
277 static int pk11_digest_copy(EVP_MD_CTX
*to
, const EVP_MD_CTX
*from
);
278 static int pk11_digest_cleanup(EVP_MD_CTX
*ctx
);
280 static int pk11_choose_slots(int *any_slot_found
);
281 static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist
,
282 CK_SLOT_ID current_slot
, int *current_slot_n_cipher
,
283 int *local_cipher_nids
);
284 static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist
,
285 CK_SLOT_ID current_slot
, int *current_slot_n_digest
,
286 int *local_digest_nids
);
287 static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR
, int slot_id
,
288 CK_MECHANISM_TYPE mech
, int *current_slot_n_cipher
, int *local_cipher_nids
,
290 static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist
, int slot_id
,
291 CK_MECHANISM_TYPE mech
, int *current_slot_n_digest
, int *local_digest_nids
,
294 static int pk11_init_all_locks(void);
295 static void pk11_free_all_locks(void);
297 #ifdef SOLARIS_HW_SLOT_SELECTION
298 static int check_hw_mechanisms(void);
299 static int nid_in_table(int nid
, int *nid_table
);
300 #endif /* SOLARIS_HW_SLOT_SELECTION */
302 /* Index for the supported ciphers */
303 enum pk11_cipher_id
{
316 #ifdef SOLARIS_AES_CTR
320 #endif /* SOLARIS_AES_CTR */
324 /* Index for the supported digests */
325 enum pk11_digest_id
{
335 #define TRY_OBJ_DESTROY(sp, obj_hdl, retval, uselock, alg_type) \
338 LOCK_OBJSTORE(alg_type); \
339 if (pk11_active_delete(obj_hdl, alg_type) == 1) \
341 retval = pk11_destroy_object(sp->session, obj_hdl, \
345 UNLOCK_OBJSTORE(alg_type); \
348 static int cipher_nids
[PK11_CIPHER_MAX
];
349 static int digest_nids
[PK11_DIGEST_MAX
];
350 static int cipher_count
= 0;
351 static int digest_count
= 0;
352 static CK_BBOOL pk11_have_rsa
= CK_FALSE
;
353 static CK_BBOOL pk11_have_dsa
= CK_FALSE
;
354 static CK_BBOOL pk11_have_dh
= CK_FALSE
;
355 static CK_BBOOL pk11_have_random
= CK_FALSE
;
357 typedef struct PK11_CIPHER_st
359 enum pk11_cipher_id id
;
364 CK_KEY_TYPE key_type
;
365 CK_MECHANISM_TYPE mech_type
;
368 static PK11_CIPHER ciphers
[] =
370 { PK11_DES_CBC
, NID_des_cbc
, 8, 8, 8,
371 CKK_DES
, CKM_DES_CBC
, },
372 { PK11_DES3_CBC
, NID_des_ede3_cbc
, 8, 24, 24,
373 CKK_DES3
, CKM_DES3_CBC
, },
374 { PK11_DES_ECB
, NID_des_ecb
, 0, 8, 8,
375 CKK_DES
, CKM_DES_ECB
, },
376 { PK11_DES3_ECB
, NID_des_ede3_ecb
, 0, 24, 24,
377 CKK_DES3
, CKM_DES3_ECB
, },
378 { PK11_RC4
, NID_rc4
, 0, 16, 256,
380 { PK11_AES_128_CBC
, NID_aes_128_cbc
, 16, 16, 16,
381 CKK_AES
, CKM_AES_CBC
, },
382 { PK11_AES_192_CBC
, NID_aes_192_cbc
, 16, 24, 24,
383 CKK_AES
, CKM_AES_CBC
, },
384 { PK11_AES_256_CBC
, NID_aes_256_cbc
, 16, 32, 32,
385 CKK_AES
, CKM_AES_CBC
, },
386 { PK11_AES_128_ECB
, NID_aes_128_ecb
, 0, 16, 16,
387 CKK_AES
, CKM_AES_ECB
, },
388 { PK11_AES_192_ECB
, NID_aes_192_ecb
, 0, 24, 24,
389 CKK_AES
, CKM_AES_ECB
, },
390 { PK11_AES_256_ECB
, NID_aes_256_ecb
, 0, 32, 32,
391 CKK_AES
, CKM_AES_ECB
, },
392 { PK11_BLOWFISH_CBC
, NID_bf_cbc
, 8, 16, 16,
393 CKK_BLOWFISH
, CKM_BLOWFISH_CBC
, },
394 #ifdef SOLARIS_AES_CTR
395 /* we don't know the correct NIDs until the engine is initialized */
396 { PK11_AES_128_CTR
, NID_undef
, 16, 16, 16,
397 CKK_AES
, CKM_AES_CTR
, },
398 { PK11_AES_192_CTR
, NID_undef
, 16, 24, 24,
399 CKK_AES
, CKM_AES_CTR
, },
400 { PK11_AES_256_CTR
, NID_undef
, 16, 32, 32,
401 CKK_AES
, CKM_AES_CTR
, },
402 #endif /* SOLARIS_AES_CTR */
405 typedef struct PK11_DIGEST_st
407 enum pk11_digest_id id
;
409 CK_MECHANISM_TYPE mech_type
;
412 static PK11_DIGEST digests
[] =
414 {PK11_MD5
, NID_md5
, CKM_MD5
, },
415 {PK11_SHA1
, NID_sha1
, CKM_SHA_1
, },
416 {PK11_SHA224
, NID_sha224
, CKM_SHA224
, },
417 {PK11_SHA256
, NID_sha256
, CKM_SHA256
, },
418 {PK11_SHA384
, NID_sha384
, CKM_SHA384
, },
419 {PK11_SHA512
, NID_sha512
, CKM_SHA512
, },
420 {0, NID_undef
, 0xFFFF, },
424 * Structure to be used for the cipher_data/md_data in
425 * EVP_CIPHER_CTX/EVP_MD_CTX structures in order to use the same pk11
426 * session in multiple cipher_update calls
428 typedef struct PK11_CIPHER_STATE_st
435 * libcrypto EVP stuff - this is how we get wired to EVP so the engine gets
436 * called when libcrypto requests a cipher NID.
438 * Note how the PK11_CIPHER_STATE is used here.
442 static const EVP_CIPHER pk11_des_cbc
=
448 pk11_cipher_do_cipher
,
450 sizeof (PK11_CIPHER_STATE
),
451 EVP_CIPHER_set_asn1_iv
,
452 EVP_CIPHER_get_asn1_iv
,
457 static const EVP_CIPHER pk11_3des_cbc
=
463 pk11_cipher_do_cipher
,
465 sizeof (PK11_CIPHER_STATE
),
466 EVP_CIPHER_set_asn1_iv
,
467 EVP_CIPHER_get_asn1_iv
,
472 * ECB modes don't use an Initial Vector so that's why set_asn1_parameters and
473 * get_asn1_parameters fields are set to NULL.
475 static const EVP_CIPHER pk11_des_ecb
=
481 pk11_cipher_do_cipher
,
483 sizeof (PK11_CIPHER_STATE
),
489 static const EVP_CIPHER pk11_3des_ecb
=
495 pk11_cipher_do_cipher
,
497 sizeof (PK11_CIPHER_STATE
),
504 static const EVP_CIPHER pk11_aes_128_cbc
=
510 pk11_cipher_do_cipher
,
512 sizeof (PK11_CIPHER_STATE
),
513 EVP_CIPHER_set_asn1_iv
,
514 EVP_CIPHER_get_asn1_iv
,
518 static const EVP_CIPHER pk11_aes_192_cbc
=
524 pk11_cipher_do_cipher
,
526 sizeof (PK11_CIPHER_STATE
),
527 EVP_CIPHER_set_asn1_iv
,
528 EVP_CIPHER_get_asn1_iv
,
532 static const EVP_CIPHER pk11_aes_256_cbc
=
538 pk11_cipher_do_cipher
,
540 sizeof (PK11_CIPHER_STATE
),
541 EVP_CIPHER_set_asn1_iv
,
542 EVP_CIPHER_get_asn1_iv
,
547 * ECB modes don't use IV so that's why set_asn1_parameters and
548 * get_asn1_parameters are set to NULL.
550 static const EVP_CIPHER pk11_aes_128_ecb
=
556 pk11_cipher_do_cipher
,
558 sizeof (PK11_CIPHER_STATE
),
564 static const EVP_CIPHER pk11_aes_192_ecb
=
570 pk11_cipher_do_cipher
,
572 sizeof (PK11_CIPHER_STATE
),
578 static const EVP_CIPHER pk11_aes_256_ecb
=
584 pk11_cipher_do_cipher
,
586 sizeof (PK11_CIPHER_STATE
),
592 #ifdef SOLARIS_AES_CTR
594 * NID_undef's will be changed to the AES counter mode NIDs as soon they are
595 * created in pk11_library_init(). Note that the need to change these structures
596 * is the reason why we don't define them with the const keyword.
598 static EVP_CIPHER pk11_aes_128_ctr
=
604 pk11_cipher_do_cipher
,
606 sizeof (PK11_CIPHER_STATE
),
607 EVP_CIPHER_set_asn1_iv
,
608 EVP_CIPHER_get_asn1_iv
,
612 static EVP_CIPHER pk11_aes_192_ctr
=
618 pk11_cipher_do_cipher
,
620 sizeof (PK11_CIPHER_STATE
),
621 EVP_CIPHER_set_asn1_iv
,
622 EVP_CIPHER_get_asn1_iv
,
626 static EVP_CIPHER pk11_aes_256_ctr
=
632 pk11_cipher_do_cipher
,
634 sizeof (PK11_CIPHER_STATE
),
635 EVP_CIPHER_set_asn1_iv
,
636 EVP_CIPHER_get_asn1_iv
,
639 #endif /* SOLARIS_AES_CTR */
641 static const EVP_CIPHER pk11_bf_cbc
=
645 EVP_CIPH_VARIABLE_LENGTH
,
647 pk11_cipher_do_cipher
,
649 sizeof (PK11_CIPHER_STATE
),
650 EVP_CIPHER_set_asn1_iv
,
651 EVP_CIPHER_get_asn1_iv
,
655 static const EVP_CIPHER pk11_rc4
=
659 EVP_CIPH_VARIABLE_LENGTH
,
661 pk11_cipher_do_cipher
,
663 sizeof (PK11_CIPHER_STATE
),
669 static const EVP_MD pk11_md5
=
672 NID_md5WithRSAEncryption
,
682 sizeof (PK11_CIPHER_STATE
),
685 static const EVP_MD pk11_sha1
=
688 NID_sha1WithRSAEncryption
,
698 sizeof (PK11_CIPHER_STATE
),
701 static const EVP_MD pk11_sha224
=
704 NID_sha224WithRSAEncryption
,
705 SHA224_DIGEST_LENGTH
,
713 /* SHA-224 uses the same cblock size as SHA-256 */
715 sizeof (PK11_CIPHER_STATE
),
718 static const EVP_MD pk11_sha256
=
721 NID_sha256WithRSAEncryption
,
722 SHA256_DIGEST_LENGTH
,
731 sizeof (PK11_CIPHER_STATE
),
734 static const EVP_MD pk11_sha384
=
737 NID_sha384WithRSAEncryption
,
738 SHA384_DIGEST_LENGTH
,
746 /* SHA-384 uses the same cblock size as SHA-512 */
748 sizeof (PK11_CIPHER_STATE
),
751 static const EVP_MD pk11_sha512
=
754 NID_sha512WithRSAEncryption
,
755 SHA512_DIGEST_LENGTH
,
764 sizeof (PK11_CIPHER_STATE
),
768 * Initialization function. Sets up various PKCS#11 library components.
769 * The definitions for control commands specific to this engine
771 #define PK11_CMD_SO_PATH ENGINE_CMD_BASE
772 static const ENGINE_CMD_DEFN pk11_cmd_defns
[] =
777 "Specifies the path to the 'pkcs#11' shared library",
778 ENGINE_CMD_FLAG_STRING
784 static RAND_METHOD pk11_random
=
795 /* Constants used when creating the ENGINE */
796 static const char *engine_pk11_id
= "pkcs11";
797 static const char *engine_pk11_name
= "PKCS #11 engine support";
799 CK_FUNCTION_LIST_PTR pFuncList
= NULL
;
800 static const char PK11_GET_FUNCTION_LIST
[] = "C_GetFunctionList";
803 * This is a static string constant for the DSO file name and the function
804 * symbol names to bind to. We set it in the Configure script based on whether
805 * this is 32 or 64 bit build.
807 static const char def_PK11_LIBNAME
[] = PK11_LIB_LOCATION
;
809 static CK_BBOOL pk11_true
= CK_TRUE
;
810 static CK_BBOOL pk11_false
= CK_FALSE
;
811 /* Needed in hw_pk11_pub.c as well so that's why it is not static. */
812 CK_SLOT_ID pubkey_SLOTID
= 0;
813 static CK_SLOT_ID rand_SLOTID
= 0;
814 static CK_SLOT_ID SLOTID
= 0;
815 static CK_BBOOL pk11_library_initialized
= CK_FALSE
;
816 static CK_BBOOL pk11_atfork_initialized
= CK_FALSE
;
817 static int pk11_pid
= 0;
819 static DSO
*pk11_dso
= NULL
;
821 /* allocate and initialize all locks used by the engine itself */
822 static int pk11_init_all_locks(void)
826 #ifndef OPENSSL_NO_RSA
827 find_lock
[OP_RSA
] = OPENSSL_malloc(sizeof (pthread_mutex_t
));
828 if (find_lock
[OP_RSA
] == NULL
)
830 (void) pthread_mutex_init(find_lock
[OP_RSA
], NULL
);
831 #endif /* OPENSSL_NO_RSA */
833 if ((uri_lock
= OPENSSL_malloc(sizeof (pthread_mutex_t
))) == NULL
)
835 (void) pthread_mutex_init(uri_lock
, NULL
);
837 #ifndef OPENSSL_NO_DSA
838 find_lock
[OP_DSA
] = OPENSSL_malloc(sizeof (pthread_mutex_t
));
839 if (find_lock
[OP_DSA
] == NULL
)
841 (void) pthread_mutex_init(find_lock
[OP_DSA
], NULL
);
842 #endif /* OPENSSL_NO_DSA */
844 #ifndef OPENSSL_NO_DH
845 find_lock
[OP_DH
] = OPENSSL_malloc(sizeof (pthread_mutex_t
));
846 if (find_lock
[OP_DH
] == NULL
)
848 (void) pthread_mutex_init(find_lock
[OP_DH
], NULL
);
849 #endif /* OPENSSL_NO_DH */
851 for (type
= 0; type
< OP_MAX
; type
++)
853 session_cache
[type
].lock
=
854 OPENSSL_malloc(sizeof (pthread_mutex_t
));
855 if (session_cache
[type
].lock
== NULL
)
857 (void) pthread_mutex_init(session_cache
[type
].lock
, NULL
);
863 pk11_free_all_locks();
864 PK11err(PK11_F_INIT_ALL_LOCKS
, PK11_R_MALLOC_FAILURE
);
868 static void pk11_free_all_locks(void)
872 #ifndef OPENSSL_NO_RSA
873 if (find_lock
[OP_RSA
] != NULL
)
875 (void) pthread_mutex_destroy(find_lock
[OP_RSA
]);
876 OPENSSL_free(find_lock
[OP_RSA
]);
877 find_lock
[OP_RSA
] = NULL
;
879 #endif /* OPENSSL_NO_RSA */
880 #ifndef OPENSSL_NO_DSA
881 if (find_lock
[OP_DSA
] != NULL
)
883 (void) pthread_mutex_destroy(find_lock
[OP_DSA
]);
884 OPENSSL_free(find_lock
[OP_DSA
]);
885 find_lock
[OP_DSA
] = NULL
;
887 #endif /* OPENSSL_NO_DSA */
888 #ifndef OPENSSL_NO_DH
889 if (find_lock
[OP_DH
] != NULL
)
891 (void) pthread_mutex_destroy(find_lock
[OP_DH
]);
892 OPENSSL_free(find_lock
[OP_DH
]);
893 find_lock
[OP_DH
] = NULL
;
895 #endif /* OPENSSL_NO_DH */
897 for (type
= 0; type
< OP_MAX
; type
++)
899 if (session_cache
[type
].lock
!= NULL
)
901 (void) pthread_mutex_destroy(session_cache
[type
].lock
);
902 OPENSSL_free(session_cache
[type
].lock
);
903 session_cache
[type
].lock
= NULL
;
909 * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
911 static int bind_pk11(ENGINE
*e
)
913 #ifndef OPENSSL_NO_RSA
914 const RSA_METHOD
*rsa
= NULL
;
915 RSA_METHOD
*pk11_rsa
= PK11_RSA();
916 #endif /* OPENSSL_NO_RSA */
917 if (!pk11_library_initialized
)
918 if (!pk11_library_init(e
))
921 if (!ENGINE_set_id(e
, engine_pk11_id
) ||
922 !ENGINE_set_name(e
, engine_pk11_name
) ||
923 !ENGINE_set_ciphers(e
, pk11_engine_ciphers
) ||
924 !ENGINE_set_digests(e
, pk11_engine_digests
))
926 #ifndef OPENSSL_NO_RSA
927 if (pk11_have_rsa
== CK_TRUE
)
929 if (!ENGINE_set_RSA(e
, PK11_RSA()) ||
930 !ENGINE_set_load_privkey_function(e
, pk11_load_privkey
) ||
931 !ENGINE_set_load_pubkey_function(e
, pk11_load_pubkey
))
933 #ifdef DEBUG_SLOT_SELECTION
934 fprintf(stderr
, "%s: registered RSA\n", PK11_DBG
);
935 #endif /* DEBUG_SLOT_SELECTION */
937 #endif /* OPENSSL_NO_RSA */
938 #ifndef OPENSSL_NO_DSA
939 if (pk11_have_dsa
== CK_TRUE
)
941 if (!ENGINE_set_DSA(e
, PK11_DSA()))
943 #ifdef DEBUG_SLOT_SELECTION
944 fprintf(stderr
, "%s: registered DSA\n", PK11_DBG
);
945 #endif /* DEBUG_SLOT_SELECTION */
947 #endif /* OPENSSL_NO_DSA */
948 #ifndef OPENSSL_NO_DH
949 if (pk11_have_dh
== CK_TRUE
)
951 if (!ENGINE_set_DH(e
, PK11_DH()))
953 #ifdef DEBUG_SLOT_SELECTION
954 fprintf(stderr
, "%s: registered DH\n", PK11_DBG
);
955 #endif /* DEBUG_SLOT_SELECTION */
957 #endif /* OPENSSL_NO_DH */
958 if (pk11_have_random
)
960 if (!ENGINE_set_RAND(e
, &pk11_random
))
962 #ifdef DEBUG_SLOT_SELECTION
963 fprintf(stderr
, "%s: registered random\n", PK11_DBG
);
964 #endif /* DEBUG_SLOT_SELECTION */
966 if (!ENGINE_set_init_function(e
, pk11_init
) ||
967 !ENGINE_set_destroy_function(e
, pk11_destroy
) ||
968 !ENGINE_set_finish_function(e
, pk11_finish
) ||
969 !ENGINE_set_ctrl_function(e
, pk11_ctrl
) ||
970 !ENGINE_set_cmd_defns(e
, pk11_cmd_defns
))
974 * Apache calls OpenSSL function RSA_blinding_on() once during startup
975 * which in turn calls bn_mod_exp. Since we do not implement bn_mod_exp
976 * here, we wire it back to the OpenSSL software implementation.
977 * Since it is used only once, performance is not a concern.
979 #ifndef OPENSSL_NO_RSA
980 rsa
= RSA_PKCS1_SSLeay();
981 pk11_rsa
->rsa_mod_exp
= rsa
->rsa_mod_exp
;
982 pk11_rsa
->bn_mod_exp
= rsa
->bn_mod_exp
;
983 #endif /* OPENSSL_NO_RSA */
985 /* Ensure the pk11 error handling is set up */
986 ERR_load_pk11_strings();
991 /* Dynamic engine support is disabled at a higher level for Solaris */
992 #ifdef ENGINE_DYNAMIC_SUPPORT
993 static int bind_helper(ENGINE
*e
, const char *id
)
995 if (id
&& (strcmp(id
, engine_pk11_id
) != 0))
1004 IMPLEMENT_DYNAMIC_CHECK_FN()
1005 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper
)
1008 static ENGINE
*engine_pk11(void)
1010 ENGINE
*ret
= ENGINE_new();
1015 if (!bind_pk11(ret
))
1025 ENGINE_load_pk11(void)
1027 ENGINE
*e_pk11
= NULL
;
1030 * Do not use dynamic PKCS#11 library on Solaris due to
1031 * security reasons. We will link it in statically.
1033 /* Attempt to load PKCS#11 library */
1035 pk11_dso
= DSO_load(NULL
, get_PK11_LIBNAME(), NULL
, 0);
1037 if (pk11_dso
== NULL
)
1039 PK11err(PK11_F_LOAD
, PK11_R_DSO_FAILURE
);
1043 e_pk11
= engine_pk11();
1052 * At this point, the pk11 shared library is either dynamically
1053 * loaded or statically linked in. So, initialize the pk11
1054 * library before calling ENGINE_set_default since the latter
1055 * needs cipher and digest algorithm information
1057 if (!pk11_library_init(e_pk11
))
1061 ENGINE_free(e_pk11
);
1067 ENGINE_free(e_pk11
);
1070 #endif /* ENGINE_DYNAMIC_SUPPORT */
1073 * These are the static string constants for the DSO file name and
1074 * the function symbol names to bind to.
1076 static const char *PK11_LIBNAME
= NULL
;
1078 static const char *get_PK11_LIBNAME(void)
1081 return (PK11_LIBNAME
);
1083 return (def_PK11_LIBNAME
);
1086 static void free_PK11_LIBNAME(void)
1089 OPENSSL_free((void*)PK11_LIBNAME
);
1091 PK11_LIBNAME
= NULL
;
1094 static long set_PK11_LIBNAME(const char *name
)
1096 free_PK11_LIBNAME();
1098 return ((PK11_LIBNAME
= BUF_strdup(name
)) != NULL
? 1 : 0);
1101 /* acquire all engine specific mutexes before fork */
1102 static void pk11_fork_prepare(void)
1106 if (!pk11_library_initialized
)
1109 LOCK_OBJSTORE(OP_RSA
);
1110 LOCK_OBJSTORE(OP_DSA
);
1111 LOCK_OBJSTORE(OP_DH
);
1112 (void) pthread_mutex_lock(uri_lock
);
1113 for (i
= 0; i
< OP_MAX
; i
++)
1115 (void) pthread_mutex_lock(session_cache
[i
].lock
);
1119 /* release all engine specific mutexes */
1120 static void pk11_fork_parent(void)
1124 if (!pk11_library_initialized
)
1127 for (i
= OP_MAX
- 1; i
>= 0; i
--)
1129 (void) pthread_mutex_unlock(session_cache
[i
].lock
);
1131 UNLOCK_OBJSTORE(OP_DH
);
1132 UNLOCK_OBJSTORE(OP_DSA
);
1133 UNLOCK_OBJSTORE(OP_RSA
);
1134 (void) pthread_mutex_unlock(uri_lock
);
1138 * same situation as in parent - we need to unlock all locks to make them
1139 * accessible to all threads.
1141 static void pk11_fork_child(void)
1145 if (!pk11_library_initialized
)
1148 for (i
= OP_MAX
- 1; i
>= 0; i
--)
1150 (void) pthread_mutex_unlock(session_cache
[i
].lock
);
1152 UNLOCK_OBJSTORE(OP_DH
);
1153 UNLOCK_OBJSTORE(OP_DSA
);
1154 UNLOCK_OBJSTORE(OP_RSA
);
1155 (void) pthread_mutex_unlock(uri_lock
);
1158 /* Initialization function for the pk11 engine */
1159 static int pk11_init(ENGINE
*e
)
1161 return (pk11_library_init(e
));
1165 * Initialization function. Sets up various PKCS#11 library components.
1166 * It selects a slot based on predefined critiera. In the process, it also
1167 * count how many ciphers and digests to support. Since the cipher and
1168 * digest information is needed when setting default engine, this function
1169 * needs to be called before calling ENGINE_set_default.
1172 static int pk11_library_init(ENGINE
*e
)
1174 CK_C_GetFunctionList p
;
1177 CK_ULONG ul_state_len
;
1182 * pk11_library_initialized is set to 0 in pk11_finish() which is called
1183 * from ENGINE_finish(). However, if there is still at least one
1184 * existing functional reference to the engine (see engine(3) for more
1185 * information), pk11_finish() is skipped. For example, this can happen
1186 * if an application forgets to clear one cipher context. In case of a
1187 * fork() when the application is finishing the engine so that it can be
1188 * reinitialized in the child, forgotten functional reference causes
1189 * pk11_library_initialized to stay 1. In that case we need the PID
1190 * check so that we properly initialize the engine again.
1192 if (pk11_library_initialized
)
1194 if (pk11_pid
== getpid())
1200 global_session
= CK_INVALID_HANDLE
;
1202 * free the locks first to prevent memory leak in case
1203 * the application calls fork() without finishing the
1206 pk11_free_all_locks();
1210 if (pk11_dso
== NULL
)
1212 PK11err(PK11_F_LIBRARY_INIT
, PK11_R_DSO_FAILURE
);
1216 #ifdef SOLARIS_AES_CTR
1218 * We must do this before we start working with slots since we need all
1221 if (pk11_add_aes_ctr_NIDs() == 0)
1223 #endif /* SOLARIS_AES_CTR */
1225 #ifdef SOLARIS_HW_SLOT_SELECTION
1226 if (check_hw_mechanisms() == 0)
1228 #endif /* SOLARIS_HW_SLOT_SELECTION */
1230 /* get the C_GetFunctionList function from the loaded library */
1231 p
= (CK_C_GetFunctionList
)DSO_bind_func(pk11_dso
,
1232 PK11_GET_FUNCTION_LIST
);
1235 PK11err(PK11_F_LIBRARY_INIT
, PK11_R_DSO_FAILURE
);
1239 /* get the full function list from the loaded library */
1243 PK11err_add_data(PK11_F_LIBRARY_INIT
, PK11_R_DSO_FAILURE
, rv
);
1247 rv
= pFuncList
->C_Initialize(NULL_PTR
);
1248 if ((rv
!= CKR_OK
) && (rv
!= CKR_CRYPTOKI_ALREADY_INITIALIZED
))
1250 PK11err_add_data(PK11_F_LIBRARY_INIT
, PK11_R_INITIALIZE
, rv
);
1254 rv
= pFuncList
->C_GetInfo(&info
);
1257 PK11err_add_data(PK11_F_LIBRARY_INIT
, PK11_R_GETINFO
, rv
);
1261 if (pk11_choose_slots(&any_slot_found
) == 0)
1265 * The library we use, set in def_PK11_LIBNAME, may not offer any
1266 * slot(s). In that case, we must not proceed but we must not return an
1267 * error. The reason is that applications that try to set up the PKCS#11
1268 * engine don't exit on error during the engine initialization just
1269 * because no slot was present.
1271 if (any_slot_found
== 0)
1274 if (global_session
== CK_INVALID_HANDLE
)
1276 /* Open the global_session for the new process */
1277 rv
= pFuncList
->C_OpenSession(SLOTID
, CKF_SERIAL_SESSION
,
1278 NULL_PTR
, NULL_PTR
, &global_session
);
1281 PK11err_add_data(PK11_F_LIBRARY_INIT
,
1282 PK11_R_OPENSESSION
, rv
);
1288 * Disable digest if C_GetOperationState is not supported since
1289 * this function is required by OpenSSL digest copy function
1291 if (pFuncList
->C_GetOperationState(global_session
, NULL
, &ul_state_len
)
1292 == CKR_FUNCTION_NOT_SUPPORTED
) {
1293 #ifdef DEBUG_SLOT_SELECTION
1294 fprintf(stderr
, "%s: C_GetOperationState() not supported, "
1295 "setting digest_count to 0\n", PK11_DBG
);
1296 #endif /* DEBUG_SLOT_SELECTION */
1300 pk11_library_initialized
= CK_TRUE
;
1301 pk11_pid
= getpid();
1303 * if initialization of the locks fails pk11_init_all_locks()
1304 * will do the cleanup.
1306 if (!pk11_init_all_locks())
1308 for (i
= 0; i
< OP_MAX
; i
++)
1309 session_cache
[i
].head
= NULL
;
1311 * initialize active lists. We only use active lists
1312 * for asymmetric ciphers.
1314 for (i
= 0; i
< OP_MAX
; i
++)
1315 active_list
[i
] = NULL
;
1317 if (!pk11_atfork_initialized
)
1319 if (pthread_atfork(pk11_fork_prepare
, pk11_fork_parent
,
1320 pk11_fork_child
) != 0)
1322 PK11err(PK11_F_LIBRARY_INIT
, PK11_R_ATFORK_FAILED
);
1325 pk11_atfork_initialized
= CK_TRUE
;
1334 /* Destructor (complements the "ENGINE_pk11()" constructor) */
1336 static int pk11_destroy(ENGINE
*e
)
1338 free_PK11_LIBNAME();
1339 ERR_unload_pk11_strings();
1344 * Termination function to clean up the session, the token, and the pk11
1348 static int pk11_finish(ENGINE
*e
)
1352 if (pk11_dso
== NULL
)
1354 PK11err(PK11_F_FINISH
, PK11_R_NOT_LOADED
);
1358 OPENSSL_assert(pFuncList
!= NULL
);
1360 if (pk11_free_all_sessions() == 0)
1363 /* free all active lists */
1364 for (i
= 0; i
< OP_MAX
; i
++)
1365 pk11_free_active_list(i
);
1367 pFuncList
->C_CloseSession(global_session
);
1368 global_session
= CK_INVALID_HANDLE
;
1371 * Since we are part of a library (libcrypto.so), calling this function
1372 * may have side-effects.
1375 pFuncList
->C_Finalize(NULL
);
1377 #ifdef SOLARIS_AES_CTR
1379 ASN1_OBJECT
*ob
= NULL
;
1380 if (NID_aes_128_ctr
!= NID_undef
) {
1381 ob
= OBJ_nid2obj(NID_aes_128_ctr
);
1383 ASN1_OBJECT_free(ob
);
1385 if (NID_aes_192_ctr
!= NID_undef
) {
1386 ob
= OBJ_nid2obj(NID_aes_192_ctr
);
1388 ASN1_OBJECT_free(ob
);
1390 if (NID_aes_256_ctr
!= NID_undef
) {
1391 ob
= OBJ_nid2obj(NID_aes_256_ctr
);
1393 ASN1_OBJECT_free(ob
);
1398 if (!DSO_free(pk11_dso
))
1400 PK11err(PK11_F_FINISH
, PK11_R_DSO_FAILURE
);
1405 pk11_library_initialized
= CK_FALSE
;
1408 * There is no way how to unregister atfork handlers (other than
1409 * unloading the library) so we just free the locks. For this reason
1410 * the atfork handlers check if the engine is initialized and bail out
1411 * immediately if not. This is necessary in case a process finishes
1412 * the engine before calling fork().
1414 pk11_free_all_locks();
1422 /* Standard engine interface function to set the dynamic library path */
1424 static int pk11_ctrl(ENGINE
*e
, int cmd
, long i
, void *p
, void (*f
)())
1426 int initialized
= ((pk11_dso
== NULL
) ? 0 : 1);
1430 case PK11_CMD_SO_PATH
:
1433 PK11err(PK11_F_CTRL
, ERR_R_PASSED_NULL_PARAMETER
);
1439 PK11err(PK11_F_CTRL
, PK11_R_ALREADY_LOADED
);
1443 return (set_PK11_LIBNAME((const char *)p
));
1448 PK11err(PK11_F_CTRL
, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED
);
1454 /* Required function by the engine random interface. It does nothing here */
1455 static void pk11_rand_cleanup(void)
1461 static void pk11_rand_add(const void *buf
, int num
, double add
)
1465 if ((sp
= pk11_get_session(OP_RAND
)) == NULL
)
1469 * Ignore any errors (e.g. CKR_RANDOM_SEED_NOT_SUPPORTED) since
1470 * the calling functions do not care anyway
1472 pFuncList
->C_SeedRandom(sp
->session
, (unsigned char *) buf
, num
);
1473 pk11_return_session(sp
, OP_RAND
);
1478 static void pk11_rand_seed(const void *buf
, int num
)
1480 pk11_rand_add(buf
, num
, 0);
1483 static int pk11_rand_bytes(unsigned char *buf
, int num
)
1488 if ((sp
= pk11_get_session(OP_RAND
)) == NULL
)
1491 rv
= pFuncList
->C_GenerateRandom(sp
->session
, buf
, num
);
1494 PK11err_add_data(PK11_F_RAND_BYTES
, PK11_R_GENERATERANDOM
, rv
);
1495 pk11_return_session(sp
, OP_RAND
);
1499 pk11_return_session(sp
, OP_RAND
);
1503 /* Required function by the engine random interface. It does nothing here */
1504 static int pk11_rand_status(void)
1509 /* Free all BIGNUM structures from PK11_SESSION. */
1510 static void pk11_free_nums(PK11_SESSION
*sp
, PK11_OPTYPE optype
)
1514 #ifndef OPENSSL_NO_RSA
1516 if (sp
->opdata_rsa_n_num
!= NULL
)
1518 BN_free(sp
->opdata_rsa_n_num
);
1519 sp
->opdata_rsa_n_num
= NULL
;
1521 if (sp
->opdata_rsa_e_num
!= NULL
)
1523 BN_free(sp
->opdata_rsa_e_num
);
1524 sp
->opdata_rsa_e_num
= NULL
;
1526 if (sp
->opdata_rsa_d_num
!= NULL
)
1528 BN_free(sp
->opdata_rsa_d_num
);
1529 sp
->opdata_rsa_d_num
= NULL
;
1533 #ifndef OPENSSL_NO_DSA
1535 if (sp
->opdata_dsa_pub_num
!= NULL
)
1537 BN_free(sp
->opdata_dsa_pub_num
);
1538 sp
->opdata_dsa_pub_num
= NULL
;
1540 if (sp
->opdata_dsa_priv_num
!= NULL
)
1542 BN_free(sp
->opdata_dsa_priv_num
);
1543 sp
->opdata_dsa_priv_num
= NULL
;
1547 #ifndef OPENSSL_NO_DH
1549 if (sp
->opdata_dh_priv_num
!= NULL
)
1551 BN_free(sp
->opdata_dh_priv_num
);
1552 sp
->opdata_dh_priv_num
= NULL
;
1562 * Get new PK11_SESSION structure ready for use. Every process must have
1563 * its own freelist of PK11_SESSION structures so handle fork() here
1564 * by destroying the old and creating new freelist.
1565 * The returned PK11_SESSION structure is disconnected from the freelist.
1568 pk11_get_session(PK11_OPTYPE optype
)
1570 PK11_SESSION
*sp
= NULL
, *sp1
, *freelist
;
1571 pthread_mutex_t
*freelist_lock
;
1572 static pid_t pid
= 0;
1584 freelist_lock
= session_cache
[optype
].lock
;
1587 PK11err(PK11_F_GET_SESSION
,
1588 PK11_R_INVALID_OPERATION_TYPE
);
1591 (void) pthread_mutex_lock(freelist_lock
);
1594 * Will use it to find out if we forked. We cannot use the PID field in
1595 * the session structure because we could get a newly allocated session
1596 * here, with no PID information.
1601 freelist
= session_cache
[optype
].head
;
1605 * If the free list is empty, allocate new unitialized (filled
1606 * with zeroes) PK11_SESSION structure otherwise return first
1607 * structure from the freelist.
1611 if ((sp
= OPENSSL_malloc(sizeof (PK11_SESSION
))) == NULL
)
1613 PK11err(PK11_F_GET_SESSION
,
1614 PK11_R_MALLOC_FAILURE
);
1617 (void) memset(sp
, 0, sizeof (PK11_SESSION
));
1620 * It is a new session so it will look like a cache miss to the
1621 * code below. So, we must not try to to destroy its members so
1622 * mark them as unused.
1624 sp
->opdata_rsa_priv_key
= CK_INVALID_HANDLE
;
1625 sp
->opdata_rsa_pub_key
= CK_INVALID_HANDLE
;
1628 freelist
= sp
->next
;
1631 * Check whether we have forked. In that case, we must get rid of all
1632 * inherited sessions and start allocating new ones.
1634 if (pid
!= (new_pid
= getpid()))
1639 * We are a new process and thus need to free any inherited
1640 * PK11_SESSION objects aside from the first session (sp) which
1641 * is the only PK11_SESSION structure we will reuse (for the
1642 * head of the list).
1644 while ((sp1
= freelist
) != NULL
)
1646 freelist
= sp1
->next
;
1648 * NOTE: we do not want to call pk11_free_all_sessions()
1649 * here because it would close underlying PKCS#11
1650 * sessions and destroy all objects.
1652 pk11_free_nums(sp1
, optype
);
1656 /* we have to free the active list as well. */
1657 pk11_free_active_list(optype
);
1659 /* Initialize the process */
1660 rv
= pFuncList
->C_Initialize(NULL_PTR
);
1661 if ((rv
!= CKR_OK
) && (rv
!= CKR_CRYPTOKI_ALREADY_INITIALIZED
))
1663 PK11err_add_data(PK11_F_GET_SESSION
, PK11_R_INITIALIZE
,
1671 * Choose slot here since the slot table is different on this
1672 * process. If we are here then we must have found at least one
1673 * usable slot before so we don't need to check any_slot_found.
1674 * See pk11_library_init()'s usage of this function for more
1677 #ifdef SOLARIS_HW_SLOT_SELECTION
1678 if (check_hw_mechanisms() == 0)
1680 #endif /* SOLARIS_HW_SLOT_SELECTION */
1681 if (pk11_choose_slots(NULL
) == 0)
1684 /* Open the global_session for the new process */
1685 rv
= pFuncList
->C_OpenSession(SLOTID
, CKF_SERIAL_SESSION
,
1686 NULL_PTR
, NULL_PTR
, &global_session
);
1689 PK11err_add_data(PK11_F_GET_SESSION
, PK11_R_OPENSESSION
,
1697 * It is an inherited session from our parent so it needs
1698 * re-initialization.
1700 if (pk11_setup_session(sp
, optype
) == 0)
1706 if (pk11_token_relogin(sp
->session
) == 0)
1709 * We will keep the session in the cache list and let
1710 * the caller cope with the situation.
1720 /* It is a new session and needs initialization. */
1721 if (pk11_setup_session(sp
, optype
) == 0)
1728 /* set new head for the list of PK11_SESSION objects */
1729 session_cache
[optype
].head
= freelist
;
1735 (void) pthread_mutex_unlock(freelist_lock
);
1742 pk11_return_session(PK11_SESSION
*sp
, PK11_OPTYPE optype
)
1744 pthread_mutex_t
*freelist_lock
;
1745 PK11_SESSION
*freelist
;
1748 * If this is a session from the parent it will be taken care of and
1749 * freed in pk11_get_session() as part of the post-fork clean up the
1750 * next time we will ask for a new session.
1752 if (sp
== NULL
|| sp
->pid
!= getpid())
1763 freelist_lock
= session_cache
[optype
].lock
;
1766 PK11err(PK11_F_RETURN_SESSION
,
1767 PK11_R_INVALID_OPERATION_TYPE
);
1771 (void) pthread_mutex_lock(freelist_lock
);
1772 freelist
= session_cache
[optype
].head
;
1773 sp
->next
= freelist
;
1774 session_cache
[optype
].head
= sp
;
1775 (void) pthread_mutex_unlock(freelist_lock
);
1779 /* Destroy all objects. This function is called when the engine is finished */
1780 static int pk11_free_all_sessions()
1785 #ifndef OPENSSL_NO_RSA
1786 (void) pk11_destroy_rsa_key_objects(NULL
);
1787 #endif /* OPENSSL_NO_RSA */
1788 #ifndef OPENSSL_NO_DSA
1789 (void) pk11_destroy_dsa_key_objects(NULL
);
1790 #endif /* OPENSSL_NO_DSA */
1791 #ifndef OPENSSL_NO_DH
1792 (void) pk11_destroy_dh_key_objects(NULL
);
1793 #endif /* OPENSSL_NO_DH */
1794 (void) pk11_destroy_cipher_key_objects(NULL
);
1797 * We try to release as much as we can but any error means that we will
1800 for (type
= 0; type
< OP_MAX
; type
++)
1802 if (pk11_free_session_list(type
) == 0)
1810 * Destroy session structures from the linked list specified. Free as many
1811 * sessions as possible but any failure in C_CloseSession() means that we
1812 * return an error on return.
1814 static int pk11_free_session_list(PK11_OPTYPE optype
)
1817 PK11_SESSION
*sp
= NULL
;
1818 PK11_SESSION
*freelist
= NULL
;
1819 pid_t mypid
= getpid();
1820 pthread_mutex_t
*freelist_lock
;
1831 freelist_lock
= session_cache
[optype
].lock
;
1834 PK11err(PK11_F_FREE_ALL_SESSIONS
,
1835 PK11_R_INVALID_OPERATION_TYPE
);
1839 (void) pthread_mutex_lock(freelist_lock
);
1840 freelist
= session_cache
[optype
].head
;
1841 while ((sp
= freelist
) != NULL
)
1843 if (sp
->session
!= CK_INVALID_HANDLE
&& sp
->pid
== mypid
)
1845 rv
= pFuncList
->C_CloseSession(sp
->session
);
1848 PK11err_add_data(PK11_F_FREE_ALL_SESSIONS
,
1849 PK11_R_CLOSESESSION
, rv
);
1853 freelist
= sp
->next
;
1854 pk11_free_nums(sp
, optype
);
1858 (void) pthread_mutex_unlock(freelist_lock
);
1864 pk11_setup_session(PK11_SESSION
*sp
, PK11_OPTYPE optype
)
1874 myslot
= pubkey_SLOTID
;
1877 myslot
= rand_SLOTID
;
1884 PK11err(PK11_F_SETUP_SESSION
,
1885 PK11_R_INVALID_OPERATION_TYPE
);
1889 sp
->session
= CK_INVALID_HANDLE
;
1890 #ifdef DEBUG_SLOT_SELECTION
1891 fprintf(stderr
, "%s: myslot=%d optype=%d\n", PK11_DBG
, myslot
, optype
);
1892 #endif /* DEBUG_SLOT_SELECTION */
1893 rv
= pFuncList
->C_OpenSession(myslot
, CKF_SERIAL_SESSION
,
1894 NULL_PTR
, NULL_PTR
, &sp
->session
);
1895 if (rv
== CKR_CRYPTOKI_NOT_INITIALIZED
)
1898 * We are probably a child process so force the
1899 * reinitialize of the session
1901 pk11_library_initialized
= CK_FALSE
;
1902 if (!pk11_library_init(NULL
))
1904 rv
= pFuncList
->C_OpenSession(myslot
, CKF_SERIAL_SESSION
,
1905 NULL_PTR
, NULL_PTR
, &sp
->session
);
1909 PK11err_add_data(PK11_F_SETUP_SESSION
, PK11_R_OPENSESSION
, rv
);
1917 #ifndef OPENSSL_NO_RSA
1919 sp
->opdata_rsa_pub_key
= CK_INVALID_HANDLE
;
1920 sp
->opdata_rsa_priv_key
= CK_INVALID_HANDLE
;
1921 sp
->opdata_rsa_pub
= NULL
;
1922 sp
->opdata_rsa_n_num
= NULL
;
1923 sp
->opdata_rsa_e_num
= NULL
;
1924 sp
->opdata_rsa_priv
= NULL
;
1925 sp
->opdata_rsa_d_num
= NULL
;
1927 #endif /* OPENSSL_NO_RSA */
1928 #ifndef OPENSSL_NO_DSA
1930 sp
->opdata_dsa_pub_key
= CK_INVALID_HANDLE
;
1931 sp
->opdata_dsa_priv_key
= CK_INVALID_HANDLE
;
1932 sp
->opdata_dsa_pub
= NULL
;
1933 sp
->opdata_dsa_pub_num
= NULL
;
1934 sp
->opdata_dsa_priv
= NULL
;
1935 sp
->opdata_dsa_priv_num
= NULL
;
1937 #endif /* OPENSSL_NO_DSA */
1938 #ifndef OPENSSL_NO_DH
1940 sp
->opdata_dh_key
= CK_INVALID_HANDLE
;
1941 sp
->opdata_dh
= NULL
;
1942 sp
->opdata_dh_priv_num
= NULL
;
1944 #endif /* OPENSSL_NO_DH */
1946 sp
->opdata_cipher_key
= CK_INVALID_HANDLE
;
1947 sp
->opdata_encrypt
= -1;
1952 * We always initialize the session as containing a non-persistent
1953 * object. The key load functions set it to persistent if that is so.
1955 sp
->persistent
= CK_FALSE
;
1959 #ifndef OPENSSL_NO_RSA
1961 * Destroy all non-NULL RSA parameters. For the RSA keys by reference code,
1962 * public components 'n'/'e' are the key components we use to check for the
1963 * cache hit even for the private keys. So, no matter whether we are destroying
1964 * a public or a private key, we always free what we can.
1967 destroy_all_rsa_params(PK11_SESSION
*sp
)
1969 if (sp
->opdata_rsa_n_num
!= NULL
)
1971 BN_free(sp
->opdata_rsa_n_num
);
1972 sp
->opdata_rsa_n_num
= NULL
;
1974 if (sp
->opdata_rsa_e_num
!= NULL
)
1976 BN_free(sp
->opdata_rsa_e_num
);
1977 sp
->opdata_rsa_e_num
= NULL
;
1979 if (sp
->opdata_rsa_d_num
!= NULL
)
1981 BN_free(sp
->opdata_rsa_d_num
);
1982 sp
->opdata_rsa_d_num
= NULL
;
1986 /* Destroy RSA public key from single session. */
1988 pk11_destroy_rsa_object_pub(PK11_SESSION
*sp
, CK_BBOOL uselock
)
1992 if (sp
->opdata_rsa_pub_key
!= CK_INVALID_HANDLE
)
1994 TRY_OBJ_DESTROY(sp
, sp
->opdata_rsa_pub_key
,
1995 ret
, uselock
, OP_RSA
);
1996 sp
->opdata_rsa_pub_key
= CK_INVALID_HANDLE
;
1997 sp
->opdata_rsa_pub
= NULL
;
1998 destroy_all_rsa_params(sp
);
2004 /* Destroy RSA private key from single session. */
2006 pk11_destroy_rsa_object_priv(PK11_SESSION
*sp
, CK_BBOOL uselock
)
2010 if (sp
->opdata_rsa_priv_key
!= CK_INVALID_HANDLE
)
2012 TRY_OBJ_DESTROY(sp
, sp
->opdata_rsa_priv_key
,
2013 ret
, uselock
, OP_RSA
);
2014 sp
->opdata_rsa_priv_key
= CK_INVALID_HANDLE
;
2015 sp
->opdata_rsa_priv
= NULL
;
2016 destroy_all_rsa_params(sp
);
2023 * Destroy RSA key object wrapper. If session is NULL, try to destroy all
2024 * objects in the free list.
2027 pk11_destroy_rsa_key_objects(PK11_SESSION
*session
)
2030 PK11_SESSION
*sp
= NULL
;
2031 PK11_SESSION
*local_free_session
;
2032 CK_BBOOL uselock
= CK_TRUE
;
2034 if (session
!= NULL
)
2035 local_free_session
= session
;
2038 (void) pthread_mutex_lock(session_cache
[OP_RSA
].lock
);
2039 local_free_session
= session_cache
[OP_RSA
].head
;
2044 * go through the list of sessions and delete key objects
2046 while ((sp
= local_free_session
) != NULL
)
2048 local_free_session
= sp
->next
;
2051 * Do not terminate list traversal if one of the
2052 * destroy operations fails.
2054 if (pk11_destroy_rsa_object_pub(sp
, uselock
) == 0)
2059 if (pk11_destroy_rsa_object_priv(sp
, uselock
) == 0)
2066 if (session
== NULL
)
2067 (void) pthread_mutex_unlock(session_cache
[OP_RSA
].lock
);
2071 #endif /* OPENSSL_NO_RSA */
2073 #ifndef OPENSSL_NO_DSA
2074 /* Destroy DSA public key from single session. */
2076 pk11_destroy_dsa_object_pub(PK11_SESSION
*sp
, CK_BBOOL uselock
)
2080 if (sp
->opdata_dsa_pub_key
!= CK_INVALID_HANDLE
)
2082 TRY_OBJ_DESTROY(sp
, sp
->opdata_dsa_pub_key
,
2083 ret
, uselock
, OP_DSA
);
2084 sp
->opdata_dsa_pub_key
= CK_INVALID_HANDLE
;
2085 sp
->opdata_dsa_pub
= NULL
;
2086 if (sp
->opdata_dsa_pub_num
!= NULL
)
2088 BN_free(sp
->opdata_dsa_pub_num
);
2089 sp
->opdata_dsa_pub_num
= NULL
;
2096 /* Destroy DSA private key from single session. */
2098 pk11_destroy_dsa_object_priv(PK11_SESSION
*sp
, CK_BBOOL uselock
)
2102 if (sp
->opdata_dsa_priv_key
!= CK_INVALID_HANDLE
)
2104 TRY_OBJ_DESTROY(sp
, sp
->opdata_dsa_priv_key
,
2105 ret
, uselock
, OP_DSA
);
2106 sp
->opdata_dsa_priv_key
= CK_INVALID_HANDLE
;
2107 sp
->opdata_dsa_priv
= NULL
;
2108 if (sp
->opdata_dsa_priv_num
!= NULL
)
2110 BN_free(sp
->opdata_dsa_priv_num
);
2111 sp
->opdata_dsa_priv_num
= NULL
;
2119 * Destroy DSA key object wrapper. If session is NULL, try to destroy all
2120 * objects in the free list.
2123 pk11_destroy_dsa_key_objects(PK11_SESSION
*session
)
2126 PK11_SESSION
*sp
= NULL
;
2127 PK11_SESSION
*local_free_session
;
2128 CK_BBOOL uselock
= CK_TRUE
;
2130 if (session
!= NULL
)
2131 local_free_session
= session
;
2134 (void) pthread_mutex_lock(session_cache
[OP_DSA
].lock
);
2135 local_free_session
= session_cache
[OP_DSA
].head
;
2140 * go through the list of sessions and delete key objects
2142 while ((sp
= local_free_session
) != NULL
)
2144 local_free_session
= sp
->next
;
2147 * Do not terminate list traversal if one of the
2148 * destroy operations fails.
2150 if (pk11_destroy_dsa_object_pub(sp
, uselock
) == 0)
2155 if (pk11_destroy_dsa_object_priv(sp
, uselock
) == 0)
2162 if (session
== NULL
)
2163 (void) pthread_mutex_unlock(session_cache
[OP_DSA
].lock
);
2167 #endif /* OPENSSL_NO_DSA */
2169 #ifndef OPENSSL_NO_DH
2170 /* Destroy DH key from single session. */
2172 pk11_destroy_dh_object(PK11_SESSION
*sp
, CK_BBOOL uselock
)
2176 if (sp
->opdata_dh_key
!= CK_INVALID_HANDLE
)
2178 TRY_OBJ_DESTROY(sp
, sp
->opdata_dh_key
,
2179 ret
, uselock
, OP_DH
);
2180 sp
->opdata_dh_key
= CK_INVALID_HANDLE
;
2181 sp
->opdata_dh
= NULL
;
2182 if (sp
->opdata_dh_priv_num
!= NULL
)
2184 BN_free(sp
->opdata_dh_priv_num
);
2185 sp
->opdata_dh_priv_num
= NULL
;
2193 * Destroy DH key object wrapper.
2195 * arg0: pointer to PKCS#11 engine session structure
2196 * if session is NULL, try to destroy all objects in the free list
2199 pk11_destroy_dh_key_objects(PK11_SESSION
*session
)
2202 PK11_SESSION
*sp
= NULL
;
2203 PK11_SESSION
*local_free_session
;
2204 CK_BBOOL uselock
= CK_TRUE
;
2206 if (session
!= NULL
)
2207 local_free_session
= session
;
2210 (void) pthread_mutex_lock(session_cache
[OP_DH
].lock
);
2211 local_free_session
= session_cache
[OP_DH
].head
;
2215 while ((sp
= local_free_session
) != NULL
)
2217 local_free_session
= sp
->next
;
2220 * Do not terminate list traversal if one of the
2221 * destroy operations fails.
2223 if (pk11_destroy_dh_object(sp
, uselock
) == 0)
2230 if (session
== NULL
)
2231 (void) pthread_mutex_unlock(session_cache
[OP_DH
].lock
);
2235 #endif /* OPENSSL_NO_DH */
2238 pk11_destroy_object(CK_SESSION_HANDLE session
, CK_OBJECT_HANDLE oh
,
2239 CK_BBOOL persistent
)
2244 * We never try to destroy persistent objects which are the objects
2245 * stored in the keystore. Also, we always use read-only sessions so
2246 * C_DestroyObject() would be returning CKR_SESSION_READ_ONLY here.
2248 if (persistent
== CK_TRUE
)
2251 rv
= pFuncList
->C_DestroyObject(session
, oh
);
2254 PK11err_add_data(PK11_F_DESTROY_OBJECT
, PK11_R_DESTROYOBJECT
,
2263 /* Symmetric ciphers and digests support functions */
2266 cipher_nid_to_pk11(int nid
)
2270 for (i
= 0; i
< PK11_CIPHER_MAX
; i
++)
2271 if (ciphers
[i
].nid
== nid
)
2272 return (ciphers
[i
].id
);
2277 pk11_usable_ciphers(const int **nids
)
2279 if (cipher_count
> 0)
2280 *nids
= cipher_nids
;
2283 return (cipher_count
);
2287 pk11_usable_digests(const int **nids
)
2289 if (digest_count
> 0)
2290 *nids
= digest_nids
;
2293 return (digest_count
);
2297 * Init context for encryption or decryption using a symmetric key.
2299 static int pk11_init_symmetric(EVP_CIPHER_CTX
*ctx
, PK11_CIPHER
*pcipher
,
2300 PK11_SESSION
*sp
, CK_MECHANISM_PTR pmech
)
2303 #ifdef SOLARIS_AES_CTR
2304 CK_AES_CTR_PARAMS ctr_params
;
2305 #endif /* SOLARIS_AES_CTR */
2308 * We expect pmech->mechanism to be already set and
2309 * pParameter/ulParameterLen initialized to NULL/0 before
2310 * pk11_init_symetric() is called.
2312 OPENSSL_assert(pmech
->mechanism
!= NULL
);
2313 OPENSSL_assert(pmech
->pParameter
== NULL
);
2314 OPENSSL_assert(pmech
->ulParameterLen
== 0);
2316 #ifdef SOLARIS_AES_CTR
2317 if (ctx
->cipher
->nid
== NID_aes_128_ctr
||
2318 ctx
->cipher
->nid
== NID_aes_192_ctr
||
2319 ctx
->cipher
->nid
== NID_aes_256_ctr
)
2321 pmech
->pParameter
= (void *)(&ctr_params
);
2322 pmech
->ulParameterLen
= sizeof (ctr_params
);
2324 * For now, we are limited to the fixed length of the counter,
2325 * it covers the whole counter block. That's what RFC 4344
2326 * needs. For more information on internal structure of the
2327 * counter block, see RFC 3686. If needed in the future, we can
2328 * add code so that the counter length can be set via
2329 * ENGINE_ctrl() function.
2331 ctr_params
.ulCounterBits
= AES_BLOCK_SIZE
* 8;
2332 OPENSSL_assert(pcipher
->iv_len
== AES_BLOCK_SIZE
);
2333 (void) memcpy(ctr_params
.cb
, ctx
->iv
, AES_BLOCK_SIZE
);
2336 #endif /* SOLARIS_AES_CTR */
2338 if (pcipher
->iv_len
> 0)
2340 pmech
->pParameter
= (void *)ctx
->iv
;
2341 pmech
->ulParameterLen
= pcipher
->iv_len
;
2345 /* if we get here, the encryption needs to be reinitialized */
2347 rv
= pFuncList
->C_EncryptInit(sp
->session
, pmech
,
2348 sp
->opdata_cipher_key
);
2350 rv
= pFuncList
->C_DecryptInit(sp
->session
, pmech
,
2351 sp
->opdata_cipher_key
);
2355 PK11err_add_data(PK11_F_CIPHER_INIT
, ctx
->encrypt
?
2356 PK11_R_ENCRYPTINIT
: PK11_R_DECRYPTINIT
, rv
);
2357 pk11_return_session(sp
, OP_CIPHER
);
2366 pk11_cipher_init(EVP_CIPHER_CTX
*ctx
, const unsigned char *key
,
2367 const unsigned char *iv
, int enc
)
2371 PK11_CIPHER_STATE
*state
= (PK11_CIPHER_STATE
*) ctx
->cipher_data
;
2373 PK11_CIPHER
*p_ciph_table_row
;
2377 index
= cipher_nid_to_pk11(ctx
->cipher
->nid
);
2378 if (index
< 0 || index
>= PK11_CIPHER_MAX
)
2381 p_ciph_table_row
= &ciphers
[index
];
2383 * iv_len in the ctx->cipher structure is the maximum IV length for the
2384 * current cipher and it must be less or equal to the IV length in our
2385 * ciphers table. The key length must be in the allowed interval. From
2386 * all cipher modes that the PKCS#11 engine supports only RC4 allows a
2387 * key length to be in some range, all other NIDs have a precise key
2388 * length. Every application can define its own EVP functions so this
2389 * code serves as a sanity check.
2391 * Note that the reason why the IV length in ctx->cipher might be
2392 * greater than the actual length is that OpenSSL uses BLOCK_CIPHER_defs
2393 * macro to define functions that return EVP structures for all DES
2394 * modes. So, even ECB modes get 8 byte IV.
2396 if (ctx
->cipher
->iv_len
< p_ciph_table_row
->iv_len
||
2397 ctx
->key_len
< p_ciph_table_row
->min_key_len
||
2398 ctx
->key_len
> p_ciph_table_row
->max_key_len
) {
2399 PK11err(PK11_F_CIPHER_INIT
, PK11_R_KEY_OR_IV_LEN_PROBLEM
);
2403 if ((sp
= pk11_get_session(OP_CIPHER
)) == NULL
)
2406 /* if applicable, the mechanism parameter is used for IV */
2407 mech
.mechanism
= p_ciph_table_row
->mech_type
;
2408 mech
.pParameter
= NULL
;
2409 mech
.ulParameterLen
= 0;
2411 /* The key object is destroyed here if it is not the current key. */
2412 (void) check_new_cipher_key(sp
, key
, ctx
->key_len
);
2415 * If the key is the same and the encryption is also the same, then
2416 * just reuse it. However, we must not forget to reinitialize the
2417 * context that was finalized in pk11_cipher_cleanup().
2419 if (sp
->opdata_cipher_key
!= CK_INVALID_HANDLE
&&
2420 sp
->opdata_encrypt
== ctx
->encrypt
)
2423 if (pk11_init_symmetric(ctx
, p_ciph_table_row
, sp
, &mech
) == 0)
2430 * Check if the key has been invalidated. If so, a new key object
2431 * needs to be created.
2433 if (sp
->opdata_cipher_key
== CK_INVALID_HANDLE
)
2435 sp
->opdata_cipher_key
= pk11_get_cipher_key(
2436 ctx
, key
, p_ciph_table_row
->key_type
, sp
);
2439 if (sp
->opdata_encrypt
!= ctx
->encrypt
&& sp
->opdata_encrypt
!= -1)
2442 * The previous encryption/decryption is different. Need to
2443 * terminate the previous * active encryption/decryption here.
2445 if (!pk11_cipher_final(sp
))
2447 pk11_return_session(sp
, OP_CIPHER
);
2452 if (sp
->opdata_cipher_key
== CK_INVALID_HANDLE
)
2454 pk11_return_session(sp
, OP_CIPHER
);
2458 /* now initialize the context with a new key */
2459 if (pk11_init_symmetric(ctx
, p_ciph_table_row
, sp
, &mech
) == 0)
2462 sp
->opdata_encrypt
= ctx
->encrypt
;
2469 * When reusing the same key in an encryption/decryption session for a
2470 * decryption/encryption session, we need to close the active session
2471 * and recreate a new one. Note that the key is in the global session so
2472 * that it needs not be recreated.
2474 * It is more appropriate to use C_En/DecryptFinish here. At the time of this
2475 * development, these two functions in the PKCS#11 libraries used return
2476 * unexpected errors when passing in 0 length output. It may be a good
2477 * idea to try them again if performance is a problem here and fix
2478 * C_En/DecryptFinial if there are bugs there causing the problem.
2481 pk11_cipher_final(PK11_SESSION
*sp
)
2485 rv
= pFuncList
->C_CloseSession(sp
->session
);
2488 PK11err_add_data(PK11_F_CIPHER_FINAL
, PK11_R_CLOSESESSION
, rv
);
2492 rv
= pFuncList
->C_OpenSession(SLOTID
, CKF_SERIAL_SESSION
,
2493 NULL_PTR
, NULL_PTR
, &sp
->session
);
2496 PK11err_add_data(PK11_F_CIPHER_FINAL
, PK11_R_OPENSESSION
, rv
);
2504 * An engine interface function. The calling function allocates sufficient
2505 * memory for the output buffer "out" to hold the results.
2508 pk11_cipher_do_cipher(EVP_CIPHER_CTX
*ctx
, unsigned char *out
,
2509 const unsigned char *in
, unsigned int inl
)
2511 PK11_CIPHER_STATE
*state
= (PK11_CIPHER_STATE
*) ctx
->cipher_data
;
2514 unsigned long outl
= inl
;
2516 if (state
== NULL
|| state
->sp
== NULL
)
2519 sp
= (PK11_SESSION
*) state
->sp
;
2524 /* RC4 is the only stream cipher we support */
2525 if (ctx
->cipher
->nid
!= NID_rc4
&& (inl
% ctx
->cipher
->block_size
) != 0)
2530 rv
= pFuncList
->C_EncryptUpdate(sp
->session
,
2531 (unsigned char *)in
, inl
, out
, &outl
);
2535 PK11err_add_data(PK11_F_CIPHER_DO_CIPHER
,
2536 PK11_R_ENCRYPTUPDATE
, rv
);
2542 rv
= pFuncList
->C_DecryptUpdate(sp
->session
,
2543 (unsigned char *)in
, inl
, out
, &outl
);
2547 PK11err_add_data(PK11_F_CIPHER_DO_CIPHER
,
2548 PK11_R_DECRYPTUPDATE
, rv
);
2554 * For DES_CBC, DES3_CBC, AES_CBC, and RC4, the output size is always
2555 * the same size of input.
2556 * The application has guaranteed to call the block ciphers with
2557 * correctly aligned buffers.
2566 * Return the session to the pool. Calling C_EncryptFinal() and C_DecryptFinal()
2567 * here is the right thing because in EVP_DecryptFinal_ex(), engine's
2568 * do_cipher() is not even called, and in EVP_EncryptFinal_ex() it is called but
2569 * the engine can't find out that it's the finalizing call. We wouldn't
2570 * necessarily have to finalize the context here since reinitializing it with
2571 * C_(Encrypt|Decrypt)Init() should be fine but for the sake of correctness,
2572 * let's do it. Some implementations might leak memory if the previously used
2573 * context is initialized without finalizing it first.
2576 pk11_cipher_cleanup(EVP_CIPHER_CTX
*ctx
)
2579 CK_ULONG len
= EVP_MAX_BLOCK_LENGTH
;
2580 CK_BYTE buf
[EVP_MAX_BLOCK_LENGTH
];
2581 PK11_CIPHER_STATE
*state
= ctx
->cipher_data
;
2583 if (state
!= NULL
&& state
->sp
!= NULL
)
2586 * We are not interested in the data here, we just need to get
2587 * rid of the context.
2590 rv
= pFuncList
->C_EncryptFinal(
2591 state
->sp
->session
, buf
, &len
);
2593 rv
= pFuncList
->C_DecryptFinal(
2594 state
->sp
->session
, buf
, &len
);
2598 PK11err_add_data(PK11_F_CIPHER_CLEANUP
, ctx
->encrypt
?
2599 PK11_R_ENCRYPTFINAL
: PK11_R_DECRYPTFINAL
, rv
);
2600 pk11_return_session(state
->sp
, OP_CIPHER
);
2604 pk11_return_session(state
->sp
, OP_CIPHER
);
2612 * Registered by the ENGINE when used to find out how to deal with
2613 * a particular NID in the ENGINE. This says what we'll do at the
2614 * top level - note, that list is restricted by what we answer with
2618 pk11_engine_ciphers(ENGINE
*e
, const EVP_CIPHER
**cipher
,
2619 const int **nids
, int nid
)
2622 return (pk11_usable_ciphers(nids
));
2626 case NID_des_ede3_cbc
:
2627 *cipher
= &pk11_3des_cbc
;
2630 *cipher
= &pk11_des_cbc
;
2632 case NID_des_ede3_ecb
:
2633 *cipher
= &pk11_3des_ecb
;
2636 *cipher
= &pk11_des_ecb
;
2638 case NID_aes_128_cbc
:
2639 *cipher
= &pk11_aes_128_cbc
;
2641 case NID_aes_192_cbc
:
2642 *cipher
= &pk11_aes_192_cbc
;
2644 case NID_aes_256_cbc
:
2645 *cipher
= &pk11_aes_256_cbc
;
2647 case NID_aes_128_ecb
:
2648 *cipher
= &pk11_aes_128_ecb
;
2650 case NID_aes_192_ecb
:
2651 *cipher
= &pk11_aes_192_ecb
;
2653 case NID_aes_256_ecb
:
2654 *cipher
= &pk11_aes_256_ecb
;
2657 *cipher
= &pk11_bf_cbc
;
2660 *cipher
= &pk11_rc4
;
2663 #ifdef SOLARIS_AES_CTR
2665 * These can't be in separated cases because the NIDs
2666 * here are not constants.
2668 if (nid
== NID_aes_128_ctr
)
2669 *cipher
= &pk11_aes_128_ctr
;
2670 else if (nid
== NID_aes_192_ctr
)
2671 *cipher
= &pk11_aes_192_ctr
;
2672 else if (nid
== NID_aes_256_ctr
)
2673 *cipher
= &pk11_aes_256_ctr
;
2675 #endif /* SOLARIS_AES_CTR */
2679 return (*cipher
!= NULL
);
2684 pk11_engine_digests(ENGINE
*e
, const EVP_MD
**digest
,
2685 const int **nids
, int nid
)
2688 return (pk11_usable_digests(nids
));
2693 *digest
= &pk11_md5
;
2696 *digest
= &pk11_sha1
;
2699 *digest
= &pk11_sha224
;
2702 *digest
= &pk11_sha256
;
2705 *digest
= &pk11_sha384
;
2708 *digest
= &pk11_sha512
;
2714 return (*digest
!= NULL
);
2718 /* Create a secret key object in a PKCS#11 session */
2719 static CK_OBJECT_HANDLE
pk11_get_cipher_key(EVP_CIPHER_CTX
*ctx
,
2720 const unsigned char *key
, CK_KEY_TYPE key_type
, PK11_SESSION
*sp
)
2723 CK_OBJECT_HANDLE h_key
= CK_INVALID_HANDLE
;
2724 CK_OBJECT_CLASS obj_key
= CKO_SECRET_KEY
;
2725 CK_ULONG ul_key_attr_count
= 6;
2727 CK_ATTRIBUTE a_key_template
[] =
2729 {CKA_CLASS
, (void*) NULL
, sizeof (CK_OBJECT_CLASS
)},
2730 {CKA_KEY_TYPE
, (void*) NULL
, sizeof (CK_KEY_TYPE
)},
2731 {CKA_TOKEN
, &pk11_false
, sizeof (pk11_false
)},
2732 {CKA_ENCRYPT
, &pk11_true
, sizeof (pk11_true
)},
2733 {CKA_DECRYPT
, &pk11_true
, sizeof (pk11_true
)},
2734 {CKA_VALUE
, (void*) NULL
, 0},
2738 * Create secret key object in global_session. All other sessions
2739 * can use the key handles. Here is why:
2740 * OpenSSL will call EncryptInit and EncryptUpdate using a secret key.
2741 * It may then call DecryptInit and DecryptUpdate using the same key.
2742 * To use the same key object, we need to call EncryptFinal with
2743 * a 0 length message. Currently, this does not work for 3DES
2744 * mechanism. To get around this problem, we close the session and
2745 * then create a new session to use the same key object. When a session
2746 * is closed, all the object handles will be invalid. Thus, create key
2747 * objects in a global session, an individual session may be closed to
2748 * terminate the active operation.
2750 CK_SESSION_HANDLE session
= global_session
;
2751 a_key_template
[0].pValue
= &obj_key
;
2752 a_key_template
[1].pValue
= &key_type
;
2753 a_key_template
[5].pValue
= (void *) key
;
2754 a_key_template
[5].ulValueLen
= (unsigned long) ctx
->key_len
;
2756 rv
= pFuncList
->C_CreateObject(session
,
2757 a_key_template
, ul_key_attr_count
, &h_key
);
2760 PK11err_add_data(PK11_F_GET_CIPHER_KEY
, PK11_R_CREATEOBJECT
,
2766 * Save the key information used in this session.
2767 * The max can be saved is PK11_KEY_LEN_MAX.
2769 sp
->opdata_key_len
= ctx
->key_len
> PK11_KEY_LEN_MAX
?
2770 PK11_KEY_LEN_MAX
: ctx
->key_len
;
2771 (void) memcpy(sp
->opdata_key
, key
, sp
->opdata_key_len
);
2778 md_nid_to_pk11(int nid
)
2782 for (i
= 0; i
< PK11_DIGEST_MAX
; i
++)
2783 if (digests
[i
].nid
== nid
)
2784 return (digests
[i
].id
);
2789 pk11_digest_init(EVP_MD_CTX
*ctx
)
2796 PK11_CIPHER_STATE
*state
= (PK11_CIPHER_STATE
*) ctx
->md_data
;
2800 index
= md_nid_to_pk11(ctx
->digest
->type
);
2801 if (index
< 0 || index
>= PK11_DIGEST_MAX
)
2804 pdp
= &digests
[index
];
2805 if ((sp
= pk11_get_session(OP_DIGEST
)) == NULL
)
2808 /* at present, no parameter is needed for supported digests */
2809 mech
.mechanism
= pdp
->mech_type
;
2810 mech
.pParameter
= NULL
;
2811 mech
.ulParameterLen
= 0;
2813 rv
= pFuncList
->C_DigestInit(sp
->session
, &mech
);
2817 PK11err_add_data(PK11_F_DIGEST_INIT
, PK11_R_DIGESTINIT
, rv
);
2818 pk11_return_session(sp
, OP_DIGEST
);
2828 pk11_digest_update(EVP_MD_CTX
*ctx
, const void *data
, size_t count
)
2831 PK11_CIPHER_STATE
*state
= (PK11_CIPHER_STATE
*) ctx
->md_data
;
2833 /* 0 length message will cause a failure in C_DigestFinal */
2837 if (state
== NULL
|| state
->sp
== NULL
)
2840 rv
= pFuncList
->C_DigestUpdate(state
->sp
->session
, (CK_BYTE
*) data
,
2845 PK11err_add_data(PK11_F_DIGEST_UPDATE
, PK11_R_DIGESTUPDATE
, rv
);
2846 pk11_return_session(state
->sp
, OP_DIGEST
);
2855 pk11_digest_final(EVP_MD_CTX
*ctx
, unsigned char *md
)
2859 PK11_CIPHER_STATE
*state
= (PK11_CIPHER_STATE
*) ctx
->md_data
;
2860 len
= ctx
->digest
->md_size
;
2862 if (state
== NULL
|| state
->sp
== NULL
)
2865 rv
= pFuncList
->C_DigestFinal(state
->sp
->session
, md
, &len
);
2869 PK11err_add_data(PK11_F_DIGEST_FINAL
, PK11_R_DIGESTFINAL
, rv
);
2870 pk11_return_session(state
->sp
, OP_DIGEST
);
2875 if (ctx
->digest
->md_size
!= len
)
2879 * Final is called and digest is returned, so return the session
2882 pk11_return_session(state
->sp
, OP_DIGEST
);
2889 pk11_digest_copy(EVP_MD_CTX
*to
, const EVP_MD_CTX
*from
)
2893 PK11_CIPHER_STATE
*state
, *state_to
;
2894 CK_BYTE_PTR pstate
= NULL
;
2895 CK_ULONG ul_state_len
;
2897 /* The copy-from state */
2898 state
= (PK11_CIPHER_STATE
*) from
->md_data
;
2899 if (state
== NULL
|| state
->sp
== NULL
)
2902 /* Initialize the copy-to state */
2903 if (!pk11_digest_init(to
))
2905 state_to
= (PK11_CIPHER_STATE
*) to
->md_data
;
2907 /* Get the size of the operation state of the copy-from session */
2908 rv
= pFuncList
->C_GetOperationState(state
->sp
->session
, NULL
,
2913 PK11err_add_data(PK11_F_DIGEST_COPY
, PK11_R_GET_OPERATION_STATE
,
2917 if (ul_state_len
== 0)
2922 pstate
= OPENSSL_malloc(ul_state_len
);
2925 PK11err(PK11_F_DIGEST_COPY
, PK11_R_MALLOC_FAILURE
);
2929 /* Get the operation state of the copy-from session */
2930 rv
= pFuncList
->C_GetOperationState(state
->sp
->session
, pstate
,
2935 PK11err_add_data(PK11_F_DIGEST_COPY
, PK11_R_GET_OPERATION_STATE
,
2940 /* Set the operation state of the copy-to session */
2941 rv
= pFuncList
->C_SetOperationState(state_to
->sp
->session
, pstate
,
2942 ul_state_len
, 0, 0);
2946 PK11err_add_data(PK11_F_DIGEST_COPY
,
2947 PK11_R_SET_OPERATION_STATE
, rv
);
2954 OPENSSL_free(pstate
);
2959 /* Return any pending session state to the pool */
2961 pk11_digest_cleanup(EVP_MD_CTX
*ctx
)
2963 PK11_CIPHER_STATE
*state
= ctx
->md_data
;
2964 unsigned char buf
[EVP_MAX_MD_SIZE
];
2966 if (state
!= NULL
&& state
->sp
!= NULL
)
2969 * If state->sp is not NULL then pk11_digest_final() has not
2970 * been called yet. We must call it now to free any memory
2971 * that might have been allocated in the token when
2972 * pk11_digest_init() was called. pk11_digest_final()
2973 * will return the session to the cache.
2975 if (!pk11_digest_final(ctx
, buf
))
2983 * Check if the new key is the same as the key object in the session. If the key
2984 * is the same, no need to create a new key object. Otherwise, the old key
2985 * object needs to be destroyed and a new one will be created. Return 1 for
2986 * cache hit, 0 for cache miss. Note that we must check the key length first
2987 * otherwise we could end up reusing a different, longer key with the same
2990 static int check_new_cipher_key(PK11_SESSION
*sp
, const unsigned char *key
,
2993 if (sp
->opdata_key_len
!= key_len
||
2994 memcmp(sp
->opdata_key
, key
, key_len
) != 0)
2996 (void) pk11_destroy_cipher_key_objects(sp
);
3002 /* Destroy one or more secret key objects. */
3003 static int pk11_destroy_cipher_key_objects(PK11_SESSION
*session
)
3006 PK11_SESSION
*sp
= NULL
;
3007 PK11_SESSION
*local_free_session
;
3009 if (session
!= NULL
)
3010 local_free_session
= session
;
3013 (void) pthread_mutex_lock(session_cache
[OP_CIPHER
].lock
);
3014 local_free_session
= session_cache
[OP_CIPHER
].head
;
3017 while ((sp
= local_free_session
) != NULL
)
3019 local_free_session
= sp
->next
;
3021 if (sp
->opdata_cipher_key
!= CK_INVALID_HANDLE
)
3024 * The secret key object is created in the
3025 * global_session. See pk11_get_cipher_key().
3027 if (pk11_destroy_object(global_session
,
3028 sp
->opdata_cipher_key
, CK_FALSE
) == 0)
3030 sp
->opdata_cipher_key
= CK_INVALID_HANDLE
;
3036 if (session
== NULL
)
3037 (void) pthread_mutex_unlock(session_cache
[OP_CIPHER
].lock
);
3044 * Public key mechanisms optionally supported
3050 * The first slot that supports at least one of those mechanisms is chosen as a
3053 * Symmetric ciphers optionally supported
3065 * Digests optionally supported
3074 * The output of this function is a set of global variables indicating which
3075 * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
3076 * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
3077 * variables carry information about which slot was chosen for (a) public key
3078 * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
3081 pk11_choose_slots(int *any_slot_found
)
3083 CK_SLOT_ID_PTR pSlotList
= NULL_PTR
;
3084 CK_ULONG ulSlotCount
= 0;
3085 CK_MECHANISM_INFO mech_info
;
3086 CK_TOKEN_INFO token_info
;
3089 CK_SLOT_ID best_slot_sofar
;
3090 CK_BBOOL found_candidate_slot
= CK_FALSE
;
3091 int slot_n_cipher
= 0;
3092 int slot_n_digest
= 0;
3093 CK_SLOT_ID current_slot
= 0;
3094 int current_slot_n_cipher
= 0;
3095 int current_slot_n_digest
= 0;
3097 int local_cipher_nids
[PK11_CIPHER_MAX
];
3098 int local_digest_nids
[PK11_DIGEST_MAX
];
3100 /* let's initialize the output parameter */
3101 if (any_slot_found
!= NULL
)
3102 *any_slot_found
= 0;
3104 /* Get slot list for memory allocation */
3105 rv
= pFuncList
->C_GetSlotList(CK_FALSE
, NULL_PTR
, &ulSlotCount
);
3109 PK11err_add_data(PK11_F_CHOOSE_SLOT
, PK11_R_GETSLOTLIST
, rv
);
3113 /* it's not an error if we didn't find any providers */
3114 if (ulSlotCount
== 0)
3116 #ifdef DEBUG_SLOT_SELECTION
3117 fprintf(stderr
, "%s: no crypto providers found\n", PK11_DBG
);
3118 #endif /* DEBUG_SLOT_SELECTION */
3122 pSlotList
= OPENSSL_malloc(ulSlotCount
* sizeof (CK_SLOT_ID
));
3124 if (pSlotList
== NULL
)
3126 PK11err(PK11_F_CHOOSE_SLOT
, PK11_R_MALLOC_FAILURE
);
3130 /* Get the slot list for processing */
3131 rv
= pFuncList
->C_GetSlotList(CK_FALSE
, pSlotList
, &ulSlotCount
);
3134 PK11err_add_data(PK11_F_CHOOSE_SLOT
, PK11_R_GETSLOTLIST
, rv
);
3135 OPENSSL_free(pSlotList
);
3139 #ifdef DEBUG_SLOT_SELECTION
3140 fprintf(stderr
, "%s: provider: %s\n", PK11_DBG
, def_PK11_LIBNAME
);
3141 fprintf(stderr
, "%s: number of slots: %d\n", PK11_DBG
, ulSlotCount
);
3143 fprintf(stderr
, "%s: == checking rand slots ==\n", PK11_DBG
);
3144 #endif /* DEBUG_SLOT_SELECTION */
3145 for (i
= 0; i
< ulSlotCount
; i
++)
3147 current_slot
= pSlotList
[i
];
3149 #ifdef DEBUG_SLOT_SELECTION
3150 fprintf(stderr
, "%s: checking slot: %d\n", PK11_DBG
, i
);
3151 #endif /* DEBUG_SLOT_SELECTION */
3152 /* Check if slot has random support. */
3153 rv
= pFuncList
->C_GetTokenInfo(current_slot
, &token_info
);
3157 #ifdef DEBUG_SLOT_SELECTION
3158 fprintf(stderr
, "%s: token label: %.32s\n", PK11_DBG
, token_info
.label
);
3159 #endif /* DEBUG_SLOT_SELECTION */
3161 if (token_info
.flags
& CKF_RNG
)
3163 #ifdef DEBUG_SLOT_SELECTION
3164 fprintf(stderr
, "%s: this token has CKF_RNG flag\n", PK11_DBG
);
3165 #endif /* DEBUG_SLOT_SELECTION */
3166 pk11_have_random
= CK_TRUE
;
3167 rand_SLOTID
= current_slot
;
3172 #ifdef DEBUG_SLOT_SELECTION
3173 fprintf(stderr
, "%s: == checking pubkey slots ==\n", PK11_DBG
);
3174 #endif /* DEBUG_SLOT_SELECTION */
3176 pubkey_SLOTID
= pSlotList
[0];
3177 for (i
= 0; i
< ulSlotCount
; i
++)
3179 CK_BBOOL slot_has_rsa
= CK_FALSE
;
3180 CK_BBOOL slot_has_dsa
= CK_FALSE
;
3181 CK_BBOOL slot_has_dh
= CK_FALSE
;
3182 current_slot
= pSlotList
[i
];
3184 #ifdef DEBUG_SLOT_SELECTION
3185 fprintf(stderr
, "%s: checking slot: %d\n", PK11_DBG
, i
);
3186 #endif /* DEBUG_SLOT_SELECTION */
3187 rv
= pFuncList
->C_GetTokenInfo(current_slot
, &token_info
);
3191 #ifdef DEBUG_SLOT_SELECTION
3192 fprintf(stderr
, "%s: token label: %.32s\n", PK11_DBG
, token_info
.label
);
3193 #endif /* DEBUG_SLOT_SELECTION */
3195 #ifndef OPENSSL_NO_RSA
3197 * Check if this slot is capable of signing and
3198 * verifying with CKM_RSA_PKCS.
3200 rv
= pFuncList
->C_GetMechanismInfo(current_slot
, CKM_RSA_PKCS
,
3203 if (rv
== CKR_OK
&& ((mech_info
.flags
& CKF_SIGN
) &&
3204 (mech_info
.flags
& CKF_VERIFY
)))
3207 * Check if this slot is capable of encryption,
3208 * decryption, sign, and verify with CKM_RSA_X_509.
3210 rv
= pFuncList
->C_GetMechanismInfo(current_slot
,
3211 CKM_RSA_X_509
, &mech_info
);
3213 if (rv
== CKR_OK
&& ((mech_info
.flags
& CKF_SIGN
) &&
3214 (mech_info
.flags
& CKF_VERIFY
) &&
3215 (mech_info
.flags
& CKF_ENCRYPT
) &&
3216 (mech_info
.flags
& CKF_VERIFY_RECOVER
) &&
3217 (mech_info
.flags
& CKF_DECRYPT
)))
3219 slot_has_rsa
= CK_TRUE
;
3222 #endif /* OPENSSL_NO_RSA */
3224 #ifndef OPENSSL_NO_DSA
3226 * Check if this slot is capable of signing and
3227 * verifying with CKM_DSA.
3229 rv
= pFuncList
->C_GetMechanismInfo(current_slot
, CKM_DSA
,
3231 if (rv
== CKR_OK
&& ((mech_info
.flags
& CKF_SIGN
) &&
3232 (mech_info
.flags
& CKF_VERIFY
)))
3234 slot_has_dsa
= CK_TRUE
;
3237 #endif /* OPENSSL_NO_DSA */
3239 #ifndef OPENSSL_NO_DH
3241 * Check if this slot is capable of DH key generataion and
3244 rv
= pFuncList
->C_GetMechanismInfo(current_slot
,
3245 CKM_DH_PKCS_KEY_PAIR_GEN
, &mech_info
);
3247 if (rv
== CKR_OK
&& (mech_info
.flags
& CKF_GENERATE_KEY_PAIR
))
3249 rv
= pFuncList
->C_GetMechanismInfo(current_slot
,
3250 CKM_DH_PKCS_DERIVE
, &mech_info
);
3251 if (rv
== CKR_OK
&& (mech_info
.flags
& CKF_DERIVE
))
3253 slot_has_dh
= CK_TRUE
;
3256 #endif /* OPENSSL_NO_DH */
3258 if (!found_candidate_slot
&&
3259 (slot_has_rsa
|| slot_has_dsa
|| slot_has_dh
))
3261 #ifdef DEBUG_SLOT_SELECTION
3263 "%s: potential slot: %d\n", PK11_DBG
, current_slot
);
3264 #endif /* DEBUG_SLOT_SELECTION */
3265 best_slot_sofar
= current_slot
;
3266 pk11_have_rsa
= slot_has_rsa
;
3267 pk11_have_dsa
= slot_has_dsa
;
3268 pk11_have_dh
= slot_has_dh
;
3269 found_candidate_slot
= CK_TRUE
;
3271 * Cache the flags for later use. We might need those if
3272 * RSA keys by reference feature is used.
3274 pubkey_token_flags
= token_info
.flags
;
3275 #ifdef DEBUG_SLOT_SELECTION
3277 "%s: setting found_candidate_slot to CK_TRUE\n",
3280 "%s: best so far slot: %d\n", PK11_DBG
,
3282 fprintf(stderr
, "%s: pubkey flags changed to "
3283 "%lu.\n", PK11_DBG
, pubkey_token_flags
);
3288 "%s: no rsa/dsa/dh\n", PK11_DBG
);
3292 #endif /* DEBUG_SLOT_SELECTION */
3295 if (found_candidate_slot
== CK_TRUE
)
3297 pubkey_SLOTID
= best_slot_sofar
;
3300 found_candidate_slot
= CK_FALSE
;
3301 best_slot_sofar
= 0;
3303 #ifdef DEBUG_SLOT_SELECTION
3304 fprintf(stderr
, "%s: == checking cipher/digest ==\n", PK11_DBG
);
3305 #endif /* DEBUG_SLOT_SELECTION */
3307 SLOTID
= pSlotList
[0];
3308 for (i
= 0; i
< ulSlotCount
; i
++)
3310 #ifdef DEBUG_SLOT_SELECTION
3311 fprintf(stderr
, "%s: checking slot: %d\n", PK11_DBG
, i
);
3312 #endif /* DEBUG_SLOT_SELECTION */
3314 current_slot
= pSlotList
[i
];
3315 current_slot_n_cipher
= 0;
3316 current_slot_n_digest
= 0;
3317 (void) memset(local_cipher_nids
, 0, sizeof (local_cipher_nids
));
3318 (void) memset(local_digest_nids
, 0, sizeof (local_digest_nids
));
3320 pk11_find_symmetric_ciphers(pFuncList
, current_slot
,
3321 ¤t_slot_n_cipher
, local_cipher_nids
);
3323 pk11_find_digests(pFuncList
, current_slot
,
3324 ¤t_slot_n_digest
, local_digest_nids
);
3326 #ifdef DEBUG_SLOT_SELECTION
3327 fprintf(stderr
, "%s: current_slot_n_cipher %d\n", PK11_DBG
,
3328 current_slot_n_cipher
);
3329 fprintf(stderr
, "%s: current_slot_n_digest %d\n", PK11_DBG
,
3330 current_slot_n_digest
);
3331 fprintf(stderr
, "%s: best so far cipher/digest slot: %d\n",
3332 PK11_DBG
, best_slot_sofar
);
3333 #endif /* DEBUG_SLOT_SELECTION */
3336 * If the current slot supports more ciphers/digests than
3337 * the previous best one we change the current best to this one,
3338 * otherwise leave it where it is.
3340 if ((current_slot_n_cipher
+ current_slot_n_digest
) >
3341 (slot_n_cipher
+ slot_n_digest
))
3343 #ifdef DEBUG_SLOT_SELECTION
3345 "%s: changing best so far slot to %d\n",
3346 PK11_DBG
, current_slot
);
3347 #endif /* DEBUG_SLOT_SELECTION */
3348 best_slot_sofar
= SLOTID
= current_slot
;
3349 cipher_count
= slot_n_cipher
= current_slot_n_cipher
;
3350 digest_count
= slot_n_digest
= current_slot_n_digest
;
3351 (void) memcpy(cipher_nids
, local_cipher_nids
,
3352 sizeof (local_cipher_nids
));
3353 (void) memcpy(digest_nids
, local_digest_nids
,
3354 sizeof (local_digest_nids
));
3358 #ifdef DEBUG_SLOT_SELECTION
3360 "%s: chosen pubkey slot: %d\n", PK11_DBG
, pubkey_SLOTID
);
3362 "%s: chosen rand slot: %d\n", PK11_DBG
, rand_SLOTID
);
3364 "%s: chosen cipher/digest slot: %d\n", PK11_DBG
, SLOTID
);
3366 "%s: pk11_have_rsa %d\n", PK11_DBG
, pk11_have_rsa
);
3368 "%s: pk11_have_dsa %d\n", PK11_DBG
, pk11_have_dsa
);
3370 "%s: pk11_have_dh %d\n", PK11_DBG
, pk11_have_dh
);
3372 "%s: pk11_have_random %d\n", PK11_DBG
, pk11_have_random
);
3374 "%s: cipher_count %d\n", PK11_DBG
, cipher_count
);
3376 "%s: digest_count %d\n", PK11_DBG
, digest_count
);
3377 #endif /* DEBUG_SLOT_SELECTION */
3379 if (pSlotList
!= NULL
)
3380 OPENSSL_free(pSlotList
);
3382 #ifdef SOLARIS_HW_SLOT_SELECTION
3383 OPENSSL_free(hw_cnids
);
3384 OPENSSL_free(hw_dnids
);
3385 #endif /* SOLARIS_HW_SLOT_SELECTION */
3387 if (any_slot_found
!= NULL
)
3388 *any_slot_found
= 1;
3392 static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR pflist
,
3393 int slot_id
, CK_MECHANISM_TYPE mech
, int *current_slot_n_cipher
,
3394 int *local_cipher_nids
, int id
)
3396 CK_MECHANISM_INFO mech_info
;
3399 #ifdef DEBUG_SLOT_SELECTION
3400 fprintf(stderr
, "%s: checking mech: %x", PK11_DBG
, mech
);
3401 #endif /* DEBUG_SLOT_SELECTION */
3402 rv
= pflist
->C_GetMechanismInfo(slot_id
, mech
, &mech_info
);
3406 #ifdef DEBUG_SLOT_SELECTION
3407 fprintf(stderr
, " not found\n");
3408 #endif /* DEBUG_SLOT_SELECTION */
3412 if ((mech_info
.flags
& CKF_ENCRYPT
) &&
3413 (mech_info
.flags
& CKF_DECRYPT
))
3415 #ifdef SOLARIS_HW_SLOT_SELECTION
3416 if (nid_in_table(ciphers
[id
].nid
, hw_cnids
))
3417 #endif /* SOLARIS_HW_SLOT_SELECTION */
3419 #ifdef DEBUG_SLOT_SELECTION
3420 fprintf(stderr
, " usable\n");
3421 #endif /* DEBUG_SLOT_SELECTION */
3422 local_cipher_nids
[(*current_slot_n_cipher
)++] =
3425 #ifdef SOLARIS_HW_SLOT_SELECTION
3426 #ifdef DEBUG_SLOT_SELECTION
3429 fprintf(stderr
, " rejected, software implementation only\n");
3431 #endif /* DEBUG_SLOT_SELECTION */
3432 #endif /* SOLARIS_HW_SLOT_SELECTION */
3434 #ifdef DEBUG_SLOT_SELECTION
3437 fprintf(stderr
, " unusable\n");
3439 #endif /* DEBUG_SLOT_SELECTION */
3444 static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist
, int slot_id
,
3445 CK_MECHANISM_TYPE mech
, int *current_slot_n_digest
, int *local_digest_nids
,
3448 CK_MECHANISM_INFO mech_info
;
3451 #ifdef DEBUG_SLOT_SELECTION
3452 fprintf(stderr
, "%s: checking mech: %x", PK11_DBG
, mech
);
3453 #endif /* DEBUG_SLOT_SELECTION */
3454 rv
= pflist
->C_GetMechanismInfo(slot_id
, mech
, &mech_info
);
3458 #ifdef DEBUG_SLOT_SELECTION
3459 fprintf(stderr
, " not found\n");
3460 #endif /* DEBUG_SLOT_SELECTION */
3464 if (mech_info
.flags
& CKF_DIGEST
)
3466 #ifdef SOLARIS_HW_SLOT_SELECTION
3467 if (nid_in_table(digests
[id
].nid
, hw_dnids
))
3468 #endif /* SOLARIS_HW_SLOT_SELECTION */
3470 #ifdef DEBUG_SLOT_SELECTION
3471 fprintf(stderr
, " usable\n");
3472 #endif /* DEBUG_SLOT_SELECTION */
3473 local_digest_nids
[(*current_slot_n_digest
)++] =
3476 #ifdef SOLARIS_HW_SLOT_SELECTION
3477 #ifdef DEBUG_SLOT_SELECTION
3480 fprintf(stderr
, " rejected, software implementation only\n");
3482 #endif /* DEBUG_SLOT_SELECTION */
3483 #endif /* SOLARIS_HW_SLOT_SELECTION */
3485 #ifdef DEBUG_SLOT_SELECTION
3488 fprintf(stderr
, " unusable\n");
3490 #endif /* DEBUG_SLOT_SELECTION */
3495 #ifdef SOLARIS_AES_CTR
3496 /* create a new NID when we have no OID for that mechanism */
3497 static int pk11_add_NID(char *sn
, char *ln
)
3502 if ((o
= ASN1_OBJECT_create(OBJ_new_nid(1), (unsigned char *)"",
3503 1, sn
, ln
)) == NULL
)
3508 /* will return NID_undef on error */
3509 nid
= OBJ_add_object(o
);
3510 ASN1_OBJECT_free(o
);
3516 * Create new NIDs for AES counter mode. OpenSSL doesn't support them now so we
3517 * have to help ourselves here.
3519 static int pk11_add_aes_ctr_NIDs(void)
3521 /* are we already set? */
3522 if (NID_aes_256_ctr
!= NID_undef
)
3526 * There are no official names for AES counter modes yet so we just
3527 * follow the format of those that exist.
3529 if ((NID_aes_128_ctr
= pk11_add_NID("AES-128-CTR", "aes-128-ctr")) ==
3532 ciphers
[PK11_AES_128_CTR
].nid
= pk11_aes_128_ctr
.nid
= NID_aes_128_ctr
;
3533 if ((NID_aes_192_ctr
= pk11_add_NID("AES-192-CTR", "aes-192-ctr")) ==
3536 ciphers
[PK11_AES_192_CTR
].nid
= pk11_aes_192_ctr
.nid
= NID_aes_192_ctr
;
3537 if ((NID_aes_256_ctr
= pk11_add_NID("AES-256-CTR", "aes-256-ctr")) ==
3540 ciphers
[PK11_AES_256_CTR
].nid
= pk11_aes_256_ctr
.nid
= NID_aes_256_ctr
;
3544 PK11err(PK11_F_ADD_AES_CTR_NIDS
, PK11_R_ADD_NID_FAILED
);
3547 #endif /* SOLARIS_AES_CTR */
3549 /* Find what symmetric ciphers this slot supports. */
3550 static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist
,
3551 CK_SLOT_ID current_slot
, int *current_slot_n_cipher
, int *local_cipher_nids
)
3555 for (i
= 0; i
< PK11_CIPHER_MAX
; ++i
)
3557 pk11_get_symmetric_cipher(pflist
, current_slot
,
3558 ciphers
[i
].mech_type
, current_slot_n_cipher
,
3559 local_cipher_nids
, ciphers
[i
].id
);
3563 /* Find what digest algorithms this slot supports. */
3564 static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist
,
3565 CK_SLOT_ID current_slot
, int *current_slot_n_digest
, int *local_digest_nids
)
3569 for (i
= 0; i
< PK11_DIGEST_MAX
; ++i
)
3571 pk11_get_digest(pflist
, current_slot
, digests
[i
].mech_type
,
3572 current_slot_n_digest
, local_digest_nids
, digests
[i
].id
);
3576 #ifdef SOLARIS_HW_SLOT_SELECTION
3578 * It would be great if we could use pkcs11_kernel directly since this library
3579 * offers hardware slots only. That's the easiest way to achieve the situation
3580 * where we use the hardware accelerators when present and OpenSSL native code
3581 * otherwise. That presumes the fact that OpenSSL native code is faster than the
3582 * code in the soft token. It's a logical assumption - Crypto Framework has some
3583 * inherent overhead so going there for the software implementation of a
3584 * mechanism should be logically slower in contrast to the OpenSSL native code,
3585 * presuming that both implementations are of similar speed. For example, the
3586 * soft token for AES is roughly three times slower than OpenSSL for 64 byte
3587 * blocks and still 20% slower for 8KB blocks. So, if we want to ship products
3588 * that use the PKCS#11 engine by default, we must somehow avoid that regression
3589 * on machines without hardware acceleration. That's why switching to the
3590 * pkcs11_kernel library seems like a very good idea.
3592 * The problem is that OpenSSL built with SunStudio is roughly 2x slower for
3593 * asymmetric operations (RSA/DSA/DH) than the soft token built with the same
3594 * compiler. That means that if we switched to pkcs11_kernel from the libpkcs11
3595 * library, we would have had a performance regression on machines without
3596 * hardware acceleration for asymmetric operations for all applications that use
3597 * the PKCS#11 engine. There is one such application - Apache web server since
3598 * it's shipped configured to use the PKCS#11 engine by default. Having said
3599 * that, we can't switch to the pkcs11_kernel library now and have to come with
3600 * a solution that, on non-accelerated machines, uses the OpenSSL native code
3601 * for all symmetric ciphers and digests while it uses the soft token for
3602 * asymmetric operations.
3604 * This is the idea: dlopen() pkcs11_kernel directly and find out what
3605 * mechanisms are there. We don't care about duplications (more slots can
3606 * support the same mechanism), we just want to know what mechanisms can be
3607 * possibly supported in hardware on that particular machine. As said before,
3608 * pkcs11_kernel will show you hardware providers only.
3610 * Then, we rely on the fact that since we use libpkcs11 library we will find
3611 * the metaslot. When we go through the metaslot's mechanisms for symmetric
3612 * ciphers and digests, we check that any found mechanism is in the table
3613 * created using the pkcs11_kernel library. So, as a result we have two arrays
3614 * of mechanisms that were advertised as supported in hardware which was the
3615 * goal of that whole excercise. Thus, we can use libpkcs11 but avoid soft token
3616 * code for symmetric ciphers and digests. See pk11_choose_slots() for more
3619 * This is Solaris specific code, if SOLARIS_HW_SLOT_SELECTION is not defined
3620 * the code won't be used.
3622 #if defined(__sparcv9) || defined(__x86_64) || defined(__amd64)
3623 static const char pkcs11_kernel
[] = "/usr/lib/security/64/pkcs11_kernel.so.1";
3625 static const char pkcs11_kernel
[] = "/usr/lib/security/pkcs11_kernel.so.1";
3629 * Check hardware capabilities of the machines. The output are two lists,
3630 * hw_cnids and hw_dnids, that contain hardware mechanisms found in all hardware
3631 * providers together. They are not sorted and may contain duplicate mechanisms.
3633 static int check_hw_mechanisms(void)
3638 CK_C_GetFunctionList p
;
3639 CK_TOKEN_INFO token_info
;
3640 CK_ULONG ulSlotCount
= 0;
3641 int n_cipher
= 0, n_digest
= 0;
3642 CK_FUNCTION_LIST_PTR pflist
= NULL
;
3643 CK_SLOT_ID_PTR pSlotList
= NULL_PTR
;
3644 int *tmp_hw_cnids
= NULL
, *tmp_hw_dnids
= NULL
;
3645 int hw_ctable_size
, hw_dtable_size
;
3647 #ifdef DEBUG_SLOT_SELECTION
3648 fprintf(stderr
, "%s: SOLARIS_HW_SLOT_SELECTION code running\n",
3652 * Use RTLD_GROUP to limit the pkcs11_kernel provider to its own
3653 * symbols, which prevents it from mistakenly accessing C_* functions
3654 * from the top-level PKCS#11 library.
3656 if ((handle
= dlopen(pkcs11_kernel
, RTLD_LAZY
| RTLD_GROUP
)) == NULL
)
3658 PK11err(PK11_F_CHECK_HW_MECHANISMS
, PK11_R_DSO_FAILURE
);
3662 if ((p
= (CK_C_GetFunctionList
)dlsym(handle
,
3663 PK11_GET_FUNCTION_LIST
)) == NULL
)
3665 PK11err(PK11_F_CHECK_HW_MECHANISMS
, PK11_R_DSO_FAILURE
);
3669 /* get the full function list from the loaded library */
3670 if (p(&pflist
) != CKR_OK
)
3672 PK11err(PK11_F_CHECK_HW_MECHANISMS
, PK11_R_DSO_FAILURE
);
3676 rv
= pflist
->C_Initialize(NULL_PTR
);
3677 if ((rv
!= CKR_OK
) && (rv
!= CKR_CRYPTOKI_ALREADY_INITIALIZED
))
3679 PK11err_add_data(PK11_F_CHECK_HW_MECHANISMS
,
3680 PK11_R_INITIALIZE
, rv
);
3684 if (pflist
->C_GetSlotList(0, NULL_PTR
, &ulSlotCount
) != CKR_OK
)
3686 PK11err(PK11_F_CHECK_HW_MECHANISMS
, PK11_R_GETSLOTLIST
);
3690 /* no slots, set the hw mechanism tables as empty */
3691 if (ulSlotCount
== 0)
3693 #ifdef DEBUG_SLOT_SELECTION
3694 fprintf(stderr
, "%s: no hardware mechanisms found\n", PK11_DBG
);
3696 hw_cnids
= OPENSSL_malloc(sizeof (int));
3697 hw_dnids
= OPENSSL_malloc(sizeof (int));
3698 if (hw_cnids
== NULL
|| hw_dnids
== NULL
)
3700 PK11err(PK11_F_CHECK_HW_MECHANISMS
,
3701 PK11_R_MALLOC_FAILURE
);
3704 /* this means empty tables */
3705 hw_cnids
[0] = NID_undef
;
3706 hw_dnids
[0] = NID_undef
;
3710 pSlotList
= OPENSSL_malloc(ulSlotCount
* sizeof (CK_SLOT_ID
));
3711 if (pSlotList
== NULL
)
3713 PK11err(PK11_F_CHECK_HW_MECHANISMS
, PK11_R_MALLOC_FAILURE
);
3717 /* Get the slot list for processing */
3718 if (pflist
->C_GetSlotList(0, pSlotList
, &ulSlotCount
) != CKR_OK
)
3720 PK11err(PK11_F_CHECK_HW_MECHANISMS
, PK11_R_GETSLOTLIST
);
3725 * We don't care about duplicit mechanisms in multiple slots and also
3726 * reserve one slot for the terminal NID_undef which we use to stop the
3729 hw_ctable_size
= ulSlotCount
* PK11_CIPHER_MAX
+ 1;
3730 hw_dtable_size
= ulSlotCount
* PK11_DIGEST_MAX
+ 1;
3731 tmp_hw_cnids
= OPENSSL_malloc(hw_ctable_size
* sizeof (int));
3732 tmp_hw_dnids
= OPENSSL_malloc(hw_dtable_size
* sizeof (int));
3733 if (tmp_hw_cnids
== NULL
|| tmp_hw_dnids
== NULL
)
3735 PK11err(PK11_F_CHECK_HW_MECHANISMS
, PK11_R_MALLOC_FAILURE
);
3740 * Do not use memset since we should not rely on the fact that NID_undef
3743 for (i
= 0; i
< hw_ctable_size
; ++i
)
3744 tmp_hw_cnids
[i
] = NID_undef
;
3745 for (i
= 0; i
< hw_dtable_size
; ++i
)
3746 tmp_hw_dnids
[i
] = NID_undef
;
3748 #ifdef DEBUG_SLOT_SELECTION
3749 fprintf(stderr
, "%s: provider: %s\n", PK11_DBG
, pkcs11_kernel
);
3750 fprintf(stderr
, "%s: found %d hardware slots\n", PK11_DBG
, ulSlotCount
);
3751 fprintf(stderr
, "%s: now looking for mechs supported in hw\n",
3753 #endif /* DEBUG_SLOT_SELECTION */
3755 for (i
= 0; i
< ulSlotCount
; i
++)
3757 if (pflist
->C_GetTokenInfo(pSlotList
[i
], &token_info
) != CKR_OK
)
3760 #ifdef DEBUG_SLOT_SELECTION
3761 fprintf(stderr
, "%s: token label: %.32s\n", PK11_DBG
, token_info
.label
);
3762 #endif /* DEBUG_SLOT_SELECTION */
3765 * We are filling the hw mech tables here. Global tables are
3766 * still NULL so all mechanisms are put into tmp tables.
3768 pk11_find_symmetric_ciphers(pflist
, pSlotList
[i
],
3769 &n_cipher
, tmp_hw_cnids
);
3770 pk11_find_digests(pflist
, pSlotList
[i
],
3771 &n_digest
, tmp_hw_dnids
);
3775 * Since we are part of a library (libcrypto.so), calling this function
3776 * may have side-effects. Also, C_Finalize() is triggered by
3780 pflist
->C_Finalize(NULL
);
3782 OPENSSL_free(pSlotList
);
3783 (void) dlclose(handle
);
3784 hw_cnids
= tmp_hw_cnids
;
3785 hw_dnids
= tmp_hw_dnids
;
3787 #ifdef DEBUG_SLOT_SELECTION
3788 fprintf(stderr
, "%s: hw mechs check complete\n", PK11_DBG
);
3789 #endif /* DEBUG_SLOT_SELECTION */
3793 if (pSlotList
!= NULL
)
3794 OPENSSL_free(pSlotList
);
3795 if (tmp_hw_cnids
!= NULL
)
3796 OPENSSL_free(tmp_hw_cnids
);
3797 if (tmp_hw_dnids
!= NULL
)
3798 OPENSSL_free(tmp_hw_dnids
);
3804 * Check presence of a NID in the table of NIDs. The table may be NULL (i.e.,
3807 static int nid_in_table(int nid
, int *nid_table
)
3812 * a special case. NULL means that we are initializing a new
3815 if (nid_table
== NULL
)
3819 * the table is never full, there is always at least one
3822 while (nid_table
[i
] != NID_undef
)
3824 if (nid_table
[i
++] == nid
)
3826 #ifdef DEBUG_SLOT_SELECTION
3827 fprintf(stderr
, " (NID %d in hw table, idx %d)", nid
, i
);
3828 #endif /* DEBUG_SLOT_SELECTION */
3835 #endif /* SOLARIS_HW_SLOT_SELECTION */
3837 #endif /* OPENSSL_NO_HW_PK11 */
3838 #endif /* OPENSSL_NO_HW */