Engine for the ICSF backend
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2833 lines
88 KiB

3 months ago
  1. /* hw_pkcs11.c (replace hw_trustway.c) */
  2. /*
  3. * PKCS#11 engine for the OpenSSL project 2002
  4. * Developped by Bull Trustway R&D Networking & Security
  5. * Introduced and tested with Bull TrustWay CC2000 crypto hardware
  6. * Afchine.Madjlessi@bull.net Bull S.A. France
  7. * http://www.servers.bull.com/trustway
  8. *
  9. * ChangLog:
  10. * * 6/30/2010 Updates to compile stand-alone and against openssl 1.0
  11. * * 8/15/2005 Fixes suggested by opencryptoki-engines list
  12. * * 1/1/2004 Modified to support digests, ciphers and openCryptoki
  13. * http://www.sf.net/projects/opencryptoki
  14. * - Serge Hallyn <serue@us.ibm.com>
  15. * - Kent Yoder <yoder1@us.ibm.com>
  16. * - Peter Waltenberg <pwalten@au1.ibm.com>
  17. * (C) International Business Machines Corporation 2004, 2005, 2010
  18. */
  19. #include <assert.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <stdio.h>
  23. #include <pthread.h>
  24. #include <dlfcn.h>
  25. #include <sys/types.h>
  26. #include <unistd.h>
  27. #include <openssl/e_os2.h>
  28. #include <openssl/engine.h>
  29. #include <openssl/err.h>
  30. #include <openssl/bn.h>
  31. #include <openssl/pem.h>
  32. #include <openssl/rsa.h>
  33. #include <openssl/rand.h>
  34. #include <openssl/objects.h>
  35. #include <openssl/md5.h>
  36. #include <openssl/ripemd.h>
  37. #ifndef OPENSSL_NO_HW
  38. #ifndef OPENSSL_NO_HW_PKCS11
  39. #include "csnpdefs.h"
  40. #include "e_pkcs11_err.h"
  41. #include "e_pkcs11.h"
  42. /* Constants used when creating the ENGINE */
  43. static const char *engine_pkcs11_id = "ibmpkcs11";
  44. static const char *engine_pkcs11_name = "PKCS#11 hardware engine support";
  45. static int bind_pkcs11(ENGINE *e);
  46. /* ENGINE level stuff */
  47. static int pkcs11_init(ENGINE *e);
  48. static int pkcs11_finish(ENGINE *e);
  49. static int pkcs11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
  50. static int pkcs11_destroy(ENGINE *e);
  51. /* RSA stuff */
  52. static int pkcs11_RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to,
  53. RSA *rsa, int padding);
  54. static int pkcs11_RSA_private_encrypt(int flen, const unsigned char *from, unsigned char *to,
  55. RSA *rsa, int padding);
  56. static int pkcs11_RSA_public_decrypt(int flen, const unsigned char *from, unsigned char *to,
  57. RSA *rsa, int padding);
  58. static int pkcs11_RSA_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
  59. RSA *rsa, int padding);
  60. static int pkcs11_RSA_init(RSA *rsa);
  61. static int pkcs11_RSA_finish(RSA *rsa);
  62. static int pkcs11_RSA_generate_key(RSA *rsa, int bits, BIGNUM *bn_e, BN_GENCB *cb);
  63. static EVP_PKEY *pkcs11_load_privkey(ENGINE*, const char* pubkey_file,
  64. UI_METHOD *ui_method, void *callback_data);
  65. static EVP_PKEY *pkcs11_load_pubkey(ENGINE*, const char* pubkey_file,
  66. UI_METHOD *ui_method, void *callback_data);
  67. CK_OBJECT_HANDLE pkcs11_FindOrCreateKey(CK_SESSION_HANDLE h, RSA* rsa, CK_OBJECT_CLASS oKey, CK_BBOOL fKeyCreate);
  68. /* exported functions (not member of ENGINE inteface) */
  69. RSA* pkcs11_RSA_generate_tmp_key(int bits,unsigned long e_value,void (*callback)(int,int,void *),void *cb_arg);
  70. /* RAND stuff */
  71. static int pkcs11_rand_seed(const void *buf, int num);
  72. static int pkcs11_rand_add(const void *buf, int num, double add_entropy);
  73. static void pkcs11_rand_cleanup(void);
  74. static int pkcs11_rand_bytes(unsigned char *buf, int num);
  75. static int pkcs11_rand_status(void);
  76. /* cipher function prototypes */
  77. static inline int pkcs11_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key, const unsigned char *iv, int enc, int alg);
  78. static inline int pkcs11_cipher(EVP_CIPHER_CTX * ctx, unsigned char *out, const unsigned char *in, size_t inlen);
  79. static int pkcs11_cipher_cleanup(EVP_CIPHER_CTX *ctx);
  80. static int pkcs11_des_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key, const unsigned char *iv, int enc);
  81. static int pkcs11_tdes_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key, const unsigned char *iv, int enc);
  82. static int pkcs11_aes_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key, const unsigned char *iv, int enc);
  83. /* End cipher function prototypes */
  84. /* Digest function prototypes */
  85. static inline int pkcs11_digest_init(EVP_MD_CTX *ctx, int alg);
  86. static int pkcs11_digest_update(EVP_MD_CTX *ctx, const void *in, size_t len);
  87. static int pkcs11_digest_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in);
  88. static int pkcs11_digest_finish(EVP_MD_CTX *ctx, unsigned char *md);
  89. static inline int pkcs11_digest_cleanup(EVP_MD_CTX *ctx);
  90. static inline int pkcs11_sha1_init(EVP_MD_CTX *ctx);
  91. static inline int pkcs11_sha224_init(EVP_MD_CTX *ctx);
  92. static inline int pkcs11_sha256_init(EVP_MD_CTX *ctx);
  93. static inline int pkcs11_sha384_init(EVP_MD_CTX *ctx);
  94. static inline int pkcs11_sha512_init(EVP_MD_CTX *ctx);
  95. static inline int pkcs11_md5_init(EVP_MD_CTX *ctx);
  96. static inline int pkcs11_ripemd160_init(EVP_MD_CTX *ctx);
  97. /* End digest function prototypes */
  98. static int pre_init_pkcs11(ENGINE *e);
  99. static int pkcs11_engine_ciphers(ENGINE * e, const EVP_CIPHER ** cipher, const int **nids, int nid);
  100. static int pkcs11_engine_digests(ENGINE * e, const EVP_MD ** digest, const int **nids, int nid);
  101. /* The definitions for control commands specific to this engine */
  102. #define PKCS11_CMD_SO_PATH ENGINE_CMD_BASE
  103. #define PKCS11_CMD_SLOT_ID (ENGINE_CMD_BASE + 1)
  104. static const ENGINE_CMD_DEFN pkcs11_cmd_defns[] =
  105. {
  106. { PKCS11_CMD_SO_PATH,
  107. "SO_PATH",
  108. "Specifies the path to the 'pkcs#11' shared library",
  109. ENGINE_CMD_FLAG_STRING
  110. },
  111. { PKCS11_CMD_SLOT_ID,
  112. "SLOT_ID",
  113. "Specifies the slot containing the token to use",
  114. ENGINE_CMD_FLAG_NUMERIC
  115. },
  116. {0, NULL, NULL, 0}
  117. };
  118. #ifdef OPENSSL_NO_DYNAMIC_ENGINE
  119. static ENGINE *engine_pkcs11(void)
  120. {
  121. ENGINE *ret = ENGINE_new();
  122. if(!ret) {
  123. return NULL;
  124. }
  125. if(!bind_helper(ret)) {
  126. ENGINE_free(ret);
  127. return NULL;
  128. }
  129. return ret;
  130. }
  131. void ENGINE_load_pkcs11(void)
  132. {
  133. ENGINE *toadd = engine_pkcs11();
  134. if(!toadd) return;
  135. ENGINE_add(toadd);
  136. ENGINE_free(toadd);
  137. ERR_clear_error();
  138. }
  139. #else
  140. static int bind_helper(ENGINE *e, const char *id)
  141. {
  142. if((NULL != id) && (strcmp(id, engine_pkcs11_id) != 0))
  143. return 0;
  144. return(bind_pkcs11(e));
  145. }
  146. IMPLEMENT_DYNAMIC_CHECK_FN()
  147. IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
  148. #endif
  149. /*
  150. * Comments on approaches:
  151. * At the moment, ciphers and digests are treated differently.
  152. *
  153. * For ciphers, we use cipher_init to initialize the cryptoki
  154. * cipher action, and update to encrypt. There is no finalize
  155. * or cleanup.
  156. *
  157. * For digests, we use digest_init to initialize a context
  158. * struct, digest_update to call C_DigestUpdate on the data that
  159. * we are receiving, digest_finish to call C_DigestFinal(), and
  160. * cleanup() to free the context struct.
  161. */
  162. /*
  163. * Each cipher action requires a new session. We store the
  164. * session and its token in the context->cipher_data void* using
  165. * this struct
  166. */
  167. struct token_session {
  168. struct _token *token;
  169. CK_SESSION_HANDLE session;
  170. };
  171. /*
  172. * For digests:
  173. * We call digest_init to start the context, digest_update
  174. * to start computing the digest on the data that is being
  175. * received and digest_finish to finish the digest operation.
  176. */
  177. struct pkcs11_digest_ctx {
  178. int alg;
  179. int len;
  180. struct _token *token;
  181. CK_SESSION_HANDLE session;
  182. };
  183. /********/
  184. #define CIPHER_DATA(ctx) ((struct token_session *)(EVP_CIPHER_CTX_get_cipher_data(ctx)))
  185. #define MD_DATA(ctx) ((struct pkcs11_digest_ctx *)(EVP_MD_CTX_md_data(ctx)))
  186. static int num_cipher_nids = 0;
  187. static int num_digest_nids = 0;
  188. #define DECLARE_DES_EVP(lmode, umode) \
  189. static EVP_CIPHER *des_##lmode = NULL; \
  190. static const EVP_CIPHER *pkcs11_des_##lmode(void) \
  191. { \
  192. if (des_##lmode == NULL) { \
  193. EVP_CIPHER *cipher; \
  194. if (( cipher = EVP_CIPHER_meth_new(NID_des_##lmode, \
  195. 8, 8)) == NULL \
  196. || !EVP_CIPHER_meth_set_iv_length(cipher, 8) \
  197. || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_##umode##_MODE)\
  198. || !EVP_CIPHER_meth_set_init(cipher, pkcs11_des_init_key) \
  199. || !EVP_CIPHER_meth_set_do_cipher(cipher, pkcs11_cipher) \
  200. || !EVP_CIPHER_meth_set_cleanup(cipher, pkcs11_cipher_cleanup)\
  201. || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof( \
  202. struct token_session))\
  203. || !EVP_CIPHER_meth_set_set_asn1_params(cipher, \
  204. EVP_CIPHER_set_asn1_iv) \
  205. || !EVP_CIPHER_meth_set_get_asn1_params(cipher, \
  206. EVP_CIPHER_get_asn1_iv)) { \
  207. EVP_CIPHER_meth_free(cipher); \
  208. cipher = NULL; \
  209. } \
  210. des_##lmode = cipher; \
  211. } \
  212. return des_##lmode; \
  213. } \
  214. \
  215. static void pkcs11_des_##lmode##_destroy(void) \
  216. { \
  217. EVP_CIPHER_meth_free(des_##lmode); \
  218. des_##lmode = NULL; \
  219. }
  220. DECLARE_DES_EVP(ecb, ECB)
  221. DECLARE_DES_EVP(cbc, CBC)
  222. #define DECLARE_TDES_EVP(lmode, umode) \
  223. static EVP_CIPHER *tdes_##lmode = NULL; \
  224. static const EVP_CIPHER *pkcs11_tdes_##lmode(void) \
  225. { \
  226. if (tdes_##lmode == NULL) { \
  227. EVP_CIPHER *cipher; \
  228. if (( cipher = EVP_CIPHER_meth_new(NID_des_ede3_##lmode, \
  229. 8, 24)) == NULL \
  230. || !EVP_CIPHER_meth_set_iv_length(cipher, 8) \
  231. || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_##umode##_MODE)\
  232. || !EVP_CIPHER_meth_set_init(cipher, pkcs11_tdes_init_key) \
  233. || !EVP_CIPHER_meth_set_do_cipher(cipher, pkcs11_cipher) \
  234. || !EVP_CIPHER_meth_set_cleanup(cipher, pkcs11_cipher_cleanup)\
  235. || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof( \
  236. struct token_session))\
  237. || !EVP_CIPHER_meth_set_set_asn1_params(cipher, \
  238. EVP_CIPHER_set_asn1_iv) \
  239. || !EVP_CIPHER_meth_set_get_asn1_params(cipher, \
  240. EVP_CIPHER_get_asn1_iv)) { \
  241. EVP_CIPHER_meth_free(cipher); \
  242. cipher = NULL; \
  243. } \
  244. tdes_##lmode = cipher; \
  245. } \
  246. return tdes_##lmode; \
  247. } \
  248. \
  249. static void pkcs11_tdes_##lmode##_destroy(void) \
  250. { \
  251. EVP_CIPHER_meth_free(tdes_##lmode); \
  252. tdes_##lmode = NULL; \
  253. }
  254. DECLARE_TDES_EVP(ecb, ECB)
  255. DECLARE_TDES_EVP(cbc, CBC)
  256. #define EVP_CIPHER_keylen_AES_128 16
  257. #define EVP_CIPHER_keylen_AES_192 24
  258. #define EVP_CIPHER_keylen_AES_256 32
  259. #define DECLARE_AES_EVP(ksize, lmode, umode) \
  260. static EVP_CIPHER *aes_##ksize##_##lmode = NULL; \
  261. static const EVP_CIPHER *pkcs11_aes_##ksize##_##lmode(void) \
  262. { \
  263. if (aes_##ksize##_##lmode == NULL) { \
  264. EVP_CIPHER *cipher; \
  265. if (( cipher = EVP_CIPHER_meth_new(NID_aes_##ksize##_##lmode, \
  266. 8, \
  267. EVP_CIPHER_keylen_AES_##ksize)) == NULL \
  268. || !EVP_CIPHER_meth_set_iv_length(cipher, 16) \
  269. || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_##umode##_MODE)\
  270. || !EVP_CIPHER_meth_set_init(cipher, pkcs11_aes_init_key) \
  271. || !EVP_CIPHER_meth_set_do_cipher(cipher, pkcs11_cipher) \
  272. || !EVP_CIPHER_meth_set_cleanup(cipher, pkcs11_cipher_cleanup)\
  273. || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof( \
  274. struct token_session))\
  275. || !EVP_CIPHER_meth_set_set_asn1_params(cipher, \
  276. EVP_CIPHER_set_asn1_iv) \
  277. || !EVP_CIPHER_meth_set_get_asn1_params(cipher, \
  278. EVP_CIPHER_get_asn1_iv)) { \
  279. EVP_CIPHER_meth_free(cipher); \
  280. cipher = NULL; \
  281. } \
  282. aes_##ksize##_##lmode = cipher; \
  283. } \
  284. return aes_##ksize##_##lmode; \
  285. } \
  286. \
  287. static void pkcs11_aes_##ksize##_##lmode##_destroy(void) \
  288. { \
  289. EVP_CIPHER_meth_free(aes_##ksize##_##lmode); \
  290. aes_##ksize##_##lmode = NULL; \
  291. }
  292. DECLARE_AES_EVP(128, cbc, CBC)
  293. DECLARE_AES_EVP(192, cbc, CBC)
  294. DECLARE_AES_EVP(256, cbc, CBC)
  295. DECLARE_AES_EVP(128, ecb, ECB)
  296. DECLARE_AES_EVP(192, ecb, ECB)
  297. DECLARE_AES_EVP(256, ecb, ECB)
  298. #define DECLARE_DIGEST_EVP(dig, len, enc) \
  299. static EVP_MD *dig##_md = NULL; \
  300. static const EVP_MD *pkcs11_##dig(void) \
  301. { \
  302. if (dig##_md == NULL) { \
  303. EVP_MD *md; \
  304. if (( md = EVP_MD_meth_new(NID_##dig, \
  305. NID_##dig##WithRSA##enc)) == NULL \
  306. || !EVP_MD_meth_set_result_size(md, len##_DIGEST_LENGTH) \
  307. || !EVP_MD_meth_set_input_blocksize(md, len##_CBLOCK) \
  308. || !EVP_MD_meth_set_app_datasize(md, \
  309. sizeof(struct pkcs11_digest_ctx)) \
  310. || !EVP_MD_meth_set_flags(md, 0) \
  311. || !EVP_MD_meth_set_init(md, pkcs11_##dig##_init) \
  312. || !EVP_MD_meth_set_update(md, pkcs11_digest_update) \
  313. || !EVP_MD_meth_set_final(md, pkcs11_digest_finish) \
  314. || !EVP_MD_meth_set_copy(md, pkcs11_digest_copy) \
  315. || !EVP_MD_meth_set_cleanup(md, pkcs11_digest_cleanup)) { \
  316. EVP_MD_meth_free(md); \
  317. md = NULL; \
  318. } \
  319. dig##_md = md; \
  320. } \
  321. return dig##_md; \
  322. } \
  323. \
  324. static void pkcs11_##dig##_destroy(void) \
  325. { \
  326. EVP_MD_meth_free(dig##_md); \
  327. dig##_md = NULL; \
  328. }
  329. DECLARE_DIGEST_EVP(sha1, SHA, Encryption)
  330. DECLARE_DIGEST_EVP(sha224, SHA256, Encryption)
  331. DECLARE_DIGEST_EVP(sha256, SHA256, Encryption)
  332. DECLARE_DIGEST_EVP(sha384, SHA512, Encryption)
  333. DECLARE_DIGEST_EVP(sha512, SHA512, Encryption)
  334. DECLARE_DIGEST_EVP(md5, MD5, Encryption)
  335. DECLARE_DIGEST_EVP(ripemd160, RIPEMD160,)
  336. /********/
  337. static RSA_METHOD *pkcs11_rsa = NULL;
  338. RSA_METHOD *PKCS11_RSA(void)
  339. {
  340. return(&pkcs11_rsa);
  341. }
  342. extern const char *RAND_version;
  343. static RAND_METHOD pkcs11_random =
  344. {
  345. /* "PKCS11 RAND method", */
  346. pkcs11_rand_seed,
  347. pkcs11_rand_bytes,
  348. pkcs11_rand_cleanup,
  349. pkcs11_rand_add,
  350. pkcs11_rand_bytes,
  351. pkcs11_rand_status
  352. };
  353. RAND_METHOD *PKCS11_RAND(void)
  354. {
  355. return(&pkcs11_random);
  356. }
  357. static CK_FUNCTION_LIST_PTR pFunctionList = NULL;
  358. /* These are the static string constants for the DSO file name and the function
  359. * symbol names to bind to.
  360. */
  361. static unsigned char PKCS11_KEY_ID[] = "OpenSSL PKCS#11";
  362. /* String used to detect a CC2000 Bull TrustWay crypto card */
  363. #define BULL_TRUSTWAY_LIBRARY_DESCRIPTION "Bull CC2000 PKCS#11 Library "
  364. static CK_BBOOL Bull_TrustWay = FALSE;
  365. #undef BULL_CC2000 /* use Bull CC2000 hardware crypto */
  366. #undef BULL_CRYPTOBOX /* use Bull CryptoBox remote hardware crypto */
  367. #undef GPKCS11 /* use GPKCS11 software crypto */
  368. #ifdef _LP64
  369. static const char def_PKCS11_LIBNAME[] = "CSNPCA64";
  370. #elif __XPLINK__ /* @P1C */
  371. static const char def_PKCS11_LIBNAME[] = "CSNPCA3X"; /* @D2A */
  372. #else
  373. static const char def_PKCS11_LIBNAME[] = "CSNPCAPI";
  374. #endif
  375. static const char PKCS11_GET_FUNCTION_LIST[] = "C_GetFunctionList";
  376. /* Size of an SSL signature: MD5+SHA1. up to allow SHA512 */
  377. //#define SSL_SIG_LENGTH 64
  378. #define SSL_SIG_LENGTH 36
  379. #define KEY_STORE 1
  380. static CK_BBOOL true = TRUE;
  381. static CK_BBOOL false = FALSE;
  382. static CK_SLOT_ID SLOTID = 0XFFFFFFFF;
  383. /* Where in the CRYPTO_EX_DATA stack we stick our per-key contexts */
  384. static int rsaPubKey = -1;
  385. static int rsaPrivKey = -1;
  386. static int deletePubKeyOnFree = -1;
  387. static int deletePrivKeyOnFree = -1;
  388. static int pkcs11Session = -1;
  389. static int PKCS11_Initialized = 0;
  390. #ifdef PKCS11_DEBUG
  391. #define DBG_fprintf(args...) do { fprintf(stderr, args); fflush(stderr); } while (0)
  392. #else
  393. #define DBG_fprintf(args...)
  394. #endif
  395. void pkcs11_atfork_init(void)
  396. {
  397. DBG_fprintf("pkcs11_atfork_init: called (pid %d)\n", getpid());
  398. PKCS11_Initialized = 0;
  399. }
  400. #define pkcs11_die(func, reason, rv) \
  401. { \
  402. char tmpbuf[20]; \
  403. PKCS11err(func, reason); \
  404. sprintf(tmpbuf, "%lx", rv); \
  405. ERR_add_error_data(2, "PKCS11 CK_RV=0X", tmpbuf); \
  406. }
  407. struct token_session *pkcs11_getSession(void)
  408. {
  409. CK_RV rv;
  410. struct token_session *wrapper;
  411. if (!pkcs11_token) {
  412. PKCS11err(PKCS11_F_GETSESSION, PKCS11_R_NO_SLOT_SELECTED);
  413. return NULL;
  414. }
  415. wrapper = OPENSSL_malloc(sizeof (struct token_session));
  416. if (!wrapper) {
  417. PKCS11err(PKCS11_F_GETSESSION, PKCS11_R_MALLOC_FAILURE);
  418. return NULL;
  419. }
  420. wrapper->token = pkcs11_token;
  421. if (!PKCS11_Initialized) {
  422. rv = pFunctionList->C_Initialize(NULL);
  423. if (rv != CKR_OK && rv != CKR_CRYPTOKI_ALREADY_INITIALIZED) {
  424. pkcs11_die(PKCS11_F_GETSESSION, PKCS11_R_INITIALIZE, rv);
  425. return NULL;
  426. }
  427. PKCS11_Initialized = 1;
  428. }
  429. rv = pFunctionList->C_OpenSession(wrapper->token->slot_id,
  430. CKF_SERIAL_SESSION | CKF_RW_SESSION,
  431. NULL_PTR,
  432. NULL_PTR,
  433. &wrapper->session);
  434. if (rv != CKR_OK) {
  435. pkcs11_die(PKCS11_F_GETSESSION, PKCS11_R_OPENSESSION, rv);
  436. return NULL;
  437. }
  438. return wrapper;
  439. }
  440. char *alg_to_string(int alg_type)
  441. {
  442. switch (alg_type) {
  443. case alg_des:
  444. return "des";
  445. case alg_tdes:
  446. return "tdes";
  447. case alg_aes:
  448. return "aes";
  449. case alg_rsa:
  450. return "rsa";
  451. case alg_sha:
  452. return "sha";
  453. case alg_md5:
  454. return "md5";
  455. case alg_ripemd:
  456. return "ripemd";
  457. default:
  458. return "invalid algorithm";
  459. }
  460. }
  461. /* This internal function is used by ENGINE_pkcs11() and possibly by the
  462. * "dynamic" ENGINE support too */
  463. static int bind_pkcs11(ENGINE *e)
  464. {
  465. DBG_fprintf("%s\n", __FUNCTION__);
  466. if (!ENGINE_set_id(e, engine_pkcs11_id) ||
  467. !ENGINE_set_name(e, engine_pkcs11_name) ||
  468. !ENGINE_set_RAND(e, &pkcs11_random) ||
  469. !ENGINE_set_init_function(e, pkcs11_init) ||
  470. !ENGINE_set_ciphers(e, pkcs11_engine_ciphers) ||
  471. !ENGINE_set_digests(e, pkcs11_engine_digests) ||
  472. !ENGINE_set_destroy_function(e, pkcs11_destroy) ||
  473. !ENGINE_set_finish_function(e, pkcs11_finish) ||
  474. !ENGINE_set_ctrl_function(e, pkcs11_ctrl) ||
  475. !ENGINE_set_cmd_defns(e, pkcs11_cmd_defns))
  476. return 0;
  477. /* Ensure the pkcs11 error handling is set up */
  478. ERR_load_pkcs11_strings();
  479. pre_init_pkcs11(e);
  480. return 1;
  481. }
  482. #ifdef ENGINE_DYNAMIC_SUPPORT
  483. static int bind_helper(ENGINE *e, const char *id)
  484. {
  485. DBG_fprintf("%s\n", __FUNCTION__);
  486. if(id && (strcmp(id, engine_pkcs11_id) != 0))
  487. return 0;
  488. if(!bind_pkcs11(e))
  489. return 0;
  490. return 1;
  491. }
  492. IMPLEMENT_DYNAMIC_CHECK_FN()
  493. IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
  494. #else
  495. static ENGINE *engine_pkcs11(void)
  496. {
  497. DBG_fprintf("%s\n", __FUNCTION__);
  498. ENGINE *ret = ENGINE_new();
  499. if(!ret)
  500. return NULL;
  501. if(!bind_pkcs11(ret))
  502. {
  503. ENGINE_free(ret);
  504. return NULL;
  505. }
  506. pre_init_pkcs11(ret);
  507. return ret;
  508. }
  509. void ENGINE_load_pkcs11(void)
  510. {
  511. DBG_fprintf("%s\n", __FUNCTION__);
  512. ENGINE *e_pkcs11 = engine_pkcs11();
  513. if(!e_pkcs11) return;
  514. ENGINE_add(e_pkcs11);
  515. ENGINE_free(e_pkcs11);
  516. ERR_clear_error();
  517. }
  518. #endif
  519. #define PKCS11_MAX_ALGS 20
  520. static int
  521. get_pkcs11_ciphers(const int **retnids)
  522. {
  523. DBG_fprintf("%s\n", __FUNCTION__);
  524. static int nids[PKCS11_MAX_ALGS];
  525. int i, count = 0, *pkcs11_implemented_ciphers;
  526. if (pkcs11_token)
  527. pkcs11_implemented_ciphers = pkcs11_token->pkcs11_implemented_ciphers;
  528. else {
  529. PKCS11err(PKCS11_F_GET_PKCS11_CIPHERS, PKCS11_R_NO_SLOT_SELECTED);
  530. return 0;
  531. }
  532. memset(nids, 0, sizeof(nids));
  533. *retnids = NULL;
  534. for (i=0; i<NUM_NID; i++) {
  535. if (pkcs11_implemented_ciphers[i])
  536. nids[count++] = i;
  537. }
  538. if (count)
  539. *retnids = nids;
  540. DBG_fprintf("Count %d\n", count);
  541. return count;
  542. }
  543. static int
  544. get_pkcs11_digests(const int **retnids)
  545. {
  546. DBG_fprintf("%s\n", __FUNCTION__);
  547. static int nids[PKCS11_MAX_ALGS];
  548. int i, count = 0, *pkcs11_implemented_digests;
  549. if (pkcs11_token)
  550. pkcs11_implemented_digests = pkcs11_token->pkcs11_implemented_digests;
  551. else {
  552. PKCS11err(PKCS11_F_GET_PKCS11_DIGESTS, PKCS11_R_NO_SLOT_SELECTED);
  553. return 0;
  554. }
  555. memset(nids, 0, sizeof(nids));
  556. *retnids = NULL;
  557. for (i=0; i<NUM_NID; i++) {
  558. if (pkcs11_implemented_digests[i])
  559. nids[count++] = i;
  560. }
  561. if (count)
  562. *retnids = nids;
  563. DBG_fprintf("Count %d\n", count);
  564. return count;
  565. }
  566. /*
  567. * ENGINE calls this to find out how to deal with
  568. * a particular NID in the ENGINE.
  569. */
  570. static int pkcs11_engine_ciphers(ENGINE * e, const EVP_CIPHER ** cipher,
  571. const int **nids, int nid)
  572. {
  573. DBG_fprintf("%s\n", __FUNCTION__);
  574. if (!cipher)
  575. return get_pkcs11_ciphers(nids);
  576. if (!pkcs11_token) {
  577. PKCS11err(PKCS11_F_ENGINE_CIPHERS, PKCS11_R_NO_SLOT_SELECTED);
  578. return 0;
  579. }
  580. /* If the algorithm requested was not added to the list at
  581. * engine init time, don't return a reference to that structure.
  582. */
  583. if (pkcs11_token->pkcs11_implemented_ciphers[nid]) {
  584. switch (nid) {
  585. case NID_aes_128_ecb:
  586. *cipher = pkcs11_aes_128_ecb();
  587. break;
  588. case NID_aes_192_ecb:
  589. *cipher = pkcs11_aes_192_ecb();
  590. break;
  591. case NID_aes_256_ecb:
  592. *cipher = pkcs11_aes_256_ecb();
  593. break;
  594. case NID_aes_128_cbc:
  595. *cipher = pkcs11_aes_128_cbc();
  596. break;
  597. case NID_aes_192_cbc:
  598. *cipher = pkcs11_aes_192_cbc();
  599. break;
  600. case NID_aes_256_cbc:
  601. *cipher = pkcs11_aes_256_cbc();
  602. break;
  603. case NID_des_ecb:
  604. *cipher = pkcs11_des_ecb();
  605. break;
  606. case NID_des_cbc:
  607. *cipher = pkcs11_des_cbc();
  608. break;
  609. case NID_des_ede3_ecb:
  610. *cipher = pkcs11_tdes_ecb();
  611. break;
  612. case NID_des_ede3_cbc:
  613. *cipher = pkcs11_tdes_cbc();
  614. break;
  615. default:
  616. *cipher = NULL;
  617. break;
  618. }
  619. }
  620. return (*cipher != NULL);
  621. }
  622. static int pkcs11_engine_digests(ENGINE * e, const EVP_MD ** digest,
  623. const int **nids, int nid)
  624. {
  625. DBG_fprintf("%s\n", __FUNCTION__);
  626. if (!digest)
  627. return get_pkcs11_digests(nids);
  628. if (!pkcs11_token) {
  629. PKCS11err(PKCS11_F_ENGINE_DIGESTS, PKCS11_R_NO_SLOT_SELECTED);
  630. return 0;
  631. }
  632. if (pkcs11_token->pkcs11_implemented_digests[nid]) {
  633. switch (nid) {
  634. case NID_ripemd160:
  635. *digest = pkcs11_ripemd160();
  636. break;
  637. case NID_md5:
  638. *digest = pkcs11_md5();
  639. break;
  640. case NID_sha1:
  641. *digest = pkcs11_sha1();
  642. break;
  643. case NID_sha224:
  644. *digest = pkcs11_sha224();
  645. break;
  646. case NID_sha256:
  647. *digest = pkcs11_sha256();
  648. break;
  649. case NID_sha384:
  650. *digest = pkcs11_sha384();
  651. break;
  652. case NID_sha512:
  653. *digest = pkcs11_sha512();
  654. break;
  655. default:
  656. *digest = NULL;
  657. break;
  658. }
  659. }
  660. return (*digest != NULL);
  661. }
  662. void *pkcs11_dso = NULL;
  663. /* These are the static string constants for the DSO file name and the function
  664. * symbol names to bind to.
  665. */
  666. static const char *PKCS11_LIBNAME = NULL;
  667. static const char *get_PKCS11_LIBNAME(void)
  668. {
  669. if(PKCS11_LIBNAME)
  670. return PKCS11_LIBNAME;
  671. return def_PKCS11_LIBNAME;
  672. }
  673. static void free_PKCS11_LIBNAME(void)
  674. {
  675. if(PKCS11_LIBNAME)
  676. OPENSSL_free((void*)PKCS11_LIBNAME);
  677. PKCS11_LIBNAME = NULL;
  678. }
  679. static long set_PKCS11_LIBNAME(const char *name)
  680. {
  681. free_PKCS11_LIBNAME();
  682. return ((PKCS11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
  683. }
  684. /* Add new NID's based on this slot's token */
  685. void pkcs11_regToken(ENGINE *e, struct _token *tok)
  686. {
  687. CK_RV rv;
  688. CK_ULONG mech_cnt;
  689. CK_MECHANISM_TYPE_PTR mech_list;
  690. int i;
  691. DBG_fprintf("%s\n", __FUNCTION__);
  692. if (!tok)
  693. return;
  694. rv = pFunctionList->C_GetMechanismList(tok->slot_id, NULL_PTR, &mech_cnt);
  695. if (rv != CKR_OK) {
  696. pkcs11_die(PKCS11_F_ADDTOKEN, PKCS11_R_GETMECHANISMLIST, rv);
  697. goto err;
  698. }
  699. /* Bounds check mech_cnt ? */
  700. mech_list = (CK_MECHANISM_TYPE_PTR) OPENSSL_malloc(mech_cnt * sizeof(CK_MECHANISM_TYPE));
  701. if (mech_list == NULL) {
  702. pkcs11_die(PKCS11_F_ADDTOKEN, PKCS11_R_MALLOC_FAILURE, rv);
  703. goto err;
  704. }
  705. rv = pFunctionList->C_GetMechanismList(tok->slot_id, mech_list, &mech_cnt);
  706. if (rv != CKR_OK) {
  707. pkcs11_die(PKCS11_F_ADDTOKEN, PKCS11_R_GETMECHANISMLIST, rv);
  708. goto err_free;
  709. }
  710. /* Check which mechanisms are performed in hardware */
  711. for( i = 0; i < mech_cnt; i++ ) {
  712. switch (mech_list[i]) {
  713. case CKM_RSA_PKCS_PSS:
  714. case CKM_SHA1_RSA_PKCS_PSS:
  715. case CKM_RSA_PKCS_KEY_PAIR_GEN:
  716. case CKM_MD2_RSA_PKCS:
  717. case CKM_RSA_PKCS:
  718. case CKM_RSA_9796:
  719. case CKM_RSA_X_509:
  720. case CKM_RSA_PKCS_OAEP:
  721. case CKM_RSA_X9_31:
  722. case CKM_RSA_X9_31_KEY_PAIR_GEN:
  723. DBG_fprintf("%s: registering RSA\n", __FUNCTION__);
  724. ENGINE_set_RSA(e, pkcs11_rsa);
  725. pkcs11_rsa = RSA_meth_new("PKCS#11 RSA", 0);
  726. RSA_meth_set_pub_enc(pkcs11_rsa, pkcs11_RSA_public_encrypt);
  727. RSA_meth_set_pub_dec(pkcs11_rsa, pkcs11_RSA_public_decrypt);
  728. RSA_meth_set_priv_enc(pkcs11_rsa, pkcs11_RSA_private_encrypt);
  729. RSA_meth_set_priv_dec(pkcs11_rsa, pkcs11_RSA_private_decrypt);
  730. RSA_meth_set_init(pkcs11_rsa, pkcs11_RSA_init);
  731. RSA_meth_set_finish(pkcs11_rsa, pkcs11_RSA_finish);
  732. RSA_meth_set_keygen(pkcs11_rsa, pkcs11_RSA_generate_key);
  733. ENGINE_set_load_privkey_function(e, pkcs11_load_privkey);
  734. ENGINE_set_load_pubkey_function(e, pkcs11_load_pubkey);
  735. break;
  736. case CKM_DSA_PARAMETER_GEN:
  737. // TODO: Implement DSA
  738. break;
  739. case CKM_DH_PKCS_KEY_PAIR_GEN:
  740. case CKM_DH_PKCS_DERIVE:
  741. case CKM_X9_42_DH_KEY_PAIR_GEN:
  742. case CKM_X9_42_DH_DERIVE:
  743. case CKM_X9_42_DH_HYBRID_DERIVE:
  744. case CKM_DH_PKCS_PARAMETER_GEN:
  745. case CKM_X9_42_DH_PARAMETER_GEN:
  746. break;
  747. case CKM_DES_ECB:
  748. tok->pkcs11_implemented_ciphers[NID_des_ecb] = 1;
  749. num_cipher_nids++;
  750. break;
  751. case CKM_DES_CBC:
  752. case CKM_DES_CBC_PAD:
  753. tok->pkcs11_implemented_ciphers[NID_des_cbc] = 1;
  754. num_cipher_nids++;
  755. break;
  756. case CKM_DES_KEY_GEN:
  757. case CKM_DES_MAC:
  758. case CKM_DES_MAC_GENERAL:
  759. break;
  760. case CKM_DES3_ECB:
  761. tok->pkcs11_implemented_ciphers[NID_des_ede3_ecb] = 1;
  762. num_cipher_nids++;
  763. break;
  764. case CKM_DES3_CBC:
  765. case CKM_DES3_CBC_PAD:
  766. tok->pkcs11_implemented_ciphers[NID_des_ede3_cbc] = 1;
  767. num_cipher_nids++;
  768. break;
  769. case CKM_DES3_KEY_GEN:
  770. case CKM_DES3_MAC:
  771. case CKM_DES3_MAC_GENERAL:
  772. break;
  773. case CKM_SHA_1:
  774. tok->pkcs11_implemented_digests[NID_sha1] = 1;
  775. num_digest_nids++;
  776. break;
  777. case CKM_SHA_1_HMAC:
  778. case CKM_SHA_1_HMAC_GENERAL:
  779. tok->pkcs11_implemented_digests[NID_hmacWithSHA1] = 1;
  780. num_digest_nids++;
  781. break;
  782. case CKM_PBA_SHA1_WITH_SHA1_HMAC:
  783. case CKM_SHA1_KEY_DERIVATION:
  784. case CKM_SHA1_RSA_PKCS:
  785. tok->pkcs11_implemented_digests[NID_sha1WithRSAEncryption] = 1;
  786. num_digest_nids++;
  787. break;
  788. case CKM_SHA224:
  789. tok->pkcs11_implemented_digests[NID_sha224] = 1;
  790. num_digest_nids++;
  791. break;
  792. case CKM_SHA224_KEY_DERIVATION:
  793. case CKM_SHA224_RSA_PKCS:
  794. tok->pkcs11_implemented_digests[NID_sha224WithRSAEncryption] = 1;
  795. num_digest_nids++;
  796. break;
  797. case CKM_SHA256:
  798. tok->pkcs11_implemented_digests[NID_sha256] = 1;
  799. num_digest_nids++;
  800. break;
  801. case CKM_SHA256_KEY_DERIVATION:
  802. case CKM_SHA256_RSA_PKCS:
  803. tok->pkcs11_implemented_digests[NID_sha256WithRSAEncryption] = 1;
  804. num_digest_nids++;
  805. break;
  806. case CKM_SHA384:
  807. tok->pkcs11_implemented_digests[NID_sha384] = 1;
  808. num_digest_nids++;
  809. break;
  810. case CKM_SHA384_KEY_DERIVATION:
  811. case CKM_SHA384_RSA_PKCS:
  812. tok->pkcs11_implemented_digests[NID_sha384WithRSAEncryption] = 1;
  813. num_digest_nids++;
  814. break;
  815. case CKM_SHA512:
  816. tok->pkcs11_implemented_digests[NID_sha512] = 1;
  817. num_digest_nids++;
  818. break;
  819. case CKM_SHA512_KEY_DERIVATION:
  820. case CKM_SHA512_RSA_PKCS:
  821. tok->pkcs11_implemented_digests[NID_sha512WithRSAEncryption] = 1;
  822. num_digest_nids++;
  823. break;
  824. case CKM_AES_ECB:
  825. tok->pkcs11_implemented_ciphers[NID_aes_128_ecb] = 1;
  826. tok->pkcs11_implemented_ciphers[NID_aes_192_ecb] = 1;
  827. tok->pkcs11_implemented_ciphers[NID_aes_256_ecb] = 1;
  828. num_cipher_nids += 3;
  829. break;
  830. case CKM_AES_KEY_GEN:
  831. break;
  832. case CKM_AES_CBC_PAD:
  833. case CKM_AES_CBC:
  834. tok->pkcs11_implemented_ciphers[NID_aes_128_cbc] = 1;
  835. tok->pkcs11_implemented_ciphers[NID_aes_192_cbc] = 1;
  836. tok->pkcs11_implemented_ciphers[NID_aes_256_cbc] = 1;
  837. num_cipher_nids += 3;
  838. break;
  839. case CKM_AES_MAC:
  840. case CKM_AES_MAC_GENERAL:
  841. break;
  842. case CKM_MD5_RSA_PKCS:
  843. case CKM_MD5:
  844. tok->pkcs11_implemented_digests[NID_md5] = 1;
  845. num_digest_nids++;
  846. break;
  847. case CKM_MD5_HMAC:
  848. case CKM_MD5_HMAC_GENERAL:
  849. case CKM_SSL3_PRE_MASTER_KEY_GEN:
  850. case CKM_SSL3_MASTER_KEY_DERIVE:
  851. case CKM_SSL3_KEY_AND_MAC_DERIVE:
  852. case CKM_SSL3_MD5_MAC:
  853. case CKM_SSL3_SHA1_MAC:
  854. break;
  855. case CKM_RIPEMD160:
  856. tok->pkcs11_implemented_digests[NID_ripemd160] = 1;
  857. num_digest_nids++;
  858. break;
  859. case CKM_RIPEMD160_HMAC:
  860. case CKM_RIPEMD160_HMAC_GENERAL:
  861. break;
  862. default:
  863. DBG_fprintf("The token in slot %lx has reported that it can "
  864. "perform\nmechanism 0x%lx, which is not available to "
  865. "accelerate in openssl.\n", tok->slot_id, mech_list[i]);
  866. break;
  867. }
  868. }
  869. return;
  870. err_free:
  871. OPENSSL_free(mech_list);
  872. err:
  873. return;
  874. }
  875. /* Add a new token struct to the list
  876. * This is called during the bind_pkcs11, in other words after openSSL has
  877. * decided to use us for some operation.
  878. */
  879. struct _token *pkcs11_addToken(CK_SLOT_ID slot_id)
  880. {
  881. struct _token *new_tok = (struct _token *) OPENSSL_malloc(sizeof(struct _token));
  882. if (new_tok == NULL) {
  883. PKCS11err(PKCS11_F_ADDTOKEN, PKCS11_R_MALLOC_FAILURE);
  884. return NULL;
  885. }
  886. memset(new_tok, 0, sizeof(struct _token));
  887. new_tok->slot_id = slot_id;
  888. new_tok->token_next = pkcs11_token_list;
  889. pkcs11_token_list = new_tok;
  890. return new_tok;
  891. }
  892. /*
  893. * pre_init_pkcs11: this is called at openSSL startup. Here is where we
  894. * try to convince openSSL to use us. If it decides not to, there is no
  895. * guarantee that we will ever be asked to clean up. So everything we
  896. * do must be self-contained.
  897. */
  898. static int pre_init_pkcs11(ENGINE *e)
  899. {
  900. CK_C_GetFunctionList p;
  901. CK_RV rv = CKR_OK;
  902. CK_INFO Info;
  903. CK_SLOT_ID_PTR pSlotList;
  904. CK_ULONG ulSlotCount;
  905. CK_SLOT_INFO slotInfo;
  906. struct _token *tok;
  907. int i;
  908. if(pkcs11_dso)
  909. {
  910. PKCS11err(PKCS11_F_PREINIT, PKCS11_R_ALREADY_LOADED);
  911. goto err;
  912. }
  913. /* Attempt to load PKCS#11 library */
  914. pkcs11_dso = dlopen(get_PKCS11_LIBNAME(), RTLD_NOW);
  915. if(pkcs11_dso == NULL)
  916. {
  917. PKCS11err(PKCS11_F_PREINIT, PKCS11_R_DSO_FAILURE);
  918. goto err;
  919. }
  920. /* get the C_GetFunctionList function from the loaded library */
  921. p = (CK_C_GetFunctionList)dlsym(pkcs11_dso, PKCS11_GET_FUNCTION_LIST);
  922. if ( !p )
  923. {
  924. PKCS11err(PKCS11_F_PREINIT, PKCS11_R_DSO_FAILURE);
  925. goto err;
  926. }
  927. /* get the full function list from the loaded library */
  928. rv = p(&pFunctionList);
  929. if (rv != CKR_OK)
  930. {
  931. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_DSO_FAILURE, rv);
  932. goto err;
  933. }
  934. /* Initialize Cryptoki */
  935. rv = pFunctionList->C_Initialize(NULL_PTR);
  936. if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
  937. {
  938. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_INITIALIZE, rv);
  939. goto err;
  940. }
  941. rv = pFunctionList->C_GetInfo(&Info);
  942. if (rv != CKR_OK)
  943. {
  944. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_GETINFO, rv);
  945. pFunctionList->C_Finalize(NULL);
  946. goto err;
  947. }
  948. if (strncmp((char *)Info.libraryDescription, BULL_TRUSTWAY_LIBRARY_DESCRIPTION, 32))
  949. {
  950. rv = pFunctionList->C_GetSlotList(TRUE, NULL_PTR, &ulSlotCount);
  951. if ((rv != CKR_OK) || (ulSlotCount == 0))
  952. {
  953. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_GETSLOTLIST, rv);
  954. }
  955. else
  956. {
  957. pSlotList = (CK_SLOT_ID_PTR) OPENSSL_malloc(ulSlotCount * sizeof(CK_SLOT_ID));
  958. if ( pSlotList != NULL)
  959. {
  960. rv = pFunctionList->C_GetSlotList(TRUE, pSlotList, &ulSlotCount);
  961. if (rv != CKR_OK)
  962. {
  963. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_GETSLOTLIST, rv);
  964. pFunctionList->C_Finalize(NULL);
  965. OPENSSL_free(pSlotList);
  966. goto err;
  967. }
  968. /* Check each slot to see if there's a hardware token present.
  969. */
  970. for (i = 0; i < ulSlotCount; i++)
  971. {
  972. rv = pFunctionList->C_GetSlotInfo(pSlotList[i], &slotInfo);
  973. if (rv != CKR_OK)
  974. {
  975. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_GETSLOTINFO,
  976. rv);
  977. pFunctionList->C_Finalize(NULL);
  978. OPENSSL_free(pSlotList);
  979. goto err;
  980. }
  981. /* we're mallocing memory here that may need to be freed
  982. * if openssl chooses not to use us. We'll free it in
  983. * the library destructor, pkcs11_engine_destructor */
  984. tok = pkcs11_addToken(pSlotList[i]);
  985. pkcs11_regToken(e, tok);
  986. }
  987. OPENSSL_free(pSlotList);
  988. }
  989. }
  990. }
  991. else
  992. {
  993. /* Bull Trustway CC2000 crypto hardware detected */
  994. Bull_TrustWay = TRUE;
  995. SLOTID = 0xFFFFFFFF;
  996. }
  997. /* Finish with Cryptoki: We will restart if openSSL calls one of our
  998. * functions */
  999. pFunctionList->C_Finalize(NULL);
  1000. dlclose(pkcs11_dso);
  1001. pkcs11_dso = NULL;
  1002. return 1;
  1003. err:
  1004. if(pkcs11_dso)
  1005. dlclose(pkcs11_dso);
  1006. pkcs11_dso = NULL;
  1007. return 0;
  1008. }
  1009. /* initialization function */
  1010. /* This is called when openSSL has decided to use us, and warns us to
  1011. * initialize. pkcs11_finish will be called when all is done. */
  1012. static int pkcs11_init(ENGINE *e)
  1013. {
  1014. DBG_fprintf("%s\n", __FUNCTION__);
  1015. CK_C_GetFunctionList p;
  1016. CK_RV rv = CKR_OK;
  1017. CK_INFO Info;
  1018. CK_SLOT_ID_PTR pSlotList;
  1019. CK_ULONG ulSlotCount;
  1020. CK_SLOT_INFO slotInfo;
  1021. int i;
  1022. if(pkcs11_dso)
  1023. {
  1024. PKCS11err(PKCS11_F_INIT, PKCS11_R_ALREADY_LOADED);
  1025. goto err;
  1026. }
  1027. /* Attempt to load PKCS#11 library */
  1028. pkcs11_dso = dlopen(get_PKCS11_LIBNAME(), RTLD_NOW);
  1029. if(pkcs11_dso == NULL)
  1030. {
  1031. PKCS11err(PKCS11_F_INIT, PKCS11_R_DSO_FAILURE);
  1032. goto err;
  1033. }
  1034. /* get the C_GetFunctionList function from the loaded library */
  1035. p = (CK_C_GetFunctionList)dlsym(pkcs11_dso, PKCS11_GET_FUNCTION_LIST);
  1036. if ( !p )
  1037. {
  1038. PKCS11err(PKCS11_F_INIT, PKCS11_R_DSO_FAILURE);
  1039. goto err;
  1040. }
  1041. /* get the full function list from the loaded library */
  1042. rv = p(&pFunctionList);
  1043. if (rv != CKR_OK)
  1044. {
  1045. pkcs11_die(PKCS11_F_INIT, PKCS11_R_DSO_FAILURE, rv);
  1046. goto err;
  1047. }
  1048. rv = pFunctionList->C_Initialize(NULL_PTR);
  1049. if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
  1050. {
  1051. pkcs11_die(PKCS11_F_INIT, PKCS11_R_INITIALIZE, rv);
  1052. goto err;
  1053. }
  1054. rv = pFunctionList->C_GetInfo(&Info);
  1055. if (rv != CKR_OK)
  1056. {
  1057. pkcs11_die(PKCS11_F_INIT, PKCS11_R_GETINFO, rv);
  1058. pFunctionList->C_Finalize(NULL);
  1059. goto err;
  1060. }
  1061. if (strncmp((char *)Info.libraryDescription, BULL_TRUSTWAY_LIBRARY_DESCRIPTION, 32))
  1062. {
  1063. rv = pFunctionList->C_GetSlotList(TRUE, NULL_PTR, &ulSlotCount);
  1064. if ((rv != CKR_OK) || (ulSlotCount == 0))
  1065. {
  1066. pkcs11_die(PKCS11_F_INIT, PKCS11_R_GETSLOTLIST, rv);
  1067. }
  1068. else
  1069. {
  1070. pSlotList = (CK_SLOT_ID_PTR) OPENSSL_malloc(ulSlotCount * sizeof(CK_SLOT_ID));
  1071. if ( pSlotList != NULL)
  1072. {
  1073. rv = pFunctionList->C_GetSlotList(TRUE, pSlotList, &ulSlotCount);
  1074. if (rv != CKR_OK)
  1075. {
  1076. pkcs11_die(PKCS11_F_INIT, PKCS11_R_GETSLOTLIST, rv);
  1077. pFunctionList->C_Finalize(NULL);
  1078. OPENSSL_free(pSlotList);
  1079. goto err;
  1080. }
  1081. /* Check each slot to see if there's a hardware token present.
  1082. */
  1083. for (i = 0; i < ulSlotCount; i++)
  1084. {
  1085. rv = pFunctionList->C_GetSlotInfo(pSlotList[i], &slotInfo);
  1086. if (rv != CKR_OK)
  1087. {
  1088. pkcs11_die(PKCS11_F_INIT, PKCS11_R_GETSLOTINFO, rv);
  1089. pFunctionList->C_Finalize(NULL);
  1090. OPENSSL_free(pSlotList);
  1091. goto err;
  1092. }
  1093. pkcs11_addToken(pSlotList[i]);
  1094. }
  1095. OPENSSL_free(pSlotList);
  1096. }
  1097. }
  1098. }
  1099. else
  1100. {
  1101. /* Bull Trustway CC2000 crypto hardware detected */
  1102. Bull_TrustWay = TRUE;
  1103. SLOTID = 0xFFFFFFFF;
  1104. }
  1105. /* Everything's fine. */
  1106. if (rsaPubKey == -1)
  1107. rsaPubKey = RSA_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1108. if (rsaPrivKey == -1)
  1109. rsaPrivKey = RSA_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1110. if (deletePubKeyOnFree == -1)
  1111. deletePubKeyOnFree = RSA_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1112. if (deletePrivKeyOnFree == -1)
  1113. deletePrivKeyOnFree = RSA_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1114. if (pkcs11Session == -1)
  1115. pkcs11Session = RSA_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1116. if (pkcs11_token_list == NULL)
  1117. PKCS11err(PKCS11_F_INIT, PKCS11_R_NOTOKENS);
  1118. PKCS11_Initialized = 1;
  1119. /* TODO: This should only be done on linux systems */
  1120. pthread_atfork(NULL, NULL, (void(*)())pkcs11_atfork_init);
  1121. return 1;
  1122. err:
  1123. if(pkcs11_dso)
  1124. dlclose(pkcs11_dso);
  1125. pkcs11_dso = NULL;
  1126. return 0;
  1127. }
  1128. /* Destructor (complements the "ENGINE_pkcs11()" constructor) */
  1129. /* XXX HUH? Can we just DSO_load once, then??? */
  1130. static int pkcs11_destroy(ENGINE *e)
  1131. {
  1132. DBG_fprintf("%s: called\n", __FUNCTION__);
  1133. pkcs11_des_ecb_destroy();
  1134. pkcs11_des_cbc_destroy();
  1135. pkcs11_tdes_ecb_destroy();
  1136. pkcs11_tdes_cbc_destroy();
  1137. pkcs11_aes_128_cbc_destroy();
  1138. pkcs11_aes_192_cbc_destroy();
  1139. pkcs11_aes_256_cbc_destroy();
  1140. pkcs11_aes_128_ecb_destroy();
  1141. pkcs11_aes_192_ecb_destroy();
  1142. pkcs11_aes_256_ecb_destroy();
  1143. pkcs11_sha1_destroy();
  1144. pkcs11_sha224_destroy();
  1145. pkcs11_sha256_destroy();
  1146. pkcs11_sha384_destroy();
  1147. pkcs11_sha512_destroy();
  1148. pkcs11_md5_destroy();
  1149. pkcs11_ripemd160_destroy();
  1150. free_PKCS11_LIBNAME();
  1151. ERR_unload_pkcs11_strings();
  1152. return 1;
  1153. }
  1154. /* termination function */
  1155. static int pkcs11_finish(ENGINE *e)
  1156. {
  1157. struct _token *tmp;
  1158. if(pkcs11_dso == NULL)
  1159. {
  1160. PKCS11err(PKCS11_F_FINISH, PKCS11_R_NOT_LOADED);
  1161. goto err;
  1162. }
  1163. assert(pFunctionList != NULL);
  1164. while (pkcs11_token_list) {
  1165. tmp = pkcs11_token_list->token_next;
  1166. OPENSSL_free(pkcs11_token_list);
  1167. pkcs11_token_list = tmp;
  1168. }
  1169. pFunctionList->C_Finalize(NULL);
  1170. if(dlclose(pkcs11_dso))
  1171. { PKCS11err(PKCS11_F_FINISH, PKCS11_R_DSO_FAILURE);
  1172. goto err;
  1173. }
  1174. pkcs11_dso = NULL;
  1175. pFunctionList = NULL;
  1176. return 1;
  1177. err:
  1178. pkcs11_dso = NULL;
  1179. pFunctionList = NULL;
  1180. return 0;
  1181. }
  1182. static int pkcs11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
  1183. {
  1184. DBG_fprintf("%s\n", __FUNCTION__);
  1185. int initialized = ((pkcs11_dso == NULL) ? 0 : 1);
  1186. struct _token *tok;
  1187. switch(cmd)
  1188. {
  1189. case PKCS11_CMD_SO_PATH:
  1190. if(p == NULL)
  1191. {
  1192. PKCS11err(PKCS11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
  1193. return 0;
  1194. }
  1195. if(initialized)
  1196. {
  1197. PKCS11err(PKCS11_F_CTRL, PKCS11_R_ALREADY_LOADED);
  1198. return 0;
  1199. }
  1200. return set_PKCS11_LIBNAME((const char*)p);
  1201. case PKCS11_CMD_SLOT_ID:
  1202. tok = pkcs11_token_list;
  1203. while (tok) {
  1204. if (tok->slot_id == i) {
  1205. pkcs11_token = tok;
  1206. DBG_fprintf("slot %ld selected\n", i);
  1207. return 1;
  1208. }
  1209. tok = tok->token_next;
  1210. }
  1211. PKCS11err(PKCS11_F_CTRL, PKCS11_R_TOKEN_NOT_AVAILABLE);
  1212. return 0;
  1213. default:
  1214. break;
  1215. }
  1216. PKCS11err(PKCS11_F_CTRL,PKCS11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
  1217. return 0;
  1218. }
  1219. CK_OBJECT_HANDLE pkcs11_FindOrCreateKey(CK_SESSION_HANDLE h,
  1220. RSA *rsa,
  1221. CK_OBJECT_CLASS oKey,
  1222. CK_BBOOL fKeyCreate)
  1223. {
  1224. CK_RV rv;
  1225. CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE;
  1226. CK_ULONG Matches;
  1227. CK_KEY_TYPE kType = CKK_RSA;
  1228. CK_ULONG ulKeyAttributeCount;
  1229. const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp;
  1230. CK_ATTRIBUTE pubKeyTemplate[] =
  1231. {
  1232. {CKA_CLASS, &oKey, sizeof(CK_OBJECT_CLASS)},
  1233. {CKA_KEY_TYPE, &kType, sizeof(CK_KEY_TYPE)},
  1234. {CKA_MODULUS, (void *)NULL, 0},
  1235. {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
  1236. };
  1237. CK_ATTRIBUTE privKeyTemplate[] =
  1238. {
  1239. {CKA_CLASS, &oKey, sizeof(CK_OBJECT_CLASS)},
  1240. {CKA_KEY_TYPE, &kType, sizeof(CK_KEY_TYPE)},
  1241. {CKA_MODULUS, (void *)NULL, 0},
  1242. {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
  1243. {CKA_PRIVATE_EXPONENT, (void *)NULL, 0},
  1244. {CKA_PRIME_1, (void *)NULL, 0},
  1245. {CKA_PRIME_2, (void *)NULL, 0},
  1246. {CKA_EXPONENT_1, (void *)NULL, 0},
  1247. {CKA_EXPONENT_2, (void *)NULL, 0},
  1248. {CKA_COEFFICIENT, (void *)NULL, 0}
  1249. };
  1250. long deletePubKey;
  1251. DBG_fprintf("%s\n", __FUNCTION__);
  1252. if (oKey == CKO_PUBLIC_KEY) {
  1253. DBG_fprintf("looking up a public key\n");
  1254. RSA_get0_key(rsa, &n, &e, NULL);
  1255. pubKeyTemplate[2].ulValueLen = BN_num_bytes(n);
  1256. pubKeyTemplate[3].ulValueLen = BN_num_bytes(e);
  1257. pubKeyTemplate[2].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)pubKeyTemplate[2].ulValueLen);
  1258. pubKeyTemplate[3].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)pubKeyTemplate[3].ulValueLen);
  1259. BN_bn2bin(n, pubKeyTemplate[2].pValue);
  1260. BN_bn2bin(e, pubKeyTemplate[3].pValue);
  1261. ulKeyAttributeCount = 4;
  1262. rv = pFunctionList->C_FindObjectsInit(h, pubKeyTemplate, ulKeyAttributeCount);
  1263. } else {
  1264. DBG_fprintf("looking up a private key\n");
  1265. RSA_get0_key(rsa, &n, &e, &d);
  1266. RSA_get0_factors(rsa, &p, &q);
  1267. RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
  1268. privKeyTemplate[2].ulValueLen = BN_num_bytes(n);
  1269. privKeyTemplate[3].ulValueLen = BN_num_bytes(e);
  1270. privKeyTemplate[4].ulValueLen = BN_num_bytes(d);
  1271. privKeyTemplate[5].ulValueLen = BN_num_bytes(p);
  1272. privKeyTemplate[6].ulValueLen = BN_num_bytes(q);
  1273. privKeyTemplate[7].ulValueLen = BN_num_bytes(dmp1);
  1274. privKeyTemplate[8].ulValueLen = BN_num_bytes(dmq1);
  1275. privKeyTemplate[9].ulValueLen = BN_num_bytes(iqmp);
  1276. privKeyTemplate[2].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[2].ulValueLen);
  1277. privKeyTemplate[3].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[3].ulValueLen);
  1278. privKeyTemplate[4].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[4].ulValueLen);
  1279. privKeyTemplate[5].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[5].ulValueLen);
  1280. privKeyTemplate[6].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[6].ulValueLen);
  1281. privKeyTemplate[7].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[7].ulValueLen);
  1282. privKeyTemplate[8].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[8].ulValueLen);
  1283. privKeyTemplate[9].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[9].ulValueLen);
  1284. BN_bn2bin(n, privKeyTemplate[2].pValue);
  1285. BN_bn2bin(e, privKeyTemplate[3].pValue);
  1286. BN_bn2bin(d, privKeyTemplate[4].pValue);
  1287. BN_bn2bin(p, privKeyTemplate[5].pValue);
  1288. BN_bn2bin(q, privKeyTemplate[6].pValue);
  1289. BN_bn2bin(dmp1, privKeyTemplate[7].pValue);
  1290. BN_bn2bin(dmq1, privKeyTemplate[8].pValue);
  1291. BN_bn2bin(iqmp, privKeyTemplate[9].pValue);
  1292. ulKeyAttributeCount = 10;
  1293. rv = pFunctionList->C_FindObjectsInit(h, privKeyTemplate, ulKeyAttributeCount);
  1294. }
  1295. if (rv != CKR_OK)
  1296. {
  1297. pkcs11_die(PKCS11_F_FINDORCREATEKEY, PKCS11_R_FINDOBJECTSINIT, rv);
  1298. goto err;
  1299. }
  1300. rv = pFunctionList->C_FindObjects(h, &hKey, 1, &Matches);
  1301. if (rv != CKR_OK)
  1302. {
  1303. pkcs11_die(PKCS11_F_FINDORCREATEKEY, PKCS11_R_FINDOBJECTS, rv);
  1304. goto err;
  1305. }
  1306. rv = pFunctionList->C_FindObjectsFinal(h);
  1307. if (rv != CKR_OK)
  1308. {
  1309. pkcs11_die(PKCS11_F_FINDORCREATEKEY, PKCS11_R_FINDOBJECTSFINAL, rv);
  1310. goto err;
  1311. }
  1312. /* Assume there should be no more than one match */
  1313. if (Matches == 0)
  1314. {
  1315. DBG_fprintf("matches was 0, creating this key\n");
  1316. DBG_fprintf("rsa->n is %d bytes\n", BN_num_bytes(n));
  1317. if (fKeyCreate &&
  1318. BN_num_bytes(n)
  1319. ) {
  1320. if (oKey == CKO_PUBLIC_KEY)
  1321. rv = pFunctionList->C_CreateObject(h, pubKeyTemplate,
  1322. ulKeyAttributeCount, &hKey);
  1323. else
  1324. rv = pFunctionList->C_CreateObject(h, privKeyTemplate,
  1325. ulKeyAttributeCount, &hKey);
  1326. if (rv != CKR_OK)
  1327. {
  1328. DBG_fprintf("error creating key object.\n");
  1329. pkcs11_die(PKCS11_F_FINDORCREATEKEY, PKCS11_R_CREATEOBJECT, rv);
  1330. goto err;
  1331. }
  1332. else
  1333. {
  1334. DBG_fprintf("key obj created\n");
  1335. deletePubKey = TRUE;
  1336. if (oKey == CKO_PUBLIC_KEY)
  1337. RSA_set_ex_data(rsa, deletePubKeyOnFree,
  1338. (void *)deletePubKey);
  1339. else
  1340. RSA_set_ex_data(rsa, deletePrivKeyOnFree,
  1341. (void *)deletePubKey);
  1342. }
  1343. }
  1344. else
  1345. {
  1346. PKCS11err(PKCS11_F_FINDORCREATEKEY, PKCS11_R_OBJECT_NOT_FOUND);
  1347. goto err;
  1348. }
  1349. }
  1350. if (oKey == CKO_PUBLIC_KEY)
  1351. RSA_set_ex_data(rsa, rsaPubKey, (char *)hKey);
  1352. if (oKey == CKO_PRIVATE_KEY)
  1353. RSA_set_ex_data(rsa, rsaPrivKey, (char *)hKey);
  1354. err:
  1355. if (oKey == CKO_PUBLIC_KEY) {
  1356. if (pubKeyTemplate[2].pValue != NULL)
  1357. {
  1358. OPENSSL_free(pubKeyTemplate[2].pValue);
  1359. pubKeyTemplate[2].pValue = NULL;
  1360. }
  1361. if (pubKeyTemplate[3].pValue != NULL)
  1362. {
  1363. OPENSSL_free(pubKeyTemplate[3].pValue);
  1364. pubKeyTemplate[3].pValue = NULL;
  1365. }
  1366. } else {
  1367. if (privKeyTemplate[2].pValue != NULL)
  1368. {
  1369. OPENSSL_free(privKeyTemplate[2].pValue);
  1370. privKeyTemplate[2].pValue = NULL;
  1371. }
  1372. if (privKeyTemplate[3].pValue != NULL)
  1373. {
  1374. OPENSSL_free(privKeyTemplate[3].pValue);
  1375. privKeyTemplate[3].pValue = NULL;
  1376. }
  1377. if (privKeyTemplate[4].pValue != NULL)
  1378. {
  1379. OPENSSL_free(privKeyTemplate[4].pValue);
  1380. privKeyTemplate[4].pValue = NULL;
  1381. }
  1382. if (privKeyTemplate[5].pValue != NULL)
  1383. {
  1384. OPENSSL_free(privKeyTemplate[5].pValue);
  1385. privKeyTemplate[5].pValue = NULL;
  1386. }
  1387. if (privKeyTemplate[6].pValue != NULL)
  1388. {
  1389. OPENSSL_free(privKeyTemplate[6].pValue);
  1390. privKeyTemplate[6].pValue = NULL;
  1391. }
  1392. if (privKeyTemplate[7].pValue != NULL)
  1393. {
  1394. OPENSSL_free(privKeyTemplate[7].pValue);
  1395. privKeyTemplate[7].pValue = NULL;
  1396. }
  1397. if (privKeyTemplate[8].pValue != NULL)
  1398. {
  1399. OPENSSL_free(privKeyTemplate[8].pValue);
  1400. privKeyTemplate[8].pValue = NULL;
  1401. }
  1402. if (privKeyTemplate[9].pValue != NULL)
  1403. {
  1404. OPENSSL_free(privKeyTemplate[9].pValue);
  1405. privKeyTemplate[9].pValue = NULL;
  1406. }
  1407. }
  1408. return hKey;
  1409. }
  1410. /*----------------------------------------------------------------*/
  1411. /* pkcs11_RSA_public_encrypt */
  1412. /* */
  1413. /* This function implements RSA public encryption. 'from_len'
  1414. bytes taken from 'from' and encrypted and put into 'to'. 'to' needs
  1415. to be at least RSA_size(rsa) bytes long. The number of bytes
  1416. written into 'to' is returned. -1 is returned on an error. The
  1417. operation performed is to = from^rsa->e mod rsa->n. */
  1418. /* for PKCS11, use C_EncryptInit + C_Encrypt */
  1419. /*----------------------------------------------------------------*/
  1420. static int pkcs11_RSA_public_encrypt(int flen,
  1421. const unsigned char *from,
  1422. unsigned char *to,
  1423. RSA *rsa,
  1424. int padding)
  1425. {
  1426. CK_ULONG bytesEncrypted=0;
  1427. CK_RV rv;
  1428. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1429. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1430. CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE;
  1431. struct token_session *wrapper = NULL;
  1432. CK_SESSION_HANDLE session;
  1433. DBG_fprintf("%s\n", __FUNCTION__);
  1434. //if (padding != RSA_PKCS1_PADDING)
  1435. //{
  1436. // PKCS11err(PKCS11_F_RSA_PUB_ENC, PKCS11_R_UNKNOWN_PADDING_TYPE);
  1437. // return -1;
  1438. //}
  1439. session = (CK_SESSION_HANDLE)RSA_get_ex_data(rsa, pkcs11Session);
  1440. if ( session == CK_INVALID_HANDLE || !session) {
  1441. wrapper = pkcs11_getSession();
  1442. if (!wrapper) {
  1443. return 0;
  1444. }
  1445. DBG_fprintf("%d: created new session\n", __LINE__);
  1446. session = wrapper->session;
  1447. RSA_set_ex_data(rsa, pkcs11Session, (void *)session);
  1448. }
  1449. hPublicKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPubKey);
  1450. if (hPublicKey == CK_INVALID_HANDLE) {
  1451. DBG_fprintf("%d: Invalid handle\n", __LINE__);
  1452. hPublicKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PUBLIC_KEY, true);
  1453. }
  1454. if (hPublicKey == CK_INVALID_HANDLE) {
  1455. DBG_fprintf("%d: Invalid handle\n", __LINE__);
  1456. } else {
  1457. rv = pFunctionList->C_EncryptInit(session, pMechanism, hPublicKey);
  1458. if (rv != CKR_OK)
  1459. {
  1460. pkcs11_die(PKCS11_F_RSA_PUB_ENC, PKCS11_R_ENCRYPTINIT, rv);
  1461. bytesEncrypted = -1;
  1462. goto out;
  1463. }
  1464. rv = pFunctionList->C_Encrypt(session, (unsigned char *)from,
  1465. flen, NULL_PTR, &bytesEncrypted);
  1466. if (rv != CKR_OK)
  1467. {
  1468. pkcs11_die(PKCS11_F_RSA_PUB_ENC, PKCS11_R_ENCRYPT, rv);
  1469. bytesEncrypted = -1;
  1470. goto out;
  1471. }
  1472. rv = pFunctionList->C_Encrypt(session, (unsigned char *)from,
  1473. flen, to, &bytesEncrypted);
  1474. if (rv != CKR_OK)
  1475. {
  1476. pkcs11_die(PKCS11_F_RSA_PUB_ENC, PKCS11_R_ENCRYPT, rv);
  1477. bytesEncrypted = -1;
  1478. goto out;
  1479. }
  1480. }
  1481. out:
  1482. OPENSSL_free(wrapper);
  1483. return bytesEncrypted;
  1484. }
  1485. /*----------------------------------------------------------------*/
  1486. /* pkcs11_RSA_private_encrypt */
  1487. /* This function implements RSA private encryption.
  1488. That corresponds to a signature and only the RSA_PKCS1_PADDING
  1489. is supported.
  1490. flen : bytes taken from 'from' and encrypted and put into 'to'.
  1491. to : needs to be at least bytes long.
  1492. ret : returns the number of bytes written into 'to' or -1 if an error.
  1493. for PKCS11 use C_SignInit + C_Sign */
  1494. /*----------------------------------------------------------------*/
  1495. static int pkcs11_RSA_private_encrypt(int flen,
  1496. const unsigned char *from,
  1497. unsigned char *to,
  1498. RSA *rsa,
  1499. int padding)
  1500. {
  1501. CK_ULONG ulSignatureLen=0;
  1502. CK_RV rv;
  1503. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1504. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1505. CK_OBJECT_HANDLE hPrivateKey= CK_INVALID_HANDLE;
  1506. struct token_session *wrapper = NULL;
  1507. CK_SESSION_HANDLE session;
  1508. DBG_fprintf("%s\n", __FUNCTION__);
  1509. //if (padding != RSA_PKCS1_PADDING)
  1510. //{
  1511. // PKCS11err(PKCS11_F_RSA_PRIV_ENC, PKCS11_R_UNKNOWN_PADDING_TYPE);
  1512. // return -1;
  1513. //}
  1514. session = (CK_SESSION_HANDLE)RSA_get_ex_data(rsa, pkcs11Session);
  1515. if (session == CK_INVALID_HANDLE || !session) {
  1516. wrapper = pkcs11_getSession();
  1517. if (!wrapper)
  1518. return 0;
  1519. DBG_fprintf("%d: created new session\n", __LINE__);
  1520. session = wrapper->session;
  1521. RSA_set_ex_data(rsa, pkcs11Session, (void *)session);
  1522. }
  1523. hPrivateKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPrivKey);
  1524. if (hPrivateKey == CK_INVALID_HANDLE)
  1525. hPrivateKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PRIVATE_KEY, true);
  1526. if (hPrivateKey != CK_INVALID_HANDLE)
  1527. {
  1528. rv = pFunctionList->C_SignInit(session, pMechanism, hPrivateKey);
  1529. if (rv != CKR_OK)
  1530. {
  1531. pkcs11_die(PKCS11_F_RSA_PRIV_ENC, PKCS11_R_SIGNINIT, rv);
  1532. ulSignatureLen = -1;
  1533. goto out;
  1534. }
  1535. rv = pFunctionList->C_Sign(session, (unsigned char *)from,
  1536. flen, NULL_PTR, &ulSignatureLen);
  1537. if (rv != CKR_OK)
  1538. {
  1539. pkcs11_die(PKCS11_F_RSA_PRIV_ENC, PKCS11_R_SIGN, rv);
  1540. ulSignatureLen = -1;
  1541. goto out;
  1542. }
  1543. rv = pFunctionList->C_Sign(session, (unsigned char *)from,
  1544. flen, to, &ulSignatureLen);
  1545. if (rv != CKR_OK)
  1546. {
  1547. pkcs11_die(PKCS11_F_RSA_PRIV_ENC, PKCS11_R_SIGN, rv);
  1548. ulSignatureLen = -1;
  1549. goto out;
  1550. }
  1551. }
  1552. out:
  1553. OPENSSL_free(wrapper);
  1554. return ulSignatureLen;
  1555. }
  1556. /*----------------------------------------------------------------*/
  1557. /* pkcs11_RSA_private_decrypt */
  1558. /* */
  1559. /*This function implements RSA private decryption.
  1560. flen : bytes are taken from 'from' and decrypted.
  1561. The decrypted data is put into 'to'.
  1562. ret : returns the number of bytes -1 if an error.
  1563. The operation performed is to = from^rsa->d mod rsa->n.*/
  1564. /* for PKCS11 use C_DecryptInit + C_Decrypt */
  1565. /*----------------------------------------------------------------*/
  1566. static int pkcs11_RSA_private_decrypt(int flen,
  1567. const unsigned char *from,
  1568. unsigned char *to,
  1569. RSA *rsa,
  1570. int padding)
  1571. {
  1572. CK_ULONG bytesDecrypted = flen;
  1573. CK_RV rv;
  1574. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1575. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1576. CK_OBJECT_HANDLE hPrivateKey;
  1577. struct token_session *wrapper = NULL;
  1578. CK_SESSION_HANDLE session;
  1579. DBG_fprintf("%s\n", __FUNCTION__);
  1580. if (padding != RSA_PKCS1_PADDING)
  1581. {
  1582. PKCS11err(PKCS11_F_RSA_PRIV_DEC, PKCS11_R_UNKNOWN_PADDING_TYPE);
  1583. return -1;
  1584. }
  1585. session = (CK_SESSION_HANDLE)RSA_get_ex_data(rsa, pkcs11Session);
  1586. if (session == CK_INVALID_HANDLE || !session) {
  1587. wrapper = pkcs11_getSession();
  1588. if (!wrapper) {
  1589. DBG_fprintf("%d: can't create new session\n", __LINE__);
  1590. return 0;
  1591. }
  1592. DBG_fprintf("%d: created new session\n", __LINE__);
  1593. session = wrapper->session;
  1594. RSA_set_ex_data(rsa, pkcs11Session, (void *)session);
  1595. }
  1596. hPrivateKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPrivKey);
  1597. if (hPrivateKey == CK_INVALID_HANDLE)
  1598. hPrivateKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PRIVATE_KEY, true);
  1599. if (hPrivateKey != CK_INVALID_HANDLE)
  1600. {
  1601. rv = pFunctionList->C_DecryptInit(session, pMechanism, hPrivateKey);
  1602. if (rv != CKR_OK)
  1603. {
  1604. pkcs11_die(PKCS11_F_RSA_PRIV_DEC, PKCS11_R_DECRYPTINIT, rv);
  1605. bytesDecrypted = -1;
  1606. goto out;
  1607. }
  1608. rv = pFunctionList->C_Decrypt(session, (unsigned char *)from,
  1609. flen, to, &bytesDecrypted);
  1610. if (rv != CKR_OK)
  1611. {
  1612. pkcs11_die(PKCS11_F_RSA_PRIV_DEC, PKCS11_R_DECRYPT, rv);
  1613. bytesDecrypted = -1;
  1614. goto out;
  1615. }
  1616. } else {
  1617. DBG_fprintf("%d: invalid key\n", __LINE__);
  1618. }
  1619. out:
  1620. OPENSSL_free(wrapper);
  1621. return bytesDecrypted;
  1622. }
  1623. /*----------------------------------------------------------------*/
  1624. /* pkcs11_RSA_public_decrypt */
  1625. /* */
  1626. /* This function implements RSA public decryption, the rsaKey
  1627. variable is the public key (but can be a private key).
  1628. This function should be processed as a pkcs11
  1629. verify-recover function
  1630. flen : bytes are taken from 'from' and decrypted.
  1631. to : The decrypted data.
  1632. ret : The number of bytes encrypted. -1 is returned to indicate an error.
  1633. The operation performed is to = from^rsa->e mod rsa->n.*/
  1634. /* for PKCS11 use C_VerifyRecoverInit + C_VerifyRecover */
  1635. /*'from' points to signature and 'flen' contains its length*/
  1636. /*----------------------------------------------------------------*/
  1637. static int pkcs11_RSA_public_decrypt(int flen,
  1638. const unsigned char *from,
  1639. unsigned char *to,
  1640. RSA *rsa,
  1641. int padding)
  1642. {
  1643. CK_ULONG bytesDecrypted = 0;
  1644. CK_RV rv;
  1645. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1646. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1647. CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE;
  1648. struct token_session *wrapper = NULL;
  1649. CK_SESSION_HANDLE session;
  1650. DBG_fprintf("%s\n", __FUNCTION__);
  1651. if (padding != RSA_PKCS1_PADDING)
  1652. {
  1653. PKCS11err(PKCS11_F_RSA_PUB_DEC, PKCS11_R_UNKNOWN_PADDING_TYPE);
  1654. return -1;
  1655. }
  1656. session = (CK_SESSION_HANDLE)RSA_get_ex_data(rsa, pkcs11Session);
  1657. if (session == CK_INVALID_HANDLE || !session) {
  1658. wrapper = pkcs11_getSession();
  1659. if (!wrapper)
  1660. return 0;
  1661. DBG_fprintf("%d: created new session\n", __LINE__);
  1662. session = wrapper->session;
  1663. RSA_set_ex_data(rsa, pkcs11Session, (void *)session);
  1664. }
  1665. hPublicKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPubKey);
  1666. if (hPublicKey == CK_INVALID_HANDLE)
  1667. hPublicKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PUBLIC_KEY, true);
  1668. if (hPublicKey != CK_INVALID_HANDLE)
  1669. {
  1670. rv = pFunctionList->C_VerifyRecoverInit(session, pMechanism, hPublicKey);
  1671. if (rv != CKR_OK)
  1672. {
  1673. pkcs11_die(PKCS11_F_RSA_PUB_DEC, PKCS11_R_VERIFYRECOVERINIT, rv);
  1674. bytesDecrypted = -1;
  1675. goto out;
  1676. }
  1677. rv = pFunctionList->C_VerifyRecover(session, (unsigned char *)from,
  1678. flen, NULL_PTR, &bytesDecrypted);
  1679. if (rv != CKR_OK)
  1680. {
  1681. pkcs11_die(PKCS11_F_RSA_PUB_DEC, PKCS11_R_VERIFYRECOVER, rv);
  1682. bytesDecrypted = -1;
  1683. goto out;
  1684. }
  1685. rv = pFunctionList->C_VerifyRecover(session, (unsigned char *)from,
  1686. flen, to, &bytesDecrypted);
  1687. if (rv != CKR_OK)
  1688. {
  1689. pkcs11_die(PKCS11_F_RSA_PUB_DEC, PKCS11_R_VERIFYRECOVER, rv);
  1690. bytesDecrypted = -1;
  1691. goto out;
  1692. }
  1693. }
  1694. out:
  1695. OPENSSL_free(wrapper);
  1696. return bytesDecrypted;
  1697. }
  1698. static int pkcs11_RSA_init(RSA *rsa)
  1699. {
  1700. struct token_session *wrapper;
  1701. DBG_fprintf("%s\n", __FUNCTION__);
  1702. wrapper = pkcs11_getSession();
  1703. if (wrapper)
  1704. RSA_set_ex_data(rsa, pkcs11Session, (void *)wrapper->session);
  1705. RSA_blinding_off(rsa);
  1706. return 1;
  1707. }
  1708. static int pkcs11_RSA_finish(RSA *rsa)
  1709. {
  1710. CK_RV rv;
  1711. CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE;
  1712. CK_OBJECT_HANDLE hPrivateKey = CK_INVALID_HANDLE;
  1713. long deletePubKey;
  1714. long deletePrivKey;
  1715. struct token_session *wrapper = NULL;
  1716. CK_SESSION_HANDLE session;
  1717. int err = 0;
  1718. DBG_fprintf("%s\n", __FUNCTION__);
  1719. /*
  1720. if (rsa->_method_mod_n != NULL)
  1721. BN_MONT_CTX_free(rsa->_method_mod_n);
  1722. if (rsa->_method_mod_p != NULL)
  1723. BN_MONT_CTX_free(rsa->_method_mod_p);
  1724. if (rsa->_method_mod_q != NULL)
  1725. BN_MONT_CTX_free(rsa->_method_mod_q);
  1726. */
  1727. deletePrivKey = (long)RSA_get_ex_data(rsa, deletePrivKeyOnFree);
  1728. hPrivateKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPrivKey);
  1729. session = (CK_SESSION_HANDLE)RSA_get_ex_data(rsa, pkcs11Session);
  1730. if (session == CK_INVALID_HANDLE || !session) {
  1731. wrapper = pkcs11_getSession();
  1732. if (!wrapper)
  1733. return 0;
  1734. DBG_fprintf("%d: created new session\n", __LINE__);
  1735. session = wrapper->session;
  1736. }
  1737. if ((deletePrivKey) && (hPrivateKey != CK_INVALID_HANDLE))
  1738. {
  1739. rv = pFunctionList->C_DestroyObject(session, hPrivateKey);
  1740. if (rv != CKR_OK)
  1741. {
  1742. pkcs11_die(PKCS11_F_RSA_FINISH, PKCS11_R_DESTROYOBJECT, rv);
  1743. goto out;
  1744. }
  1745. hPrivateKey = CK_INVALID_HANDLE;
  1746. RSA_set_ex_data(rsa, rsaPrivKey, (void *)hPrivateKey);
  1747. deletePrivKey = FALSE;
  1748. RSA_set_ex_data(rsa, deletePrivKeyOnFree, (void *)deletePrivKey);
  1749. }
  1750. deletePubKey = (long)RSA_get_ex_data(rsa, deletePubKeyOnFree);
  1751. hPublicKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPubKey);
  1752. if ((deletePubKey) && (hPublicKey != CK_INVALID_HANDLE))
  1753. {
  1754. rv = pFunctionList->C_DestroyObject(session, hPublicKey);
  1755. if (rv != CKR_OK)
  1756. {
  1757. pkcs11_die(PKCS11_F_RSA_FINISH, PKCS11_R_DESTROYOBJECT, rv);
  1758. goto out;
  1759. }
  1760. hPublicKey = CK_INVALID_HANDLE;
  1761. RSA_set_ex_data(rsa, rsaPubKey, (void *)hPublicKey);
  1762. deletePubKey = FALSE;
  1763. RSA_set_ex_data(rsa, deletePubKeyOnFree, (void *)deletePubKey);
  1764. }
  1765. rv = pFunctionList->C_CloseSession(session);
  1766. RSA_set_ex_data(rsa, pkcs11Session, (void *)CK_INVALID_HANDLE);
  1767. err = 1;
  1768. out:
  1769. OPENSSL_free(wrapper);
  1770. return err;
  1771. }
  1772. static int pkcs11_RSA_generate_key_with_mechanism(RSA* rsa,
  1773. CK_MECHANISM *pMechanism,
  1774. int bits,
  1775. BIGNUM *bn_e,
  1776. BN_GENCB *cb,
  1777. CK_BBOOL token)
  1778. {
  1779. DBG_fprintf("%s\n", __FUNCTION__);
  1780. DBG_fprintf("mechanism %lx chosen\n", *pMechanism);
  1781. CK_ULONG i;
  1782. CK_OBJECT_HANDLE hPublicKey;
  1783. CK_OBJECT_HANDLE hPrivateKey;
  1784. CK_OBJECT_CLASS oPublicKey = CKO_PUBLIC_KEY;
  1785. CK_OBJECT_CLASS oPrivateKey = CKO_PRIVATE_KEY;
  1786. CK_KEY_TYPE kType = CKK_RSA;
  1787. CK_ULONG ulPublicKeyAttributeCount = 8;
  1788. CK_ATTRIBUTE aPublicKeyTemplate[] =
  1789. {
  1790. {CKA_CLASS, &oPublicKey, sizeof(CK_OBJECT_CLASS)},
  1791. {CKA_TOKEN, (void *)NULL, 0},
  1792. {CKA_PRIVATE, &false, sizeof(CK_BBOOL)},
  1793. {CKA_MODIFIABLE, &false, sizeof(false)},
  1794. {CKA_KEY_TYPE, &kType, sizeof(CK_KEY_TYPE)},
  1795. {CKA_MODULUS_BITS, (void *)&bits, sizeof(bits)},
  1796. {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
  1797. {CKA_ID, PKCS11_KEY_ID, 16}
  1798. };
  1799. CK_ULONG ulPublicKeyAttributeResultCount = 2;
  1800. CK_ATTRIBUTE aPublicKeyResult[] =
  1801. {
  1802. {CKA_MODULUS, (void *)NULL, 0},
  1803. {CKA_MODULUS_BITS, (void *)NULL, 0},
  1804. {CKA_PUBLIC_EXPONENT, (void *)NULL, 0}
  1805. };
  1806. CK_ULONG ulPrivateKeyAttributeCount = 12;
  1807. CK_ATTRIBUTE aPrivateKeyTemplate[] =
  1808. {
  1809. {CKA_CLASS, &oPrivateKey, sizeof(CK_OBJECT_CLASS)},
  1810. {CKA_TOKEN, (void *)NULL, 0},
  1811. {CKA_PRIVATE, &false, sizeof(CK_BBOOL)},
  1812. {CKA_MODIFIABLE, &false, sizeof(CK_BBOOL)},
  1813. {CKA_KEY_TYPE, &kType, sizeof(CK_KEY_TYPE)},
  1814. {CKA_SENSITIVE, &true, sizeof(CK_BBOOL)},
  1815. {CKA_DECRYPT, &true, sizeof(CK_BBOOL)},
  1816. {CKA_SIGN, &true, sizeof(CK_BBOOL)},
  1817. {CKA_SIGN_RECOVER, &true, sizeof(CK_BBOOL)},
  1818. {CKA_UNWRAP, &true, sizeof(CK_BBOOL)},
  1819. {CKA_EXTRACTABLE, &true, sizeof(CK_BBOOL)},
  1820. {CKA_ID, PKCS11_KEY_ID, 16}
  1821. };
  1822. CK_RV rv;
  1823. CK_ATTRIBUTE *pModulus = NULL;
  1824. CK_ATTRIBUTE *pExponent = NULL;
  1825. int ret = 1;
  1826. struct token_session *wrapper = NULL;
  1827. CK_SESSION_HANDLE session;
  1828. BIGNUM *n;
  1829. aPublicKeyTemplate[6].ulValueLen = BN_num_bytes(bn_e);
  1830. aPublicKeyTemplate[6].pValue = OPENSSL_malloc(aPublicKeyTemplate[6].ulValueLen);
  1831. i = BN_bn2bin(bn_e, aPublicKeyTemplate[6].pValue);
  1832. aPublicKeyTemplate[1].ulValueLen = sizeof(token);
  1833. aPublicKeyTemplate[1].pValue = &token;
  1834. aPrivateKeyTemplate[1].ulValueLen = sizeof(token);
  1835. aPrivateKeyTemplate[1].pValue = &token;
  1836. session = (CK_SESSION_HANDLE)RSA_get_ex_data(rsa, pkcs11Session);
  1837. if (session == CK_INVALID_HANDLE || !session) {
  1838. wrapper = pkcs11_getSession();
  1839. if (!wrapper)
  1840. return 0;
  1841. DBG_fprintf("%d: created new session\n", __LINE__);
  1842. session = wrapper->session;
  1843. RSA_set_ex_data(rsa, pkcs11Session, (void *)session);
  1844. }
  1845. rv = pFunctionList->C_GenerateKeyPair(session,
  1846. pMechanism,
  1847. aPublicKeyTemplate,
  1848. ulPublicKeyAttributeCount,
  1849. aPrivateKeyTemplate,
  1850. ulPrivateKeyAttributeCount,
  1851. &hPublicKey,
  1852. &hPrivateKey);
  1853. if (rv != CKR_OK)
  1854. {
  1855. pkcs11_die(PKCS11_F_RSA_GEN_KEY, PKCS11_R_GEN_KEY, rv);
  1856. ret = 0;
  1857. goto err;
  1858. }
  1859. rv = pFunctionList->C_GetAttributeValue(session, hPublicKey, aPublicKeyResult, ulPublicKeyAttributeResultCount);
  1860. switch(rv)
  1861. {
  1862. case CKR_OK:
  1863. for(i = 0; i < ulPublicKeyAttributeResultCount; i++)
  1864. { /* Al locate required buffers */
  1865. if (((CK_LONG) aPublicKeyResult[i].ulValueLen) == -1)
  1866. { /* can't get this attribute */
  1867. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_NO_MODULUS_OR_NO_EXPONENT);
  1868. goto err;
  1869. }
  1870. else
  1871. {
  1872. aPublicKeyResult[i].pValue = OPENSSL_malloc(aPublicKeyResult[i].ulValueLen);
  1873. if (!aPublicKeyResult[i].pValue)
  1874. {
  1875. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_GEN_KEY);
  1876. goto err;
  1877. }
  1878. }
  1879. }
  1880. break;
  1881. case CKR_ATTRIBUTE_SENSITIVE:
  1882. case CKR_ATTRIBUTE_TYPE_INVALID:
  1883. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_ATTRIBUT_SENSITIVE_OR_INVALID);
  1884. goto err;
  1885. default:
  1886. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_GETATTRIBUTVALUE);
  1887. goto err;
  1888. }
  1889. /* Then get the values */
  1890. rv = pFunctionList->C_GetAttributeValue(session, hPublicKey, aPublicKeyResult,ulPublicKeyAttributeResultCount);
  1891. switch(rv)
  1892. {
  1893. case CKR_OK:
  1894. break;
  1895. case CKR_ATTRIBUTE_SENSITIVE:
  1896. case CKR_ATTRIBUTE_TYPE_INVALID:
  1897. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_ATTRIBUT_SENSITIVE_OR_INVALID);
  1898. goto err;
  1899. default:
  1900. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_GETATTRIBUTVALUE);
  1901. goto err;
  1902. }
  1903. /* recherche du Modulus */
  1904. for(i = 0; i < ulPublicKeyAttributeResultCount; i++)
  1905. {
  1906. if (aPublicKeyResult[i].type == CKA_MODULUS)
  1907. {
  1908. if (((CK_LONG) aPublicKeyResult[i].ulValueLen) != -1)
  1909. {
  1910. pModulus = &(aPublicKeyResult[i]);
  1911. }
  1912. break;
  1913. }
  1914. }
  1915. if (pModulus == NULL)
  1916. {
  1917. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_NO_MODULUS);
  1918. goto err;
  1919. }
  1920. n = BN_new();
  1921. BN_bin2bn(pModulus->pValue, pModulus->ulValueLen, n);
  1922. RSA_set0_key(rsa, n, NULL, NULL);
  1923. /* search Exponent */
  1924. for(i = 0; i < ulPublicKeyAttributeResultCount; i++)
  1925. {
  1926. if (aPublicKeyResult[i].type == CKA_PUBLIC_EXPONENT)
  1927. {
  1928. if (((CK_LONG) aPublicKeyResult[i].ulValueLen) != -1)
  1929. {
  1930. pExponent = &(aPublicKeyResult[i]);
  1931. }
  1932. break;
  1933. }
  1934. }
  1935. if (pExponent == NULL)
  1936. {
  1937. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_NO_EXPONENT);
  1938. goto err;
  1939. }
  1940. RSA_set0_key(rsa, NULL, bn_e, NULL);
  1941. bn_e = NULL;
  1942. RSA_set_ex_data(rsa, rsaPubKey, (char *)hPublicKey);
  1943. RSA_set_ex_data(rsa, rsaPrivKey, (char *)hPrivateKey);
  1944. err:
  1945. for(i = 0; i < ulPublicKeyAttributeResultCount; i++)
  1946. {
  1947. if (aPublicKeyResult[i].pValue)
  1948. {
  1949. OPENSSL_free(aPublicKeyResult[i].pValue);
  1950. aPublicKeyResult[i].pValue = NULL;
  1951. }
  1952. }
  1953. if (aPublicKeyTemplate[6].pValue != NULL)
  1954. {
  1955. OPENSSL_free(aPublicKeyTemplate[6].pValue);
  1956. aPublicKeyTemplate[6].pValue = NULL;
  1957. }
  1958. OPENSSL_free(wrapper);
  1959. return ret;
  1960. }
  1961. /* ************************************************************ */
  1962. /* */
  1963. /* function : pkcs11_RSA_generate_key */
  1964. /* */
  1965. /* ************************************************************ */
  1966. static int pkcs11_RSA_generate_key(RSA* rsa,
  1967. int bits,
  1968. BIGNUM *bn_e,
  1969. BN_GENCB *cb
  1970. )
  1971. {
  1972. DBG_fprintf("%s, bits=%d\n", __FUNCTION__, bits);
  1973. CK_MECHANISM Mechanism = {CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0};
  1974. CK_BBOOL token = TRUE;
  1975. return pkcs11_RSA_generate_key_with_mechanism(rsa, &Mechanism, bits, bn_e, cb, token);
  1976. }
  1977. /* The private is found from the public key stored in PEM format in "pubkey_file" */
  1978. static EVP_PKEY *pkcs11_load_privkey(ENGINE* e, const char* pubkey_file,
  1979. UI_METHOD *ui_method, void *callback_data)
  1980. {
  1981. EVP_PKEY *pkey=NULL;
  1982. FILE *pubkey;
  1983. CK_OBJECT_HANDLE hPrivateKey = CK_INVALID_HANDLE;
  1984. RSA *rsa;
  1985. DBG_fprintf("%s\n", __FUNCTION__);
  1986. if ((pubkey=fopen(pubkey_file,"r")) != NULL)
  1987. {
  1988. pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
  1989. fclose(pubkey);
  1990. if (pkey)
  1991. {
  1992. rsa = EVP_PKEY_get1_RSA(pkey);
  1993. if (rsa)
  1994. {
  1995. struct token_session *wrapper = NULL;
  1996. CK_SESSION_HANDLE session;
  1997. session = (CK_SESSION_HANDLE)RSA_get_ex_data(rsa, pkcs11Session);
  1998. if (session == CK_INVALID_HANDLE || !session) {
  1999. wrapper = pkcs11_getSession();
  2000. if (!wrapper)
  2001. return 0;
  2002. DBG_fprintf("%d: created new session\n", __LINE__);
  2003. session = wrapper->session;
  2004. RSA_set_ex_data(rsa, pkcs11Session, (void *)session);
  2005. }
  2006. hPrivateKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PRIVATE_KEY, true);
  2007. if (hPrivateKey == CK_INVALID_HANDLE)
  2008. {
  2009. EVP_PKEY_free(pkey);
  2010. pkey = NULL;
  2011. }
  2012. OPENSSL_free(wrapper);
  2013. }
  2014. else
  2015. {
  2016. EVP_PKEY_free(pkey);
  2017. pkey = NULL;
  2018. }
  2019. }
  2020. }
  2021. return(pkey);
  2022. }
  2023. static EVP_PKEY *pkcs11_load_pubkey(ENGINE* e, const char* pubkey_file,
  2024. UI_METHOD *ui_method, void *callback_data)
  2025. {
  2026. EVP_PKEY *pkey=NULL;
  2027. FILE *pubkey;
  2028. CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE;
  2029. RSA *rsa;
  2030. DBG_fprintf("%s\n", __FUNCTION__);
  2031. if ((pubkey=fopen(pubkey_file,"r")) != NULL)
  2032. {
  2033. pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
  2034. fclose(pubkey);
  2035. if (pkey)
  2036. {
  2037. rsa = EVP_PKEY_get1_RSA(pkey);
  2038. if (rsa)
  2039. {
  2040. struct token_session *wrapper = NULL;
  2041. CK_SESSION_HANDLE session;
  2042. session = (CK_SESSION_HANDLE)RSA_get_ex_data(rsa, pkcs11Session);
  2043. if (session == CK_INVALID_HANDLE || !session) {
  2044. wrapper = pkcs11_getSession();
  2045. if (!wrapper)
  2046. return 0;
  2047. DBG_fprintf("%d: created new session\n", __LINE__);
  2048. session = wrapper->session;
  2049. RSA_set_ex_data(rsa, pkcs11Session, (void *)session);
  2050. }
  2051. hPublicKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PUBLIC_KEY, true);
  2052. if (hPublicKey == CK_INVALID_HANDLE)
  2053. {
  2054. EVP_PKEY_free(pkey);
  2055. pkey = NULL;
  2056. }
  2057. OPENSSL_free(wrapper);
  2058. }
  2059. else
  2060. {
  2061. EVP_PKEY_free(pkey);
  2062. pkey = NULL;
  2063. }
  2064. }
  2065. }
  2066. return(pkey);
  2067. }
  2068. #endif
  2069. static void pkcs11_rand_cleanup(void)
  2070. {
  2071. return;
  2072. }
  2073. static int pkcs11_rand_add(const void *buf, int num, double entropy)
  2074. {
  2075. CK_RV rv;
  2076. struct token_session *wrapper;
  2077. int ret = 0;
  2078. DBG_fprintf("%s\n", __FUNCTION__);
  2079. /* return any token */
  2080. wrapper = pkcs11_getSession();
  2081. if (!wrapper)
  2082. return 0;
  2083. rv = pFunctionList->C_SeedRandom(wrapper->session, (CK_BYTE_PTR)&entropy, sizeof(entropy));
  2084. if (rv != CKR_OK)
  2085. {
  2086. pkcs11_die(PKCS11_F_RAND_ADD