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.

3082 lines
78 KiB

  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 <openssl/e_os2.h>
  23. #include <sys/types.h>
  24. #include <unistd.h>
  25. #include <openssl/engine.h>
  26. #include <openssl/dso.h>
  27. #include <openssl/err.h>
  28. #include <stdio.h>
  29. #include <openssl/bn.h>
  30. #include <openssl/pem.h>
  31. #include <openssl/rsa.h>
  32. #include <openssl/rand.h>
  33. #include <openssl/objects.h>
  34. #include <openssl/x509.h>
  35. #include <openssl/md5.h>
  36. #include <openssl/ripemd.h>
  37. #include <pthread.h>
  38. #ifndef OPENSSL_NO_HW
  39. #ifndef OPENSSL_NO_HW_PKCS11
  40. #include "cryptoki.h"
  41. #include "e_pkcs11_err.h"
  42. #include "e_pkcs11.h"
  43. /* SHA224, CAMELLIA */
  44. #include "pkcs-11v2-20a3.h"
  45. /* Constants used when creating the ENGINE */
  46. static const char *engine_pkcs11_id = "ibmpkcs11";
  47. static const char *engine_pkcs11_name = "PKCS#11 hardware engine support";
  48. static int bind_pkcs11(ENGINE *e);
  49. /* ENGINE level stuff */
  50. static int pkcs11_init(ENGINE *e);
  51. static int pkcs11_finish(ENGINE *e);
  52. static int pkcs11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
  53. static int pkcs11_destroy(ENGINE *e);
  54. #ifndef OPENSSL_NO_RSA
  55. /* RSA stuff */
  56. static int pkcs11_RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to,
  57. RSA *rsa, int padding);
  58. static int pkcs11_RSA_private_encrypt(int flen, const unsigned char *from, unsigned char *to,
  59. RSA *rsa, int padding);
  60. static int pkcs11_RSA_public_decrypt(int flen, const unsigned char *from, unsigned char *to,
  61. RSA *rsa, int padding);
  62. static int pkcs11_RSA_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
  63. RSA *rsa, int padding);
  64. static int pkcs11_RSA_init(RSA *rsa);
  65. static int pkcs11_RSA_finish(RSA *rsa);
  66. static int pkcs11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
  67. unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
  68. /* this API changed in OpenSSL version 1.0.0 */
  69. #if (OPENSSL_VERSION_NUMBER < 0x10000000L)
  70. static int pkcs11_RSA_verify(int dtype, const unsigned char *m, unsigned int m_len,
  71. unsigned char *sigbuf, unsigned int siglen, const RSA *rsa);
  72. #else
  73. static int pkcs11_RSA_verify(int dtype, const unsigned char *m, unsigned int m_len,
  74. const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa);
  75. #endif
  76. static int pkcs11_RSA_generate_key(RSA *rsa, int bits, BIGNUM *bn_e, BN_GENCB *cb);
  77. static EVP_PKEY *pkcs11_load_privkey(ENGINE*, const char* pubkey_file,
  78. UI_METHOD *ui_method, void *callback_data);
  79. static EVP_PKEY *pkcs11_load_pubkey(ENGINE*, const char* pubkey_file,
  80. UI_METHOD *ui_method, void *callback_data);
  81. CK_OBJECT_HANDLE pkcs11_FindOrCreateKey(CK_SESSION_HANDLE h, RSA* rsa, CK_OBJECT_CLASS oKey, CK_BBOOL fKeyCreate);
  82. /* exported functions (not member of ENGINE inteface) */
  83. RSA* pkcs11_RSA_generate_tmp_key(int bits,unsigned long e_value,void (*callback)(int,int,void *),void *cb_arg);
  84. #endif
  85. /* RAND stuff */
  86. static void pkcs11_rand_seed(const void *buf, int num);
  87. static void pkcs11_rand_add(const void *buf, int num, double add_entropy);
  88. static void pkcs11_rand_cleanup(void);
  89. static int pkcs11_rand_bytes(unsigned char *buf, int num);
  90. static int pkcs11_rand_status(void);
  91. /* cipher function prototypes */
  92. static inline int pkcs11_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key,
  93. const unsigned char *iv, int enc, int alg);
  94. static inline int pkcs11_cipher(EVP_CIPHER_CTX * ctx, unsigned char *out,
  95. const unsigned char *in, unsigned int inlen);
  96. static int pkcs11_cipher_cleanup(EVP_CIPHER_CTX *ctx);
  97. static int pkcs11_des_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key,
  98. const unsigned char *iv, int enc);
  99. static int pkcs11_tdes_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key,
  100. const unsigned char *iv, int enc);
  101. static int pkcs11_aes_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key,
  102. const unsigned char *iv, int enc);
  103. /* End cipher function prototypes */
  104. /* Digest function prototypes */
  105. static inline int pkcs11_digest_init(EVP_MD_CTX *ctx, int alg);
  106. static int pkcs11_digest_update(EVP_MD_CTX *ctx, const void *in, size_t len);
  107. static int pkcs11_digest_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in);
  108. static int pkcs11_digest_finish(EVP_MD_CTX *ctx, unsigned char *md);
  109. static inline int pkcs11_digest_cleanup(EVP_MD_CTX *ctx);
  110. static inline int pkcs11_sha1_init(EVP_MD_CTX *ctx);
  111. static inline int pkcs11_sha224_init(EVP_MD_CTX *ctx);
  112. static inline int pkcs11_sha256_init(EVP_MD_CTX *ctx);
  113. static inline int pkcs11_sha384_init(EVP_MD_CTX *ctx);
  114. static inline int pkcs11_sha512_init(EVP_MD_CTX *ctx);
  115. static inline int pkcs11_md5_init(EVP_MD_CTX *ctx);
  116. static inline int pkcs11_ripemd_init(EVP_MD_CTX *ctx);
  117. /* End digest function prototypes */
  118. static int pre_init_pkcs11(ENGINE *e);
  119. static int pkcs11_engine_ciphers(ENGINE * e, const EVP_CIPHER ** cipher,
  120. const int **nids, int nid);
  121. static int pkcs11_engine_digests(ENGINE * e, const EVP_MD ** digest,
  122. const int **nids, int nid);
  123. /* Number of NID's that exist in OpenSSL 1.0.0a */
  124. #define NUM_NID 893
  125. int pkcs11_implemented_ciphers[NUM_NID] = { 0, };
  126. int pkcs11_implemented_digests[NUM_NID] = { 0, };
  127. pid_t mypid = -1;
  128. /* The definitions for control commands specific to this engine */
  129. #define PKCS11_CMD_SO_PATH ENGINE_CMD_BASE
  130. static const ENGINE_CMD_DEFN pkcs11_cmd_defns[] =
  131. {
  132. { PKCS11_CMD_SO_PATH,
  133. "SO_PATH",
  134. "Specifies the path to the 'pkcs#11' shared library",
  135. ENGINE_CMD_FLAG_STRING
  136. },
  137. {0, NULL, NULL, 0}
  138. };
  139. #ifdef OPENSSL_NO_DYNAMIC_ENGINE
  140. static ENGINE *engine_pkcs11(void)
  141. {
  142. ENGINE *ret = ENGINE_new();
  143. if(!ret) {
  144. return NULL;
  145. }
  146. if(!bind_helper(ret)) {
  147. ENGINE_free(ret);
  148. return NULL;
  149. }
  150. return ret;
  151. }
  152. void ENGINE_load_pkcs11(void)
  153. {
  154. ENGINE *toadd = engine_pkcs11();
  155. if(!toadd) return;
  156. ENGINE_add(toadd);
  157. ENGINE_free(toadd);
  158. ERR_clear_error();
  159. }
  160. #else
  161. static int bind_helper(ENGINE *e, const char *id)
  162. {
  163. if((NULL != id) && (strcmp(id, engine_pkcs11_id) != 0))
  164. return 0;
  165. return(bind_pkcs11(e));
  166. }
  167. IMPLEMENT_DYNAMIC_CHECK_FN()
  168. IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
  169. #endif
  170. /*
  171. * Comments on approaches:
  172. * At the moment, ciphers and digests are treated differently.
  173. *
  174. * For ciphers, we use cipher_init to initialize the cryptoki
  175. * cipher action, and update to encrypt. There is no finalize
  176. * or cleanup.
  177. *
  178. * For digests, we use digest_init to initialize a context
  179. * struct, digest_update to append data to the data field within
  180. * that struct, finalize() to call C_Digest() on all the data
  181. * at once, and cleanup() to free the context struct.
  182. * The digest approach is part of the openbsd implementation. We
  183. * do not do anything about the potential EVP_MD_FLAG_ONESHOT
  184. * condition in update(), because openssl will still call finalize
  185. * after that.
  186. */
  187. /*
  188. * Each cipher/digest action requires a new session. We store the
  189. * session and its token in the context->cipher_data void* using
  190. * this struct
  191. */
  192. struct token_session {
  193. struct _token *token;
  194. CK_SESSION_HANDLE session;
  195. };
  196. /*
  197. * For digests:
  198. * We follow the example of openbsd_hw.c: digest_update just builds up
  199. * an array of what to process. final() runs the digest on that data.
  200. * TODO: In order to prevent memory problems when we have a huge input,
  201. * we may want to trigger a do_digest when len gets too big.
  202. */
  203. #define PKCS11_DIGEST_BLOCK_SIZE 4096
  204. struct pkcs11_digest_ctx {
  205. int alg;
  206. char *data;
  207. int len;
  208. int size; /* alloc'd size of data so far */
  209. int *ref_cnt; /* number of references to this digest operation */
  210. };
  211. /********/
  212. #define CIPHER_DATA(ctx) ((struct token_session *)(ctx->cipher_data))
  213. #define MD_DATA(ctx) ((struct token_session *)(ctx->md_data))
  214. static int num_cipher_nids = 0;
  215. static int num_digest_nids = 0;
  216. const EVP_CIPHER pkcs11_des_ecb = {
  217. NID_des_ecb, /* NID */
  218. 8, /* Block size */
  219. 8, /* Key len */
  220. 8, /* IV len */
  221. EVP_CIPH_ECB_MODE, /* flags */
  222. pkcs11_des_init_key, /* init */
  223. pkcs11_cipher, /* do_cipher */
  224. pkcs11_cipher_cleanup, /* cleanup */
  225. sizeof(struct token_session),
  226. EVP_CIPHER_set_asn1_iv,
  227. EVP_CIPHER_get_asn1_iv,
  228. NULL, /* misc ctrl ops */
  229. NULL /* app data (ctx->cipher_data) */
  230. };
  231. const EVP_CIPHER pkcs11_des_cbc = {
  232. NID_des_cbc, /* NID */
  233. 8, /* Block size */
  234. 8, /* Key len */
  235. 8, /* IV len */
  236. EVP_CIPH_CBC_MODE, /* flags */
  237. pkcs11_des_init_key, /* init */
  238. pkcs11_cipher, /* do_cipher */
  239. pkcs11_cipher_cleanup, /* cleanup */
  240. sizeof(struct token_session), /* sizeof(ctx->cipher_data) */
  241. EVP_CIPHER_set_asn1_iv,
  242. EVP_CIPHER_get_asn1_iv,
  243. NULL, /* misc ctrl ops */
  244. NULL /* app data (ctx->cipher_data) */
  245. };
  246. const EVP_CIPHER pkcs11_tdes_ecb = {
  247. NID_des_ede3_ecb, /* NID */
  248. 8, /* Block size */
  249. 24, /* Key len */
  250. 8, /* IV len */
  251. EVP_CIPH_ECB_MODE, /* flags */
  252. pkcs11_tdes_init_key, /* init */
  253. pkcs11_cipher, /* do_cipher */
  254. pkcs11_cipher_cleanup, /* cleanup */
  255. sizeof(struct token_session), /* sizeof(ctx->cipher_data) */
  256. EVP_CIPHER_set_asn1_iv,
  257. EVP_CIPHER_get_asn1_iv,
  258. NULL, /* misc ctrl ops */
  259. NULL /* app data (ctx->cipher_data) */
  260. };
  261. const EVP_CIPHER pkcs11_tdes_cbc = {
  262. NID_des_ede3_cbc, /* NID */
  263. 8, /* Block size */
  264. 24, /* Key len */
  265. 8, /* IV len */
  266. EVP_CIPH_CBC_MODE, /* flags */
  267. pkcs11_tdes_init_key, /* init */
  268. pkcs11_cipher, /* do_cipher */
  269. pkcs11_cipher_cleanup, /* cleanup */
  270. sizeof(struct token_session), /* sizeof(ctx->cipher_data) */
  271. EVP_CIPHER_set_asn1_iv,
  272. EVP_CIPHER_get_asn1_iv,
  273. NULL, /* misc ctrl ops */
  274. NULL /* app data (ctx->cipher_data) */
  275. };
  276. /* AES ECB */
  277. const EVP_CIPHER pkcs11_aes_128_ecb = {
  278. NID_aes_128_cbc, /* NID */
  279. 16, /* Block size */
  280. 16, /* Key len */
  281. 16, /* IV len */
  282. EVP_CIPH_ECB_MODE, /* flags */
  283. pkcs11_aes_init_key, /* init */
  284. pkcs11_cipher, /* do_cipher */
  285. pkcs11_cipher_cleanup, /* cleanup */
  286. sizeof(struct token_session), /* sizeof(ctx->cipher_data) */
  287. EVP_CIPHER_set_asn1_iv,
  288. EVP_CIPHER_get_asn1_iv,
  289. NULL, /* misc ctrl ops */
  290. NULL /* app data (ctx->cipher_data) */
  291. };
  292. const EVP_CIPHER pkcs11_aes_192_ecb = {
  293. NID_aes_192_ecb, /* NID */
  294. 24, /* Block size */
  295. 24, /* Key len */
  296. 24, /* IV len */
  297. EVP_CIPH_ECB_MODE, /* flags */
  298. pkcs11_aes_init_key, /* init */
  299. pkcs11_cipher, /* do_cipher */
  300. pkcs11_cipher_cleanup, /* cleanup */
  301. sizeof(struct token_session), /* sizeof(ctx->cipher_data) */
  302. EVP_CIPHER_set_asn1_iv,
  303. EVP_CIPHER_get_asn1_iv,
  304. NULL, /* misc ctrl ops */
  305. NULL /* app data (ctx->cipher_data) */
  306. };
  307. const EVP_CIPHER pkcs11_aes_256_ecb = {
  308. NID_aes_256_ecb, /* NID */
  309. 32, /* Block size */
  310. 32, /* Key len */
  311. 32, /* IV len */
  312. EVP_CIPH_ECB_MODE, /* flags */
  313. pkcs11_aes_init_key, /* init */
  314. pkcs11_cipher, /* do_cipher */
  315. pkcs11_cipher_cleanup, /* cleanup */
  316. sizeof(struct token_session), /* sizeof(ctx->cipher_data) */
  317. EVP_CIPHER_set_asn1_iv,
  318. EVP_CIPHER_get_asn1_iv,
  319. NULL, /* misc ctrl ops */
  320. NULL /* app data (ctx->cipher_data) */
  321. };
  322. /* AES CBC */
  323. const EVP_CIPHER pkcs11_aes_128_cbc = {
  324. NID_aes_128_cbc, /* NID */
  325. 16, /* Block size */
  326. 16, /* Key len */
  327. 16, /* IV len */
  328. EVP_CIPH_CBC_MODE, /* flags */
  329. pkcs11_aes_init_key, /* init */
  330. pkcs11_cipher, /* do_cipher */
  331. pkcs11_cipher_cleanup, /* cleanup */
  332. sizeof(struct token_session), /* sizeof(ctx->cipher_data) */
  333. EVP_CIPHER_set_asn1_iv,
  334. EVP_CIPHER_get_asn1_iv,
  335. NULL, /* misc ctrl ops */
  336. NULL /* app data (ctx->cipher_data) */
  337. };
  338. const EVP_CIPHER pkcs11_aes_192_cbc = {
  339. NID_aes_192_cbc, /* NID */
  340. 24, /* Block size */
  341. 24, /* Key len */
  342. 24, /* IV len */
  343. EVP_CIPH_CBC_MODE, /* flags */
  344. pkcs11_aes_init_key, /* init */
  345. pkcs11_cipher, /* do_cipher */
  346. pkcs11_cipher_cleanup, /* cleanup */
  347. sizeof(struct token_session), /* sizeof(ctx->cipher_data) */
  348. EVP_CIPHER_set_asn1_iv,
  349. EVP_CIPHER_get_asn1_iv,
  350. NULL, /* misc ctrl ops */
  351. NULL /* app data (ctx->cipher_data) */
  352. };
  353. const EVP_CIPHER pkcs11_aes_256_cbc = {
  354. NID_aes_256_cbc, /* NID */
  355. 32, /* Block size */
  356. 32, /* Key len */
  357. 32, /* IV len */
  358. EVP_CIPH_CBC_MODE, /* flags */
  359. pkcs11_aes_init_key, /* init */
  360. pkcs11_cipher, /* do_cipher */
  361. pkcs11_cipher_cleanup, /* cleanup */
  362. sizeof(struct token_session), /* sizeof(ctx->cipher_data) */
  363. EVP_CIPHER_set_asn1_iv,
  364. EVP_CIPHER_get_asn1_iv,
  365. NULL, /* misc ctrl ops */
  366. NULL /* app data (ctx->cipher_data) */
  367. };
  368. /* Message Digests */
  369. const EVP_MD pkcs11_sha1 = {
  370. NID_sha1,
  371. NID_sha1WithRSAEncryption,
  372. SHA_DIGEST_LENGTH,
  373. 0,
  374. pkcs11_sha1_init,
  375. pkcs11_digest_update,
  376. pkcs11_digest_finish, /* final */
  377. pkcs11_digest_copy,
  378. pkcs11_digest_cleanup, /* cleanup */
  379. EVP_PKEY_RSA_method,
  380. SHA_CBLOCK,
  381. sizeof(struct pkcs11_digest_ctx)
  382. };
  383. const EVP_MD pkcs11_sha224 = {
  384. NID_sha224,
  385. NID_sha224WithRSAEncryption,
  386. SHA224_DIGEST_LENGTH,
  387. 0,
  388. pkcs11_sha224_init,
  389. pkcs11_digest_update,
  390. pkcs11_digest_finish, /* final */
  391. pkcs11_digest_copy,
  392. pkcs11_digest_cleanup, /* cleanup */
  393. EVP_PKEY_RSA_method,
  394. SHA256_CBLOCK,
  395. sizeof(struct pkcs11_digest_ctx)
  396. };
  397. const EVP_MD pkcs11_sha256 = {
  398. NID_sha256,
  399. NID_sha256WithRSAEncryption,
  400. SHA256_DIGEST_LENGTH,
  401. 0,
  402. pkcs11_sha256_init,
  403. pkcs11_digest_update,
  404. pkcs11_digest_finish, /* final */
  405. pkcs11_digest_copy,
  406. pkcs11_digest_cleanup, /* cleanup */
  407. EVP_PKEY_RSA_method,
  408. SHA256_CBLOCK,
  409. sizeof(struct pkcs11_digest_ctx)
  410. };
  411. const EVP_MD pkcs11_sha384 = {
  412. NID_sha384,
  413. NID_sha384WithRSAEncryption,
  414. SHA384_DIGEST_LENGTH,
  415. 0,
  416. pkcs11_sha384_init,
  417. pkcs11_digest_update,
  418. pkcs11_digest_finish, /* final */
  419. pkcs11_digest_copy,
  420. pkcs11_digest_cleanup, /* cleanup */
  421. EVP_PKEY_RSA_method,
  422. SHA512_CBLOCK,
  423. sizeof(struct pkcs11_digest_ctx)
  424. };
  425. const EVP_MD pkcs11_sha512 = {
  426. NID_sha512,
  427. NID_sha512WithRSAEncryption,
  428. SHA512_DIGEST_LENGTH,
  429. 0,
  430. pkcs11_sha512_init,
  431. pkcs11_digest_update,
  432. pkcs11_digest_finish, /* final */
  433. pkcs11_digest_copy,
  434. pkcs11_digest_cleanup, /* cleanup */
  435. EVP_PKEY_RSA_method,
  436. SHA512_CBLOCK,
  437. sizeof(struct pkcs11_digest_ctx)
  438. };
  439. const EVP_MD pkcs11_md5 = {
  440. NID_md5,
  441. NID_md5WithRSAEncryption,
  442. MD5_DIGEST_LENGTH,
  443. 0,
  444. pkcs11_md5_init,
  445. pkcs11_digest_update,
  446. pkcs11_digest_finish, /* final */
  447. pkcs11_digest_copy,
  448. pkcs11_digest_cleanup, /* cleanup */
  449. EVP_PKEY_RSA_method,
  450. MD5_CBLOCK,
  451. sizeof(struct pkcs11_digest_ctx)
  452. };
  453. const EVP_MD pkcs11_ripemd = {
  454. NID_ripemd160,
  455. NID_ripemd160WithRSA,
  456. RIPEMD160_DIGEST_LENGTH,
  457. 0, /* flags */
  458. pkcs11_ripemd_init,
  459. pkcs11_digest_update,
  460. pkcs11_digest_finish, /* final */
  461. pkcs11_digest_copy,
  462. pkcs11_digest_cleanup, /* cleanup */
  463. EVP_PKEY_RSA_method,
  464. RIPEMD160_CBLOCK,
  465. sizeof(struct pkcs11_digest_ctx)
  466. };
  467. /********/
  468. #ifndef OPENSSL_NO_RSA
  469. static RSA_METHOD pkcs11_rsa =
  470. {
  471. "PKCS#11 RSA",
  472. pkcs11_RSA_public_encrypt, /* rsa_pub_encrypt */
  473. pkcs11_RSA_public_decrypt, /* rsa_pub_decrypt */
  474. pkcs11_RSA_private_encrypt, /* rsa_priv_encrypt */
  475. pkcs11_RSA_private_decrypt, /* rsa_priv_decrypt */
  476. NULL, /* rsa_mod_exp */
  477. NULL, /* bn_mod_exp */
  478. pkcs11_RSA_init, /* init */
  479. pkcs11_RSA_finish, /* finish */
  480. RSA_FLAG_SIGN_VER, /* flags */
  481. NULL, /* app_data */
  482. pkcs11_RSA_sign, /* rsa_sign */
  483. pkcs11_RSA_verify, /* rsa_verify */
  484. pkcs11_RSA_generate_key /* rsa_generate_key */
  485. };
  486. RSA_METHOD *PKCS11_RSA(void)
  487. {
  488. return(&pkcs11_rsa);
  489. }
  490. #endif
  491. extern const char *RAND_version;
  492. static RAND_METHOD pkcs11_random =
  493. {
  494. /* "PKCS11 RAND method", */
  495. pkcs11_rand_seed,
  496. pkcs11_rand_bytes,
  497. pkcs11_rand_cleanup,
  498. pkcs11_rand_add,
  499. pkcs11_rand_bytes,
  500. pkcs11_rand_status
  501. };
  502. RAND_METHOD *PKCS11_RAND(void)
  503. {
  504. return(&pkcs11_random);
  505. }
  506. static CK_FUNCTION_LIST_PTR pFunctionList = NULL;
  507. /* These are the static string constants for the DSO file name and the function
  508. * symbol names to bind to.
  509. */
  510. static unsigned char PKCS11_KEY_ID[] = "OpenSSL PKCS#11";
  511. /* String used to detect a CC2000 Bull TrustWay crypto card */
  512. #define BULL_TRUSTWAY_LIBRARY_DESCRIPTION "Bull CC2000 PKCS#11 Library "
  513. static CK_BBOOL Bull_TrustWay = FALSE;
  514. #undef BULL_CC2000 /* use Bull CC2000 hardware crypto */
  515. #undef BULL_CRYPTOBOX /* use Bull CryptoBox remote hardware crypto */
  516. #undef GPKCS11 /* use GPKCS11 software crypto */
  517. #if defined(BULL_CC2000)
  518. static const char def_PKCS11_LIBNAME[] = "gpkcs11cc2000";
  519. #elif defined(BULL_CRYPTOBOX)
  520. static const char def_PKCS11_LIBNAME[] = "cryptobox_clnt";
  521. extern CK_RV C_InitializeRpc (CK_CHAR_PTR, CK_CHAR_PTR, CK_ULONG_PTR);
  522. #elif defined(GPKCS11)
  523. static const char def_PKCS11_LIBNAME[] = "gpkcs11";
  524. #elif defined(OPENCRYPTOKI)
  525. static char *def_PKCS11_LIBNAME = "opencryptoki";
  526. #else
  527. static const char def_PKCS11_LIBNAME[] = "pkcs11";
  528. #endif
  529. static const char PKCS11_GET_FUNCTION_LIST[] = "C_GetFunctionList";
  530. /* Size of an SSL signature: MD5+SHA1. up to allow SHA512 */
  531. //#define SSL_SIG_LENGTH 64
  532. #define SSL_SIG_LENGTH 36
  533. #define KEY_STORE 1
  534. static CK_BBOOL true = TRUE;
  535. static CK_BBOOL false = FALSE;
  536. static CK_SLOT_ID SLOTID = 0XFFFFFFFF;
  537. #ifndef OPENSSL_NO_RSA
  538. /* Where in the CRYPTO_EX_DATA stack we stick our per-key contexts */
  539. static int rsaPubKey = -1;
  540. static int rsaPrivKey = -1;
  541. static int deletePubKeyOnFree = -1;
  542. static int deletePrivKeyOnFree = -1;
  543. #endif
  544. static int PKCS11_Initialized = 0;
  545. #ifdef PKCS11_DEBUG
  546. #define DBG_fprintf(args...) do { fprintf(stderr, args); fflush(stderr); } while (0)
  547. #else
  548. #define DBG_fprintf(args...)
  549. #endif
  550. void pkcs11_atfork_init(void)
  551. {
  552. DBG_fprintf("pkcs11_atfork_init: called (pid %d)\n", getpid());
  553. PKCS11_Initialized = 0;
  554. }
  555. #define pkcs11_die(func, reason, rv) \
  556. { \
  557. char tmpbuf[20]; \
  558. PKCS11err(func, reason); \
  559. sprintf(tmpbuf, "%lx", rv); \
  560. ERR_add_error_data(2, "PKCS11 CK_RV=0X", tmpbuf); \
  561. }
  562. struct token_session *pkcs11_getSession(void)
  563. {
  564. CK_RV rv;
  565. struct token_session *wrapper = OPENSSL_malloc(sizeof (struct token_session));
  566. if (!wrapper) {
  567. PKCS11err(PKCS11_F_GETSESSION, PKCS11_R_MALLOC_FAILURE);
  568. return NULL;
  569. }
  570. wrapper->token = pkcs11_token_list;
  571. if (!PKCS11_Initialized) {
  572. rv = pFunctionList->C_Initialize(NULL);
  573. if (rv != CKR_OK && rv != CKR_CRYPTOKI_ALREADY_INITIALIZED) {
  574. pkcs11_die(PKCS11_F_GETSESSION, PKCS11_R_INITIALIZE, rv);
  575. return NULL;
  576. }
  577. PKCS11_Initialized = 1;
  578. }
  579. rv = pFunctionList->C_OpenSession(wrapper->token->slot,
  580. CKF_SERIAL_SESSION | CKF_RW_SESSION,
  581. NULL_PTR,
  582. NULL_PTR,
  583. &wrapper->session);
  584. if (rv != CKR_OK) {
  585. pkcs11_die(PKCS11_F_GETSESSION, PKCS11_R_OPENSESSION, rv);
  586. return NULL;
  587. }
  588. return wrapper;
  589. }
  590. char *alg_to_string(int alg_type)
  591. {
  592. switch (alg_type) {
  593. case alg_des:
  594. return "des";
  595. case alg_tdes:
  596. return "tdes";
  597. case alg_aes:
  598. return "aes";
  599. case alg_rsa:
  600. return "rsa";
  601. case alg_sha:
  602. return "sha";
  603. case alg_md5:
  604. return "md5";
  605. case alg_ripemd:
  606. return "ripemd";
  607. default:
  608. return "invalid algorithm";
  609. }
  610. }
  611. /* This internal function is used by ENGINE_pkcs11() and possibly by the
  612. * "dynamic" ENGINE support too */
  613. static int bind_pkcs11(ENGINE *e)
  614. {
  615. DBG_fprintf("%s\n", __FUNCTION__);
  616. if (!ENGINE_set_id(e, engine_pkcs11_id) ||
  617. !ENGINE_set_name(e, engine_pkcs11_name) ||
  618. #if 0
  619. /* RSA functions are set below, in pre_init_pkcs11(), but only
  620. * when some token's mechanism list reports supporting RSA */
  621. #ifndef OPENSSL_NO_RSA
  622. !ENGINE_set_RSA(e, &pkcs11_rsa) ||
  623. !ENGINE_set_load_privkey_function(e, pkcs11_load_privkey) ||
  624. !ENGINE_set_load_pubkey_function(e, pkcs11_load_pubkey) ||
  625. #endif
  626. #endif
  627. !ENGINE_set_RAND(e, &pkcs11_random) ||
  628. !ENGINE_set_init_function(e, pkcs11_init) ||
  629. !ENGINE_set_ciphers(e, pkcs11_engine_ciphers) ||
  630. !ENGINE_set_digests(e, pkcs11_engine_digests) ||
  631. !ENGINE_set_destroy_function(e, pkcs11_destroy) ||
  632. !ENGINE_set_finish_function(e, pkcs11_finish) ||
  633. !ENGINE_set_ctrl_function(e, pkcs11_ctrl) ||
  634. !ENGINE_set_cmd_defns(e, pkcs11_cmd_defns))
  635. return 0;
  636. /* Ensure the pkcs11 error handling is set up */
  637. ERR_load_pkcs11_strings();
  638. pre_init_pkcs11(e);
  639. return 1;
  640. }
  641. #ifdef ENGINE_DYNAMIC_SUPPORT
  642. static int bind_helper(ENGINE *e, const char *id)
  643. {
  644. DBG_fprintf("%s\n", __FUNCTION__);
  645. if(id && (strcmp(id, engine_pkcs11_id) != 0))
  646. return 0;
  647. if(!bind_pkcs11(e))
  648. return 0;
  649. return 1;
  650. }
  651. IMPLEMENT_DYNAMIC_CHECK_FN()
  652. IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
  653. #else
  654. static ENGINE *engine_pkcs11(void)
  655. {
  656. DBG_fprintf("%s\n", __FUNCTION__);
  657. ENGINE *ret = ENGINE_new();
  658. if(!ret)
  659. return NULL;
  660. if(!bind_pkcs11(ret))
  661. {
  662. ENGINE_free(ret);
  663. return NULL;
  664. }
  665. pre_init_pkcs11(ret);
  666. return ret;
  667. }
  668. void ENGINE_load_pkcs11(void)
  669. {
  670. DBG_fprintf("%s\n", __FUNCTION__);
  671. ENGINE *e_pkcs11 = engine_pkcs11();
  672. if(!e_pkcs11) return;
  673. ENGINE_add(e_pkcs11);
  674. ENGINE_free(e_pkcs11);
  675. ERR_clear_error();
  676. }
  677. #endif
  678. #define PKCS11_MAX_ALGS 20
  679. static int
  680. get_pkcs11_ciphers(const int **retnids)
  681. {
  682. static int nids[PKCS11_MAX_ALGS];
  683. int i, count = 0;
  684. memset(nids, 0, sizeof(nids));
  685. *retnids = NULL;
  686. for (i=0; i<NUM_NID; i++) {
  687. if (pkcs11_implemented_ciphers[i])
  688. nids[count++] = i;
  689. }
  690. if (count)
  691. *retnids = nids;
  692. return count;
  693. }
  694. static int
  695. get_pkcs11_digests(const int **retnids)
  696. {
  697. static int nids[PKCS11_MAX_ALGS];
  698. int i, count = 0;
  699. memset(nids, 0, sizeof(nids));
  700. *retnids = NULL;
  701. for (i=0; i<NUM_NID; i++) {
  702. if (pkcs11_implemented_digests[i])
  703. nids[count++] = i;
  704. }
  705. if (count)
  706. *retnids = nids;
  707. return count;
  708. }
  709. /*
  710. * ENGINE calls this to find out how to deal with
  711. * a particular NID in the ENGINE.
  712. */
  713. static int pkcs11_engine_ciphers(ENGINE * e, const EVP_CIPHER ** cipher,
  714. const int **nids, int nid)
  715. {
  716. if (!cipher)
  717. return get_pkcs11_ciphers(nids);
  718. /* If the algorithm requested was not added to the list at
  719. * engine init time, don't return a reference to that structure.
  720. */
  721. if (pkcs11_implemented_ciphers[nid]) {
  722. switch (nid) {
  723. case NID_aes_128_ecb:
  724. *cipher = &pkcs11_aes_128_ecb;
  725. break;
  726. case NID_aes_192_ecb:
  727. *cipher = &pkcs11_aes_192_ecb;
  728. break;
  729. case NID_aes_256_ecb:
  730. *cipher = &pkcs11_aes_256_ecb;
  731. break;
  732. case NID_aes_128_cbc:
  733. *cipher = &pkcs11_aes_128_cbc;
  734. break;
  735. case NID_aes_192_cbc:
  736. *cipher = &pkcs11_aes_192_cbc;
  737. break;
  738. case NID_aes_256_cbc:
  739. *cipher = &pkcs11_aes_256_cbc;
  740. break;
  741. case NID_des_ecb:
  742. *cipher = &pkcs11_des_ecb;
  743. break;
  744. case NID_des_cbc:
  745. *cipher = &pkcs11_des_cbc;
  746. break;
  747. case NID_des_ede3_ecb:
  748. *cipher = &pkcs11_tdes_ecb;
  749. break;
  750. case NID_des_ede3_cbc:
  751. *cipher = &pkcs11_tdes_cbc;
  752. break;
  753. default:
  754. *cipher = NULL;
  755. break;
  756. }
  757. }
  758. return (*cipher != NULL);
  759. }
  760. static int pkcs11_engine_digests(ENGINE * e, const EVP_MD ** digest,
  761. const int **nids, int nid)
  762. {
  763. if (!digest)
  764. return get_pkcs11_digests(nids);
  765. if (pkcs11_implemented_digests[nid]) {
  766. switch (nid) {
  767. case NID_ripemd160:
  768. *digest = &pkcs11_ripemd;
  769. break;
  770. case NID_md5:
  771. *digest = &pkcs11_md5;
  772. break;
  773. case NID_sha1:
  774. *digest = &pkcs11_sha1;
  775. break;
  776. default:
  777. *digest = NULL;
  778. break;
  779. }
  780. }
  781. return (*digest != NULL);
  782. }
  783. /* This is a process-global DSO handle used for loading and unloading
  784. * the PKCS#11 library. NB: This is only set (or unset) during an
  785. * init() or finish() call (reference counts permitting) and they're
  786. * operating with global locks, so this should be thread-safe
  787. * implicitly. */
  788. static DSO *pkcs11_dso = NULL;
  789. /* These are the static string constants for the DSO file name and the function
  790. * symbol names to bind to.
  791. */
  792. static const char *PKCS11_LIBNAME = NULL;
  793. static const char *get_PKCS11_LIBNAME(void)
  794. {
  795. if(PKCS11_LIBNAME)
  796. return PKCS11_LIBNAME;
  797. return def_PKCS11_LIBNAME;
  798. }
  799. static void free_PKCS11_LIBNAME(void)
  800. {
  801. if(PKCS11_LIBNAME)
  802. OPENSSL_free((void*)PKCS11_LIBNAME);
  803. PKCS11_LIBNAME = NULL;
  804. }
  805. static long set_PKCS11_LIBNAME(const char *name)
  806. {
  807. free_PKCS11_LIBNAME();
  808. return ((PKCS11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
  809. }
  810. int add_hw_token(struct _token *new_tok, CK_MECHANISM_TYPE mech, struct _token **list_head,
  811. short *enabled, struct _token **next_ptr)
  812. {
  813. CK_RV rv;
  814. CK_MECHANISM_INFO mech_info;
  815. rv = pFunctionList->C_GetMechanismInfo(new_tok->slot, mech, &mech_info);
  816. if (rv != CKR_OK) {
  817. pkcs11_die(PKCS11_F_ADDTOKEN, PKCS11_R_GETMECHANISMINFO, rv);
  818. }
  819. /* return 0 if not HW enabled */
  820. if ((mech_info.flags & CKF_HW) == 0)
  821. return 0;
  822. if (!*enabled) {
  823. *enabled = 1;
  824. *next_ptr = *list_head;
  825. *list_head = new_tok;
  826. }
  827. /* return 1 if HW enabled */
  828. return 1;
  829. }
  830. /* Add new NID's based on this slot's token */
  831. void pkcs11_regToken(ENGINE *e, CK_SLOT_ID slot_id)
  832. {
  833. CK_RV rv;
  834. CK_ULONG mech_cnt;
  835. CK_MECHANISM_TYPE_PTR mech_list;
  836. int i;
  837. DBG_fprintf("%s\n", __FUNCTION__);
  838. rv = pFunctionList->C_GetMechanismList(slot_id, NULL_PTR, &mech_cnt);
  839. if (rv != CKR_OK) {
  840. pkcs11_die(PKCS11_F_ADDTOKEN, PKCS11_R_GETMECHANISMLIST, rv);
  841. goto err;
  842. }
  843. /* Bounds check mech_cnt ? */
  844. mech_list = (CK_MECHANISM_TYPE_PTR) OPENSSL_malloc(mech_cnt * sizeof(CK_MECHANISM_TYPE));
  845. if (mech_list == NULL) {
  846. pkcs11_die(PKCS11_F_ADDTOKEN, PKCS11_R_MALLOC_FAILURE, rv);
  847. goto err;
  848. }
  849. rv = pFunctionList->C_GetMechanismList(slot_id, mech_list, &mech_cnt);
  850. if (rv != CKR_OK) {
  851. pkcs11_die(PKCS11_F_ADDTOKEN, PKCS11_R_GETMECHANISMLIST, rv);
  852. goto err_free;
  853. }
  854. /* Check which mechanisms are performed in hardware */
  855. for( i = 0; i < mech_cnt; i++ ) {
  856. switch (mech_list[i]) {
  857. case CKM_RSA_PKCS_KEY_PAIR_GEN:
  858. case CKM_RSA_PKCS:
  859. case CKM_RSA_9796:
  860. case CKM_RSA_X_509:
  861. case CKM_RSA_PKCS_OAEP:
  862. case CKM_RSA_X9_31:
  863. case CKM_RSA_X9_31_KEY_PAIR_GEN:
  864. case CKM_MD5_RSA_PKCS:
  865. #ifndef OPENSSL_NO_RSA
  866. DBG_fprintf("%s: registering RSA\n", __FUNCTION__);
  867. ENGINE_set_RSA(e, &pkcs11_rsa);
  868. ENGINE_set_load_privkey_function(e, pkcs11_load_privkey);
  869. ENGINE_set_load_pubkey_function(e, pkcs11_load_pubkey);
  870. #endif
  871. break;
  872. case CKM_DH_PKCS_KEY_PAIR_GEN:
  873. case CKM_DH_PKCS_DERIVE:
  874. case CKM_X9_42_DH_KEY_PAIR_GEN:
  875. case CKM_X9_42_DH_DERIVE:
  876. case CKM_X9_42_DH_HYBRID_DERIVE:
  877. case CKM_DH_PKCS_PARAMETER_GEN:
  878. case CKM_X9_42_DH_PARAMETER_GEN:
  879. break;
  880. case CKM_DES_ECB:
  881. pkcs11_implemented_ciphers[NID_des_ecb] = 1;
  882. num_cipher_nids++;
  883. break;
  884. case CKM_DES_CBC:
  885. case CKM_DES_CBC_PAD:
  886. pkcs11_implemented_ciphers[NID_des_cbc] = 1;
  887. num_cipher_nids++;
  888. break;
  889. case CKM_DES_KEY_GEN:
  890. case CKM_DES_MAC:
  891. case CKM_DES_MAC_GENERAL:
  892. break;
  893. case CKM_DES3_ECB:
  894. pkcs11_implemented_ciphers[NID_des_ede3_ecb] = 1;
  895. num_cipher_nids++;
  896. break;
  897. case CKM_DES3_CBC:
  898. case CKM_DES3_CBC_PAD:
  899. pkcs11_implemented_ciphers[NID_des_ede3_cbc] = 1;
  900. num_cipher_nids++;
  901. break;
  902. case CKM_DES3_KEY_GEN:
  903. case CKM_DES3_MAC:
  904. case CKM_DES3_MAC_GENERAL:
  905. break;
  906. case CKM_SHA_1:
  907. pkcs11_implemented_digests[NID_sha1] = 1;
  908. num_digest_nids++;
  909. break;
  910. case CKM_SHA_1_HMAC:
  911. case CKM_SHA_1_HMAC_GENERAL:
  912. pkcs11_implemented_digests[NID_hmacWithSHA1] = 1;
  913. num_digest_nids++;
  914. break;
  915. case CKM_PBA_SHA1_WITH_SHA1_HMAC:
  916. case CKM_SHA1_KEY_DERIVATION:
  917. case CKM_SHA1_RSA_PKCS:
  918. pkcs11_implemented_digests[NID_sha1WithRSAEncryption] = 1;
  919. num_digest_nids++;
  920. break;
  921. case CKM_SHA224:
  922. pkcs11_implemented_digests[NID_sha224] = 1;
  923. num_digest_nids++;
  924. break;
  925. case CKM_SHA224_KEY_DERIVATION:
  926. case CKM_SHA224_RSA_PKCS:
  927. pkcs11_implemented_digests[NID_sha224WithRSAEncryption] = 1;
  928. num_digest_nids++;
  929. break;
  930. case CKM_SHA256:
  931. pkcs11_implemented_digests[NID_sha256] = 1;
  932. num_digest_nids++;
  933. break;
  934. case CKM_SHA256_KEY_DERIVATION:
  935. case CKM_SHA256_RSA_PKCS:
  936. pkcs11_implemented_digests[NID_sha256WithRSAEncryption] = 1;
  937. num_digest_nids++;
  938. break;
  939. case CKM_SHA384:
  940. pkcs11_implemented_digests[NID_sha384] = 1;
  941. num_digest_nids++;
  942. break;
  943. case CKM_SHA384_KEY_DERIVATION:
  944. case CKM_SHA384_RSA_PKCS:
  945. pkcs11_implemented_digests[NID_sha384WithRSAEncryption] = 1;
  946. num_digest_nids++;
  947. break;
  948. case CKM_SHA512:
  949. pkcs11_implemented_digests[NID_sha512] = 1;
  950. num_digest_nids++;
  951. break;
  952. case CKM_SHA512_KEY_DERIVATION:
  953. case CKM_SHA512_RSA_PKCS:
  954. pkcs11_implemented_digests[NID_sha512WithRSAEncryption] = 1;
  955. num_digest_nids++;
  956. break;
  957. case CKM_AES_ECB:
  958. pkcs11_implemented_ciphers[NID_aes_128_ecb] = 1;
  959. pkcs11_implemented_ciphers[NID_aes_192_ecb] = 1;
  960. pkcs11_implemented_ciphers[NID_aes_256_ecb] = 1;
  961. num_cipher_nids += 3;
  962. break;
  963. case CKM_AES_KEY_GEN:
  964. break;
  965. case CKM_AES_CBC_PAD:
  966. case CKM_AES_CBC:
  967. pkcs11_implemented_ciphers[NID_aes_128_cbc] = 1;
  968. pkcs11_implemented_ciphers[NID_aes_192_cbc] = 1;
  969. pkcs11_implemented_ciphers[NID_aes_256_cbc] = 1;
  970. num_cipher_nids += 3;
  971. break;
  972. case CKM_AES_MAC:
  973. case CKM_AES_MAC_GENERAL:
  974. break;
  975. case CKM_MD5:
  976. pkcs11_implemented_digests[NID_md5] = 1;
  977. num_digest_nids++;
  978. break;
  979. case CKM_MD5_HMAC:
  980. case CKM_MD5_HMAC_GENERAL:
  981. case CKM_SSL3_PRE_MASTER_KEY_GEN:
  982. case CKM_SSL3_MASTER_KEY_DERIVE:
  983. case CKM_SSL3_KEY_AND_MAC_DERIVE:
  984. case CKM_SSL3_MD5_MAC:
  985. case CKM_SSL3_SHA1_MAC:
  986. break;
  987. case CKM_RIPEMD160:
  988. pkcs11_implemented_digests[NID_ripemd160] = 1;
  989. num_digest_nids++;
  990. break;
  991. case CKM_RIPEMD160_HMAC:
  992. case CKM_RIPEMD160_HMAC_GENERAL:
  993. break;
  994. default:
  995. DBG_fprintf("The token in slot %lx has reported that it can "
  996. "perform\nmechanism 0x%lx, which is not available to "
  997. "accelerate in openssl.\n", slot_id, mech_list[i]);
  998. break;
  999. }
  1000. }
  1001. err_free:
  1002. OPENSSL_free(mech_list);
  1003. err:
  1004. return;
  1005. }
  1006. /* Add a new token struct to the list
  1007. * This is called during the bind_pkcs11, in other words after openSSL has
  1008. * decided to use us for some operation.
  1009. */
  1010. void pkcs11_addToken(CK_SLOT_ID slot_id)
  1011. {
  1012. struct _token *new_tok = (struct _token *) OPENSSL_malloc(sizeof(struct _token));
  1013. if (new_tok == NULL) {
  1014. PKCS11err(PKCS11_F_ADDTOKEN, PKCS11_R_MALLOC_FAILURE);
  1015. return;
  1016. }
  1017. memset(new_tok, 0, sizeof(struct _token));
  1018. new_tok->slot = slot_id;
  1019. new_tok->token_next = pkcs11_token_list;
  1020. pkcs11_token_list = new_tok;
  1021. }
  1022. /*
  1023. * pre_init_pkcs11: this is called at openSSL startup. Here is where we
  1024. * try to convince openSSL to use us. If it decides not to, there is no
  1025. * guarantee that we will ever be asked to clean up. So everything we
  1026. * do must be self-contained.
  1027. */
  1028. static int pre_init_pkcs11(ENGINE *e)
  1029. {
  1030. CK_C_GetFunctionList p;
  1031. CK_RV rv = CKR_OK;
  1032. CK_INFO Info;
  1033. CK_SLOT_ID_PTR pSlotList;
  1034. CK_ULONG ulSlotCount;
  1035. CK_SLOT_INFO slotInfo;
  1036. int i;
  1037. if(pkcs11_dso)
  1038. {
  1039. PKCS11err(PKCS11_F_PREINIT, PKCS11_R_ALREADY_LOADED);
  1040. goto err;
  1041. }
  1042. /* Attempt to load PKCS#11 library */
  1043. pkcs11_dso = DSO_load(NULL, get_PKCS11_LIBNAME(), NULL, 0);
  1044. if(pkcs11_dso == NULL)
  1045. {
  1046. PKCS11err(PKCS11_F_PREINIT, PKCS11_R_DSO_FAILURE);
  1047. goto err;
  1048. }
  1049. /* get the C_GetFunctionList function from the loaded library */
  1050. p = (CK_C_GetFunctionList)DSO_bind_func(pkcs11_dso, PKCS11_GET_FUNCTION_LIST);
  1051. if ( !p )
  1052. {
  1053. PKCS11err(PKCS11_F_PREINIT, PKCS11_R_DSO_FAILURE);
  1054. goto err;
  1055. }
  1056. /* get the full function list from the loaded library */
  1057. rv = p(&pFunctionList);
  1058. if (rv != CKR_OK)
  1059. {
  1060. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_DSO_FAILURE, rv);
  1061. goto err;
  1062. }
  1063. #ifdef BULL_CRYPTOBOX
  1064. /* the address of the CryptoBox is in /etc/CryptoBox */
  1065. rv = C_InitializeRpc (NULL, NULL, NULL);
  1066. if (rv != CKR_OK)
  1067. goto err;
  1068. #endif
  1069. /* Initialize Cryptoki */
  1070. rv = pFunctionList->C_Initialize(NULL_PTR);
  1071. if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
  1072. {
  1073. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_INITIALIZE, rv);
  1074. goto err;
  1075. }
  1076. rv = pFunctionList->C_GetInfo(&Info);
  1077. if (rv != CKR_OK)
  1078. {
  1079. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_GETINFO, rv);
  1080. goto err;
  1081. }
  1082. if (strncmp((char *)Info.libraryDescription, BULL_TRUSTWAY_LIBRARY_DESCRIPTION, 32))
  1083. {
  1084. rv = pFunctionList->C_GetSlotList(TRUE, NULL_PTR, &ulSlotCount);
  1085. if ((rv != CKR_OK) || (ulSlotCount == 0))
  1086. {
  1087. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_GETSLOTLIST, rv);
  1088. }
  1089. else
  1090. {
  1091. pSlotList = (CK_SLOT_ID_PTR) OPENSSL_malloc(ulSlotCount * sizeof(CK_SLOT_ID));
  1092. if ( pSlotList != NULL)
  1093. {
  1094. rv = pFunctionList->C_GetSlotList(TRUE, pSlotList, &ulSlotCount);
  1095. if (rv != CKR_OK)
  1096. {
  1097. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_GETSLOTLIST, rv);
  1098. OPENSSL_free(pSlotList);
  1099. goto err;
  1100. }
  1101. /* Check each slot to see if there's a hardware token present.
  1102. */
  1103. for (i = 0; i < ulSlotCount; i++)
  1104. {
  1105. rv = pFunctionList->C_GetSlotInfo(pSlotList[i], &slotInfo);
  1106. if (rv != CKR_OK)
  1107. {
  1108. pkcs11_die(PKCS11_F_PREINIT, PKCS11_R_GETSLOTINFO, rv);
  1109. OPENSSL_free(pSlotList);
  1110. goto err;
  1111. }
  1112. pkcs11_regToken(e, pSlotList[i]);
  1113. }
  1114. OPENSSL_free(pSlotList);
  1115. }
  1116. }
  1117. }
  1118. else
  1119. {
  1120. /* Bull Trustway CC2000 crypto hardware detected */
  1121. Bull_TrustWay = TRUE;
  1122. SLOTID = 0xFFFFFFFF;
  1123. }
  1124. /* Finish with Cryptoki: We will restart if openSSL calls one of our
  1125. * functions */
  1126. pFunctionList->C_Finalize(NULL);
  1127. DSO_free(pkcs11_dso);
  1128. pkcs11_dso = NULL;
  1129. return 1;
  1130. err:
  1131. if(pkcs11_dso)
  1132. DSO_free(pkcs11_dso);
  1133. pkcs11_dso = NULL;
  1134. return 0;
  1135. }
  1136. /* initialization function */
  1137. /* This is called when openSSL has decided to use us, and warns us to
  1138. * initialize. pkcs11_finish will be called when all is done. */
  1139. static int pkcs11_init(ENGINE *e)
  1140. {
  1141. CK_C_GetFunctionList p;
  1142. CK_RV rv = CKR_OK;
  1143. CK_INFO Info;
  1144. CK_SLOT_ID_PTR pSlotList;
  1145. CK_ULONG ulSlotCount;
  1146. CK_SLOT_INFO slotInfo;
  1147. int i;
  1148. if(pkcs11_dso)
  1149. {
  1150. PKCS11err(PKCS11_F_INIT, PKCS11_R_ALREADY_LOADED);
  1151. goto err;
  1152. }
  1153. /* Attempt to load PKCS#11 library */
  1154. pkcs11_dso = DSO_load(NULL, get_PKCS11_LIBNAME(), NULL, 0);
  1155. if(pkcs11_dso == NULL)
  1156. {
  1157. PKCS11err(PKCS11_F_INIT, PKCS11_R_DSO_FAILURE);
  1158. goto err;
  1159. }
  1160. /* get the C_GetFunctionList function from the loaded library */
  1161. p = (CK_C_GetFunctionList)DSO_bind_func(pkcs11_dso, PKCS11_GET_FUNCTION_LIST);
  1162. if ( !p )
  1163. {
  1164. PKCS11err(PKCS11_F_INIT, PKCS11_R_DSO_FAILURE);
  1165. goto err;
  1166. }
  1167. /* get the full function list from the loaded library */
  1168. rv = p(&pFunctionList);
  1169. if (rv != CKR_OK)
  1170. {
  1171. pkcs11_die(PKCS11_F_INIT, PKCS11_R_DSO_FAILURE, rv);
  1172. goto err;
  1173. }
  1174. #ifdef BULL_CRYPTOBOX
  1175. /* the address of the CryptoBox is in /etc/CryptoBox */
  1176. rv = C_InitializeRpc (NULL, NULL, NULL);
  1177. if (rv != CKR_OK)
  1178. goto err;
  1179. #endif
  1180. rv = pFunctionList->C_Initialize(NULL_PTR);
  1181. if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
  1182. {
  1183. pkcs11_die(PKCS11_F_INIT, PKCS11_R_INITIALIZE, rv);
  1184. goto err;
  1185. }
  1186. rv = pFunctionList->C_GetInfo(&Info);
  1187. if (rv != CKR_OK)
  1188. {
  1189. pkcs11_die(PKCS11_F_INIT, PKCS11_R_GETINFO, rv);
  1190. goto err;
  1191. }
  1192. if (strncmp((char *)Info.libraryDescription, BULL_TRUSTWAY_LIBRARY_DESCRIPTION, 32))
  1193. {
  1194. rv = pFunctionList->C_GetSlotList(TRUE, NULL_PTR, &ulSlotCount);
  1195. if ((rv != CKR_OK) || (ulSlotCount == 0))
  1196. {
  1197. pkcs11_die(PKCS11_F_INIT, PKCS11_R_GETSLOTLIST, rv);
  1198. }
  1199. else
  1200. {
  1201. pSlotList = (CK_SLOT_ID_PTR) OPENSSL_malloc(ulSlotCount * sizeof(CK_SLOT_ID));
  1202. if ( pSlotList != NULL)
  1203. {
  1204. rv = pFunctionList->C_GetSlotList(TRUE, pSlotList, &ulSlotCount);
  1205. if (rv != CKR_OK)
  1206. {
  1207. pkcs11_die(PKCS11_F_INIT, PKCS11_R_GETSLOTLIST, rv);
  1208. OPENSSL_free(pSlotList);
  1209. goto err;
  1210. }
  1211. /* Check each slot to see if there's a hardware token present.
  1212. */
  1213. for (i = 0; i < ulSlotCount; i++)
  1214. {
  1215. rv = pFunctionList->C_GetSlotInfo(pSlotList[i], &slotInfo);
  1216. if (rv != CKR_OK)
  1217. {
  1218. pkcs11_die(PKCS11_F_INIT, PKCS11_R_GETSLOTINFO, rv);
  1219. OPENSSL_free(pSlotList);
  1220. goto err;
  1221. }
  1222. pkcs11_addToken(pSlotList[i]);
  1223. }
  1224. OPENSSL_free(pSlotList);
  1225. }
  1226. }
  1227. }
  1228. else
  1229. {
  1230. /* Bull Trustway CC2000 crypto hardware detected */
  1231. Bull_TrustWay = TRUE;
  1232. SLOTID = 0xFFFFFFFF;
  1233. }
  1234. #ifndef OPENSSL_NO_RSA
  1235. /* Everything's fine. */
  1236. if (rsaPubKey == -1)
  1237. rsaPubKey = RSA_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1238. if (rsaPrivKey == -1)
  1239. rsaPrivKey = RSA_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1240. if (deletePubKeyOnFree == -1)
  1241. deletePubKeyOnFree = RSA_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1242. if (deletePrivKeyOnFree == -1)
  1243. deletePrivKeyOnFree = RSA_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1244. #endif
  1245. if (pkcs11_token_list == NULL)
  1246. PKCS11err(PKCS11_F_INIT, PKCS11_R_NOTOKENS);
  1247. PKCS11_Initialized = 1;
  1248. /* TODO: This should only be done on linux systems */
  1249. pthread_atfork(NULL, NULL, (void(*)())pkcs11_atfork_init);
  1250. return 1;
  1251. err:
  1252. if(pkcs11_dso)
  1253. DSO_free(pkcs11_dso);
  1254. pkcs11_dso = NULL;
  1255. return 0;
  1256. }
  1257. /* Destructor (complements the "ENGINE_pkcs11()" constructor) */
  1258. /* XXX HUH? Can we just DSO_load once, then??? */
  1259. static int pkcs11_destroy(ENGINE *e)
  1260. {
  1261. DBG_fprintf("%s: called\n", __FUNCTION__);
  1262. fflush(stderr);
  1263. free_PKCS11_LIBNAME();
  1264. ERR_unload_pkcs11_strings();
  1265. return 1;
  1266. }
  1267. /* termination function */
  1268. static int pkcs11_finish(ENGINE *e)
  1269. {
  1270. struct _token *tmp;
  1271. if(pkcs11_dso == NULL)
  1272. {
  1273. PKCS11err(PKCS11_F_FINISH, PKCS11_R_NOT_LOADED);
  1274. goto err;
  1275. }
  1276. assert(pFunctionList != NULL);
  1277. while (pkcs11_token_list) {
  1278. tmp = pkcs11_token_list->token_next;
  1279. OPENSSL_free(pkcs11_token_list);
  1280. pkcs11_token_list = tmp;
  1281. }
  1282. pFunctionList->C_Finalize(NULL);
  1283. if(!DSO_free(pkcs11_dso))
  1284. { PKCS11err(PKCS11_F_FINISH, PKCS11_R_DSO_FAILURE);
  1285. goto err;
  1286. }
  1287. pkcs11_dso = NULL;
  1288. pFunctionList = NULL;
  1289. return 1;
  1290. err:
  1291. pkcs11_dso = NULL;
  1292. pFunctionList = NULL;
  1293. return 0;
  1294. }
  1295. static int pkcs11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
  1296. {
  1297. int initialized = ((pkcs11_dso == NULL) ? 0 : 1);
  1298. switch(cmd)
  1299. {
  1300. case PKCS11_CMD_SO_PATH:
  1301. if(p == NULL)
  1302. {
  1303. PKCS11err(PKCS11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
  1304. return 0;
  1305. }
  1306. if(initialized)
  1307. {
  1308. PKCS11err(PKCS11_F_CTRL, PKCS11_R_ALREADY_LOADED);
  1309. return 0;
  1310. }
  1311. return set_PKCS11_LIBNAME((const char*)p);
  1312. default:
  1313. break;
  1314. }
  1315. PKCS11err(PKCS11_F_CTRL,PKCS11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
  1316. return 0;
  1317. }
  1318. #ifndef OPENSSL_NO_RSA
  1319. CK_OBJECT_HANDLE pkcs11_FindOrCreateKey(CK_SESSION_HANDLE h,
  1320. RSA *rsa,
  1321. CK_OBJECT_CLASS oKey,
  1322. CK_BBOOL fKeyCreate)
  1323. {
  1324. CK_RV rv;
  1325. CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE;
  1326. int ret=0;
  1327. CK_ULONG Matches;
  1328. CK_KEY_TYPE kType = CKK_RSA;
  1329. CK_ULONG ulKeyAttributeCount;
  1330. CK_ATTRIBUTE pubKeyTemplate[] =
  1331. {
  1332. {CKA_CLASS, &oKey, sizeof(CK_OBJECT_CLASS)},
  1333. {CKA_KEY_TYPE, &kType, sizeof(CK_KEY_TYPE)},
  1334. {CKA_MODULUS, (void *)NULL, 0},
  1335. {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
  1336. };
  1337. CK_ATTRIBUTE privKeyTemplate[] =
  1338. {
  1339. {CKA_CLASS, &oKey, sizeof(CK_OBJECT_CLASS)},
  1340. {CKA_KEY_TYPE, &kType, sizeof(CK_KEY_TYPE)},
  1341. {CKA_MODULUS, (void *)NULL, 0},
  1342. {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
  1343. {CKA_PRIVATE_EXPONENT, (void *)NULL, 0},
  1344. {CKA_PRIME_1, (void *)NULL, 0},
  1345. {CKA_PRIME_2, (void *)NULL, 0},
  1346. {CKA_EXPONENT_1, (void *)NULL, 0},
  1347. {CKA_EXPONENT_2, (void *)NULL, 0},
  1348. {CKA_COEFFICIENT, (void *)NULL, 0}
  1349. };
  1350. long deletePubKey;
  1351. DBG_fprintf("%s\n", __FUNCTION__);
  1352. if (oKey == CKO_PUBLIC_KEY) {
  1353. DBG_fprintf("looking up a public key\n");
  1354. pubKeyTemplate[2].ulValueLen = BN_num_bytes(rsa->n);
  1355. pubKeyTemplate[2].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)pubKeyTemplate[2].ulValueLen);
  1356. ret = BN_bn2bin(rsa->n, pubKeyTemplate[2].pValue);
  1357. pubKeyTemplate[3].ulValueLen = BN_num_bytes(rsa->e);
  1358. pubKeyTemplate[3].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)pubKeyTemplate[3].ulValueLen);
  1359. ret = BN_bn2bin(rsa->e, pubKeyTemplate[3].pValue);
  1360. ulKeyAttributeCount = 4;
  1361. rv = pFunctionList->C_FindObjectsInit(h, pubKeyTemplate, ulKeyAttributeCount);
  1362. } else {
  1363. DBG_fprintf("looking up a private key\n");
  1364. privKeyTemplate[2].ulValueLen = BN_num_bytes(rsa->n);
  1365. privKeyTemplate[2].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[2].ulValueLen);
  1366. ret = BN_bn2bin(rsa->n, privKeyTemplate[2].pValue);
  1367. privKeyTemplate[3].ulValueLen = BN_num_bytes(rsa->e);
  1368. privKeyTemplate[3].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[3].ulValueLen);
  1369. ret = BN_bn2bin(rsa->e, privKeyTemplate[3].pValue);
  1370. privKeyTemplate[4].ulValueLen = BN_num_bytes(rsa->d);
  1371. privKeyTemplate[4].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[4].ulValueLen);
  1372. ret = BN_bn2bin(rsa->d, privKeyTemplate[4].pValue);
  1373. privKeyTemplate[5].ulValueLen = BN_num_bytes(rsa->p);
  1374. privKeyTemplate[5].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[5].ulValueLen);
  1375. ret = BN_bn2bin(rsa->p, privKeyTemplate[5].pValue);
  1376. privKeyTemplate[6].ulValueLen = BN_num_bytes(rsa->q);
  1377. privKeyTemplate[6].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[6].ulValueLen);
  1378. ret = BN_bn2bin(rsa->q, privKeyTemplate[6].pValue);
  1379. privKeyTemplate[7].ulValueLen = BN_num_bytes(rsa->dmp1);
  1380. privKeyTemplate[7].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[7].ulValueLen);
  1381. ret = BN_bn2bin(rsa->dmp1, privKeyTemplate[7].pValue);
  1382. privKeyTemplate[8].ulValueLen = BN_num_bytes(rsa->dmq1);
  1383. privKeyTemplate[8].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[8].ulValueLen);
  1384. ret = BN_bn2bin(rsa->dmq1, privKeyTemplate[8].pValue);
  1385. privKeyTemplate[9].ulValueLen = BN_num_bytes(rsa->iqmp);
  1386. privKeyTemplate[9].pValue = (CK_VOID_PTR)OPENSSL_malloc((size_t)privKeyTemplate[9].ulValueLen);
  1387. ret = BN_bn2bin(rsa->iqmp, privKeyTemplate[9].pValue);
  1388. ulKeyAttributeCount = 10;
  1389. rv = pFunctionList->C_FindObjectsInit(h, privKeyTemplate, ulKeyAttributeCount);
  1390. }
  1391. if (rv != CKR_OK)
  1392. {
  1393. pkcs11_die(PKCS11_F_FINDORCREATEKEY, PKCS11_R_FINDOBJECTSINIT, rv);
  1394. goto err;
  1395. }
  1396. rv = pFunctionList->C_FindObjects(h, &hKey, 1, &Matches);
  1397. if (rv != CKR_OK)
  1398. {
  1399. pkcs11_die(PKCS11_F_FINDORCREATEKEY, PKCS11_R_FINDOBJECTS, rv);
  1400. goto err;
  1401. }
  1402. rv = pFunctionList->C_FindObjectsFinal(h);
  1403. if (rv != CKR_OK)
  1404. {
  1405. pkcs11_die(PKCS11_F_FINDORCREATEKEY, PKCS11_R_FINDOBJECTSFINAL, rv);
  1406. goto err;
  1407. }
  1408. /* Assume there should be no more than one match */
  1409. if (Matches == 0)
  1410. {
  1411. DBG_fprintf("matches was 0, creating this key\n");
  1412. DBG_fprintf("rsa->n is %d bytes\n", BN_num_bytes(rsa->n));
  1413. if (fKeyCreate && BN_num_bytes(rsa->n)) {
  1414. if (oKey == CKO_PUBLIC_KEY)
  1415. rv = pFunctionList->C_CreateObject(h, pubKeyTemplate,
  1416. ulKeyAttributeCount, &hKey);
  1417. else
  1418. rv = pFunctionList->C_CreateObject(h, privKeyTemplate,
  1419. ulKeyAttributeCount, &hKey);
  1420. if (rv != CKR_OK)
  1421. {
  1422. DBG_fprintf("error creating key object.\n");
  1423. pkcs11_die(PKCS11_F_FINDORCREATEKEY, PKCS11_R_CREATEOBJECT, rv);
  1424. goto err;
  1425. }
  1426. else
  1427. {
  1428. DBG_fprintf("key obj created\n");
  1429. deletePubKey = TRUE;
  1430. if (oKey == CKO_PUBLIC_KEY)
  1431. RSA_set_ex_data(rsa, deletePubKeyOnFree,
  1432. (void *)deletePubKey);
  1433. else
  1434. RSA_set_ex_data(rsa, deletePrivKeyOnFree,
  1435. (void *)deletePubKey);
  1436. }
  1437. }
  1438. else
  1439. {
  1440. PKCS11err(PKCS11_F_FINDORCREATEKEY, PKCS11_R_OBJECT_NOT_FOUND);
  1441. goto err;
  1442. }
  1443. }
  1444. if (oKey == CKO_PUBLIC_KEY)
  1445. RSA_set_ex_data(rsa, rsaPubKey, (char *)hKey);
  1446. if (oKey == CKO_PRIVATE_KEY)
  1447. RSA_set_ex_data(rsa, rsaPrivKey, (char *)hKey);
  1448. err:
  1449. if (oKey == CKO_PUBLIC_KEY) {
  1450. if (pubKeyTemplate[2].pValue != NULL)
  1451. {
  1452. OPENSSL_free(pubKeyTemplate[2].pValue);
  1453. pubKeyTemplate[2].pValue = NULL;
  1454. }
  1455. if (pubKeyTemplate[3].pValue != NULL)
  1456. {
  1457. OPENSSL_free(pubKeyTemplate[3].pValue);
  1458. pubKeyTemplate[3].pValue = NULL;
  1459. }
  1460. } else {
  1461. if (privKeyTemplate[2].pValue != NULL)
  1462. {
  1463. OPENSSL_free(privKeyTemplate[2].pValue);
  1464. privKeyTemplate[2].pValue = NULL;
  1465. }
  1466. if (privKeyTemplate[3].pValue != NULL)
  1467. {
  1468. OPENSSL_free(privKeyTemplate[3].pValue);
  1469. privKeyTemplate[3].pValue = NULL;
  1470. }
  1471. if (privKeyTemplate[4].pValue != NULL)
  1472. {
  1473. OPENSSL_free(privKeyTemplate[4].pValue);
  1474. privKeyTemplate[4].pValue = NULL;
  1475. }
  1476. }
  1477. return hKey;
  1478. }
  1479. /*----------------------------------------------------------------*/
  1480. /* pkcs11_RSA_public_encrypt */
  1481. /* */
  1482. /* This function implements RSA public encryption. 'from_len'
  1483. bytes taken from 'from' and encrypted and put into 'to'. 'to' needs
  1484. to be at least RSA_size(rsa) bytes long. The number of bytes
  1485. written into 'to' is returned. -1 is returned on an error. The
  1486. operation performed is to = from^rsa->e mod rsa->n. */
  1487. /* for PKCS11, use C_EncryptInit + C_Encrypt */
  1488. /*----------------------------------------------------------------*/
  1489. static int pkcs11_RSA_public_encrypt(int flen,
  1490. const unsigned char *from,
  1491. unsigned char *to,
  1492. RSA *rsa,
  1493. int padding)
  1494. {
  1495. CK_ULONG bytesEncrypted=0;
  1496. CK_RV rv;
  1497. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1498. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1499. CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE;
  1500. struct token_session *wrapper = NULL;
  1501. CK_SESSION_HANDLE session;
  1502. DBG_fprintf("%s\n", __FUNCTION__);
  1503. if (padding != RSA_PKCS1_PADDING)
  1504. {
  1505. PKCS11err(PKCS11_F_RSA_PUB_ENC, PKCS11_R_UNKNOWN_PADDING_TYPE);
  1506. return -1;
  1507. }
  1508. wrapper = pkcs11_getSession();
  1509. if (!wrapper)
  1510. return 0;
  1511. session = wrapper->session;
  1512. hPublicKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPubKey);
  1513. if (hPublicKey == CK_INVALID_HANDLE)
  1514. hPublicKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PUBLIC_KEY, true);
  1515. if (hPublicKey != CK_INVALID_HANDLE)
  1516. {
  1517. rv = pFunctionList->C_EncryptInit(session, pMechanism, hPublicKey);
  1518. if (rv != CKR_OK)
  1519. {
  1520. pkcs11_die(PKCS11_F_RSA_PUB_ENC, PKCS11_R_ENCRYPTINIT, rv);
  1521. bytesEncrypted = -1;
  1522. goto out;
  1523. }
  1524. rv = pFunctionList->C_Encrypt(session, (unsigned char *)from,
  1525. flen, NULL_PTR, &bytesEncrypted);
  1526. if (rv != CKR_OK)
  1527. {
  1528. pkcs11_die(PKCS11_F_RSA_PUB_ENC, PKCS11_R_ENCRYPT, rv);
  1529. bytesEncrypted = -1;
  1530. goto out;
  1531. }
  1532. rv = pFunctionList->C_Encrypt(session, (unsigned char *)from,
  1533. flen, to, &bytesEncrypted);
  1534. if (rv != CKR_OK)
  1535. {
  1536. pkcs11_die(PKCS11_F_RSA_PUB_ENC, PKCS11_R_ENCRYPT, rv);
  1537. bytesEncrypted = -1;
  1538. goto out;
  1539. }
  1540. }
  1541. out:
  1542. OPENSSL_free(wrapper);
  1543. return bytesEncrypted;
  1544. }
  1545. /*----------------------------------------------------------------*/
  1546. /* pkcs11_RSA_private_encrypt */
  1547. /* This function implements RSA private encryption.
  1548. That corresponds to a signature and only the RSA_PKCS1_PADDING
  1549. is supported.
  1550. flen : bytes taken from 'from' and encrypted and put into 'to'.
  1551. to : needs to be at least bytes long.
  1552. ret : returns the number of bytes written into 'to' or -1 if an error.
  1553. for PKCS11 use C_SignInit + C_Sign */
  1554. /*----------------------------------------------------------------*/
  1555. static int pkcs11_RSA_private_encrypt(int flen,
  1556. const unsigned char *from,
  1557. unsigned char *to,
  1558. RSA *rsa,
  1559. int padding)
  1560. {
  1561. CK_ULONG ulSignatureLen=0;
  1562. CK_RV rv;
  1563. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1564. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1565. CK_OBJECT_HANDLE hPrivateKey= CK_INVALID_HANDLE;
  1566. struct token_session *wrapper = NULL;
  1567. CK_SESSION_HANDLE session;
  1568. DBG_fprintf("%s\n", __FUNCTION__);
  1569. if (padding != RSA_PKCS1_PADDING)
  1570. {
  1571. PKCS11err(PKCS11_F_RSA_PRIV_ENC, PKCS11_R_UNKNOWN_PADDING_TYPE);
  1572. return -1;
  1573. }
  1574. wrapper = pkcs11_getSession();
  1575. if (!wrapper)
  1576. return 0;
  1577. session = wrapper->session;
  1578. hPrivateKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPrivKey);
  1579. if (hPrivateKey == CK_INVALID_HANDLE)
  1580. hPrivateKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PRIVATE_KEY, true);
  1581. if (hPrivateKey != CK_INVALID_HANDLE)
  1582. {
  1583. rv = pFunctionList->C_SignInit(session, pMechanism, hPrivateKey);
  1584. if (rv != CKR_OK)
  1585. {
  1586. pkcs11_die(PKCS11_F_RSA_PRIV_ENC, PKCS11_R_SIGNINIT, rv);
  1587. ulSignatureLen = -1;
  1588. goto out;
  1589. }
  1590. rv = pFunctionList->C_Sign(session, (unsigned char *)from,
  1591. flen, NULL_PTR, &ulSignatureLen);
  1592. if (rv != CKR_OK)
  1593. {
  1594. pkcs11_die(PKCS11_F_RSA_PRIV_ENC, PKCS11_R_SIGN, rv);
  1595. ulSignatureLen = -1;
  1596. goto out;
  1597. }
  1598. rv = pFunctionList->C_Sign(session, (unsigned char *)from,
  1599. flen, to, &ulSignatureLen);
  1600. if (rv != CKR_OK)
  1601. {
  1602. pkcs11_die(PKCS11_F_RSA_PRIV_ENC, PKCS11_R_SIGN, rv);
  1603. ulSignatureLen = -1;
  1604. goto out;
  1605. }
  1606. }
  1607. out:
  1608. OPENSSL_free(wrapper);
  1609. return ulSignatureLen;
  1610. }
  1611. /*----------------------------------------------------------------*/
  1612. /* pkcs11_RSA_private_decrypt */
  1613. /* */
  1614. /*This function implements RSA private decryption.
  1615. flen : bytes are taken from 'from' and decrypted.
  1616. The decrypted data is put into 'to'.
  1617. ret : returns the number of bytes -1 if an error.
  1618. The operation performed is to = from^rsa->d mod rsa->n.*/
  1619. /* for PKCS11 use C_DecryptInit + C_Decrypt */
  1620. /*----------------------------------------------------------------*/
  1621. static int pkcs11_RSA_private_decrypt(int flen,
  1622. const unsigned char *from,
  1623. unsigned char *to,
  1624. RSA *rsa,
  1625. int padding)
  1626. {
  1627. CK_ULONG bytesDecrypted = flen;
  1628. CK_RV rv;
  1629. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1630. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1631. CK_OBJECT_HANDLE hPrivateKey;
  1632. struct token_session *wrapper = NULL;
  1633. CK_SESSION_HANDLE session;
  1634. DBG_fprintf("%s\n", __FUNCTION__);
  1635. if (padding != RSA_PKCS1_PADDING)
  1636. {
  1637. PKCS11err(PKCS11_F_RSA_PRIV_DEC, PKCS11_R_UNKNOWN_PADDING_TYPE);
  1638. return -1;
  1639. }
  1640. wrapper = pkcs11_getSession();
  1641. if (!wrapper)
  1642. return 0;
  1643. session = wrapper->session;
  1644. hPrivateKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPrivKey);
  1645. if (hPrivateKey == CK_INVALID_HANDLE)
  1646. hPrivateKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PRIVATE_KEY, true);
  1647. if (hPrivateKey != CK_INVALID_HANDLE)
  1648. {
  1649. rv = pFunctionList->C_DecryptInit(session, pMechanism, hPrivateKey);
  1650. if (rv != CKR_OK)
  1651. {
  1652. pkcs11_die(PKCS11_F_RSA_PRIV_DEC, PKCS11_R_DECRYPTINIT, rv);
  1653. bytesDecrypted = -1;
  1654. goto out;
  1655. }
  1656. rv = pFunctionList->C_Decrypt(session, (unsigned char *)from,
  1657. flen, to, &bytesDecrypted);
  1658. if (rv != CKR_OK)
  1659. {
  1660. pkcs11_die(PKCS11_F_RSA_PRIV_DEC, PKCS11_R_DECRYPT, rv);
  1661. bytesDecrypted = -1;
  1662. goto out;
  1663. }
  1664. }
  1665. out:
  1666. OPENSSL_free(wrapper);
  1667. return bytesDecrypted;
  1668. }
  1669. /*----------------------------------------------------------------*/
  1670. /* pkcs11_RSA_public_decrypt */
  1671. /* */
  1672. /* This function implements RSA public decryption, the rsaKey
  1673. variable is the public key (but can be a private key).
  1674. This function should be processed as a pkcs11
  1675. verify-recover function
  1676. flen : bytes are taken from 'from' and decrypted.
  1677. to : The decrypted data.
  1678. ret : The number of bytes encrypted. -1 is returned to indicate an error.
  1679. The operation performed is to = from^rsa->e mod rsa->n.*/
  1680. /* for PKCS11 use C_VerifyRecoverInit + C_VerifyRecover */
  1681. /*'from' points to signature and 'flen' contains its length*/
  1682. /*----------------------------------------------------------------*/
  1683. static int pkcs11_RSA_public_decrypt(int flen,
  1684. const unsigned char *from,
  1685. unsigned char *to,
  1686. RSA *rsa,
  1687. int padding)
  1688. {
  1689. CK_ULONG bytesDecrypted = 0;
  1690. CK_RV rv;
  1691. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1692. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1693. CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE;
  1694. struct token_session *wrapper = NULL;
  1695. CK_SESSION_HANDLE session;
  1696. DBG_fprintf("%s\n", __FUNCTION__);
  1697. if (padding != RSA_PKCS1_PADDING)
  1698. {
  1699. PKCS11err(PKCS11_F_RSA_PUB_DEC, PKCS11_R_UNKNOWN_PADDING_TYPE);
  1700. return -1;
  1701. }
  1702. wrapper = pkcs11_getSession();
  1703. if (!wrapper)
  1704. return 0;
  1705. session = wrapper->session;
  1706. hPublicKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPubKey);
  1707. if (hPublicKey == CK_INVALID_HANDLE)
  1708. hPublicKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PUBLIC_KEY, true);
  1709. if (hPublicKey != CK_INVALID_HANDLE)
  1710. {
  1711. rv = pFunctionList->C_VerifyRecoverInit(session, pMechanism, hPublicKey);
  1712. if (rv != CKR_OK)
  1713. {
  1714. pkcs11_die(PKCS11_F_RSA_PUB_DEC, PKCS11_R_VERIFYRECOVERINIT, rv);
  1715. bytesDecrypted = -1;
  1716. goto out;
  1717. }
  1718. rv = pFunctionList->C_VerifyRecover(session, (unsigned char *)from,
  1719. flen, NULL_PTR, &bytesDecrypted);
  1720. if (rv != CKR_OK)
  1721. {
  1722. pkcs11_die(PKCS11_F_RSA_PUB_DEC, PKCS11_R_VERIFYRECOVER, rv);
  1723. bytesDecrypted = -1;
  1724. goto out;
  1725. }
  1726. rv = pFunctionList->C_VerifyRecover(session, (unsigned char *)from,
  1727. flen, to, &bytesDecrypted);
  1728. if (rv != CKR_OK)
  1729. {
  1730. pkcs11_die(PKCS11_F_RSA_PUB_DEC, PKCS11_R_VERIFYRECOVER, rv);
  1731. bytesDecrypted = -1;
  1732. goto out;
  1733. }
  1734. }
  1735. out:
  1736. OPENSSL_free(wrapper);
  1737. return bytesDecrypted;
  1738. }
  1739. static int pkcs11_RSA_init(RSA *rsa)
  1740. {
  1741. DBG_fprintf("%s\n", __FUNCTION__);
  1742. rsa->flags |= RSA_FLAG_SIGN_VER;
  1743. RSA_blinding_off(rsa);
  1744. return 1;
  1745. }
  1746. static int pkcs11_RSA_finish(RSA *rsa)
  1747. {
  1748. CK_RV rv;
  1749. CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE;
  1750. CK_OBJECT_HANDLE hPrivateKey = CK_INVALID_HANDLE;
  1751. long deletePubKey;
  1752. long deletePrivKey;
  1753. struct token_session *wrapper = NULL;
  1754. CK_SESSION_HANDLE session;
  1755. int err = 0;
  1756. DBG_fprintf("%s\n", __FUNCTION__);
  1757. if (rsa->_method_mod_n != NULL)
  1758. BN_MONT_CTX_free(rsa->_method_mod_n);
  1759. if (rsa->_method_mod_p != NULL)
  1760. BN_MONT_CTX_free(rsa->_method_mod_p);
  1761. if (rsa->_method_mod_q != NULL)
  1762. BN_MONT_CTX_free(rsa->_method_mod_q);
  1763. deletePrivKey = (long)RSA_get_ex_data(rsa, deletePrivKeyOnFree);
  1764. hPrivateKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPrivKey);
  1765. wrapper = pkcs11_getSession();
  1766. if (!wrapper)
  1767. return 0;
  1768. session = wrapper->session;
  1769. if ((deletePrivKey) && (hPrivateKey != CK_INVALID_HANDLE))
  1770. {
  1771. rv = pFunctionList->C_DestroyObject(session, hPrivateKey);
  1772. if (rv != CKR_OK)
  1773. {
  1774. pkcs11_die(PKCS11_F_RSA_FINISH, PKCS11_R_DESTROYOBJECT, rv);
  1775. goto out;
  1776. }
  1777. hPrivateKey = CK_INVALID_HANDLE;
  1778. RSA_set_ex_data(rsa, rsaPrivKey, (void *)hPrivateKey);
  1779. deletePrivKey = FALSE;
  1780. RSA_set_ex_data(rsa, deletePrivKeyOnFree, (void *)deletePrivKey);
  1781. }
  1782. deletePubKey = (long)RSA_get_ex_data(rsa, deletePubKeyOnFree);
  1783. hPublicKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPubKey);
  1784. if ((deletePubKey) && (hPublicKey != CK_INVALID_HANDLE))
  1785. {
  1786. rv = pFunctionList->C_DestroyObject(session, hPublicKey);
  1787. if (rv != CKR_OK)
  1788. {
  1789. pkcs11_die(PKCS11_F_RSA_FINISH, PKCS11_R_DESTROYOBJECT, rv);
  1790. goto out;
  1791. }
  1792. hPublicKey = CK_INVALID_HANDLE;
  1793. RSA_set_ex_data(rsa, rsaPubKey, (void *)hPublicKey);
  1794. deletePubKey = FALSE;
  1795. RSA_set_ex_data(rsa, deletePubKeyOnFree, (void *)deletePubKey);
  1796. }
  1797. err = 1;
  1798. out:
  1799. OPENSSL_free(wrapper);
  1800. return err;
  1801. }
  1802. static int pkcs11_RSA_sign(int type,
  1803. const unsigned char *m,
  1804. unsigned int m_len,
  1805. unsigned char *sigret,
  1806. unsigned int *siglen,
  1807. const RSA *rsa)
  1808. {
  1809. X509_SIG sig;
  1810. ASN1_TYPE parameter;
  1811. int i,j;
  1812. unsigned char *p,*s = NULL;
  1813. X509_ALGOR algor;
  1814. ASN1_OCTET_STRING digest;
  1815. CK_RV rv;
  1816. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1817. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1818. CK_OBJECT_HANDLE hPrivateKey;
  1819. int ret = 0;
  1820. struct token_session *wrapper = NULL;
  1821. CK_SESSION_HANDLE session;
  1822. CK_ULONG ulSigLen;
  1823. DBG_fprintf("%s\n", __FUNCTION__);
  1824. DBG_fprintf("rsa->n is %d bytes.\n", BN_num_bytes(rsa->n));
  1825. /* Encode the digest */
  1826. /* Special case: SSL signature, just check the length */
  1827. if(type == NID_md5_sha1)
  1828. {
  1829. if(m_len != SSL_SIG_LENGTH)
  1830. {
  1831. PKCS11err(PKCS11_F_RSA_SIGN, PKCS11_R_INVALID_MESSAGE_LENGTH);
  1832. DBG_fprintf("mlen = %d\n", m_len);
  1833. return 0;
  1834. }
  1835. i = SSL_SIG_LENGTH;
  1836. s = (unsigned char *)m;
  1837. }
  1838. else
  1839. {
  1840. sig.algor= &algor;
  1841. sig.algor->algorithm=OBJ_nid2obj(type);
  1842. if (sig.algor->algorithm == NULL)
  1843. {
  1844. PKCS11err(PKCS11_F_RSA_SIGN, PKCS11_R_UNKNOWN_ALGORITHM_TYPE);
  1845. return 0;
  1846. }
  1847. if (sig.algor->algorithm->length == 0)
  1848. {
  1849. PKCS11err(PKCS11_F_RSA_SIGN, PKCS11_R_UNKNOWN_ASN1_OBJECT_ID);
  1850. return 0;
  1851. }
  1852. parameter.type=V_ASN1_NULL;
  1853. parameter.value.ptr=NULL;
  1854. sig.algor->parameter= &parameter;
  1855. sig.digest= &digest;
  1856. sig.digest->data=(unsigned char *)m;
  1857. sig.digest->length=m_len;
  1858. i=i2d_X509_SIG(&sig,NULL);
  1859. }
  1860. j=RSA_size(rsa);
  1861. if ((i-RSA_PKCS1_PADDING) > j)
  1862. {
  1863. PKCS11err(PKCS11_F_RSA_SIGN, PKCS11_R_DIGEST_TOO_BIG);
  1864. return 0;
  1865. }
  1866. if(type != NID_md5_sha1)
  1867. {
  1868. s=(unsigned char *)OPENSSL_malloc((unsigned int)j+1);
  1869. if (s == NULL)
  1870. {
  1871. PKCS11err(PKCS11_F_RSA_SIGN, PKCS11_R_MALLOC_FAILURE);
  1872. return 0;
  1873. }
  1874. p=s;
  1875. i2d_X509_SIG(&sig,&p);
  1876. }
  1877. wrapper = pkcs11_getSession();
  1878. if (!wrapper)
  1879. return 0;
  1880. session = wrapper->session;
  1881. hPrivateKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPrivKey);
  1882. if (hPrivateKey == CK_INVALID_HANDLE)
  1883. hPrivateKey = pkcs11_FindOrCreateKey(session, (RSA *)rsa, CKO_PRIVATE_KEY, true);
  1884. if (hPrivateKey != CK_INVALID_HANDLE)
  1885. {
  1886. rv = pFunctionList->C_SignInit(session, pMechanism, hPrivateKey);
  1887. if (rv != CKR_OK)
  1888. {
  1889. pkcs11_die(PKCS11_F_RSA_SIGN, PKCS11_R_SIGNINIT, rv);
  1890. goto err;
  1891. }
  1892. ulSigLen = j;
  1893. rv = pFunctionList->C_Sign(session, s, i, sigret, &ulSigLen);
  1894. if (rv != CKR_OK)
  1895. {
  1896. pkcs11_die(PKCS11_F_RSA_SIGN, PKCS11_R_SIGN, rv);
  1897. goto err;
  1898. }
  1899. *siglen = (unsigned int)ulSigLen;
  1900. ret = 1;
  1901. }
  1902. DBG_fprintf("returning *siglen = %u\n", *siglen);
  1903. err:
  1904. if(type != NID_md5_sha1)
  1905. {
  1906. memset(s,0,(unsigned int)j+1);
  1907. OPENSSL_free(s);
  1908. }
  1909. OPENSSL_free(wrapper);
  1910. return ret;
  1911. }
  1912. #if (OPENSSL_VERSION_NUMBER < 0x10000000L)
  1913. static int pkcs11_RSA_verify(int type,
  1914. const unsigned char *m,
  1915. unsigned int m_len,
  1916. unsigned char *sigbuf,
  1917. unsigned int siglen,
  1918. const RSA *rsa)
  1919. #else
  1920. static int pkcs11_RSA_verify(int type,
  1921. const unsigned char *m,
  1922. unsigned int m_len,
  1923. const unsigned char *sigbuf,
  1924. unsigned int siglen,
  1925. const RSA *rsa)
  1926. #endif
  1927. {
  1928. X509_SIG sig;
  1929. ASN1_TYPE parameter;
  1930. int i,j;
  1931. unsigned char *p,*s = NULL;
  1932. X509_ALGOR algor;
  1933. ASN1_OCTET_STRING digest;
  1934. CK_RV rv;
  1935. CK_MECHANISM Mechanism_rsa = {CKM_RSA_PKCS, NULL, 0};
  1936. CK_MECHANISM *pMechanism = &Mechanism_rsa;
  1937. CK_OBJECT_HANDLE hPublicKey;
  1938. CK_ULONG ulSigLen;
  1939. int ret = 0;
  1940. struct token_session *wrapper = NULL;
  1941. CK_SESSION_HANDLE session;
  1942. DBG_fprintf("%s\n", __FUNCTION__);
  1943. /* Encode the digest */
  1944. /* Special case: SSL signature, just check the length */
  1945. if(type == NID_md5_sha1)
  1946. {
  1947. if(m_len != SSL_SIG_LENGTH)
  1948. {
  1949. PKCS11err(PKCS11_F_RSA_VERIFY, PKCS11_R_INVALID_MESSAGE_LENGTH);
  1950. DBG_fprintf("m_len = %d\n", m_len);
  1951. return 0;
  1952. }
  1953. i = SSL_SIG_LENGTH;
  1954. s = (unsigned char *)m;
  1955. }
  1956. else
  1957. {
  1958. sig.algor= &algor;
  1959. sig.algor->algorithm=OBJ_nid2obj(type);
  1960. if (sig.algor->algorithm == NULL)
  1961. {
  1962. PKCS11err(PKCS11_F_RSA_VERIFY, PKCS11_R_UNKNOWN_ALGORITHM_TYPE);
  1963. return 0;
  1964. }
  1965. if (sig.algor->algorithm->length == 0)
  1966. {
  1967. PKCS11err(PKCS11_F_RSA_VERIFY, PKCS11_R_UNKNOWN_ASN1_OBJECT_ID);
  1968. return 0;
  1969. }
  1970. parameter.type=V_ASN1_NULL;
  1971. parameter.value.ptr=NULL;
  1972. sig.algor->parameter= &parameter;
  1973. sig.digest= &digest;
  1974. sig.digest->data=(unsigned char *)m;
  1975. sig.digest->length=m_len;
  1976. i=i2d_X509_SIG(&sig,NULL);
  1977. }
  1978. j=RSA_size(rsa);
  1979. if ((i-RSA_PKCS1_PADDING) > j)
  1980. {
  1981. PKCS11err(PKCS11_F_RSA_VERIFY, PKCS11_R_DIGEST_TOO_BIG);
  1982. return 0;
  1983. }
  1984. if(type != NID_md5_sha1)
  1985. {
  1986. s=(unsigned char *)OPENSSL_malloc((unsigned int)j+1);
  1987. if (s == NULL)
  1988. {
  1989. PKCS11err(PKCS11_F_RSA_VERIFY, PKCS11_R_MALLOC_FAILURE);
  1990. return 0;
  1991. }
  1992. p=s;
  1993. i2d_X509_SIG(&sig,&p);
  1994. }
  1995. wrapper = pkcs11_getSession();
  1996. if (!wrapper)
  1997. return 0;
  1998. session = wrapper->session;
  1999. hPublicKey = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, rsaPubKey);
  2000. if (hPublicKey == CK_INVALID_HANDLE)
  2001. hPublicKey = pkcs11_FindOrCreateKey(session, (RSA *)rsa, CKO_PUBLIC_KEY, true);
  2002. if (hPublicKey != CK_INVALID_HANDLE)
  2003. {
  2004. rv = pFunctionList->C_VerifyInit(session, pMechanism, hPublicKey);
  2005. if (rv != CKR_OK)
  2006. {
  2007. pkcs11_die(PKCS11_F_RSA_VERIFY, PKCS11_R_VERIFYINIT, rv);
  2008. goto err;
  2009. }
  2010. ulSigLen = siglen;
  2011. rv = pFunctionList->C_Verify(session, s, i, (CK_BYTE_PTR)sigbuf, ulSigLen);
  2012. if (rv != CKR_OK)
  2013. {
  2014. pkcs11_die(PKCS11_F_RSA_VERIFY, PKCS11_R_VERIFY, rv);
  2015. goto err;
  2016. }
  2017. ret = 1;
  2018. }
  2019. err:
  2020. if(type != NID_md5_sha1)
  2021. {
  2022. memset(s,0,(unsigned int)siglen);
  2023. OPENSSL_free(s);
  2024. }
  2025. OPENSSL_free(wrapper);
  2026. return ret;
  2027. }
  2028. static int pkcs11_RSA_generate_key_with_mechanism(RSA* rsa,
  2029. CK_MECHANISM *pMechanism,
  2030. int bits,
  2031. BIGNUM *bn_e,
  2032. BN_GENCB *cb,
  2033. CK_BBOOL token)
  2034. {
  2035. CK_ULONG i;
  2036. CK_OBJECT_HANDLE hPublicKey;
  2037. CK_OBJECT_HANDLE hPrivateKey;
  2038. CK_OBJECT_CLASS oPublicKey = CKO_PUBLIC_KEY;
  2039. CK_OBJECT_CLASS oPrivateKey = CKO_PRIVATE_KEY;
  2040. CK_KEY_TYPE kType = CKK_RSA;
  2041. CK_ULONG ulPublicKeyAttributeCount = 8;
  2042. CK_ATTRIBUTE aPublicKeyTemplate[] =
  2043. {
  2044. {CKA_CLASS, &oPublicKey, sizeof(CK_OBJECT_CLASS)},
  2045. {CKA_TOKEN, (void *)NULL, 0},
  2046. {CKA_PRIVATE, &false, sizeof(CK_BBOOL)},
  2047. {CKA_MODIFIABLE, &false, sizeof(false)},
  2048. {CKA_KEY_TYPE, &kType, sizeof(CK_KEY_TYPE)},
  2049. {CKA_MODULUS_BITS, (void *)&bits, sizeof(bits)},
  2050. {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
  2051. {CKA_ID, PKCS11_KEY_ID, 16}
  2052. };
  2053. CK_ULONG ulPublicKeyAttributeResultCount = 2;
  2054. CK_ATTRIBUTE aPublicKeyResult[] =
  2055. {
  2056. {CKA_MODULUS, (void *)NULL, 0},
  2057. /* {CKA_MODULUS_BITS, (void *)NULL, 0}, */
  2058. {CKA_PUBLIC_EXPONENT, (void *)NULL, 0}
  2059. };
  2060. CK_ULONG ulPrivateKeyAttributeCount = 12;
  2061. CK_ATTRIBUTE aPrivateKeyTemplate[] =
  2062. {
  2063. {CKA_CLASS, &oPrivateKey, sizeof(CK_OBJECT_CLASS)},
  2064. {CKA_TOKEN, (void *)NULL, 0},
  2065. {CKA_PRIVATE, &false, sizeof(CK_BBOOL)},
  2066. {CKA_MODIFIABLE, &false, sizeof(CK_BBOOL)},
  2067. {CKA_KEY_TYPE, &kType, sizeof(CK_KEY_TYPE)},
  2068. {CKA_SENSITIVE, &true, sizeof(CK_BBOOL)},
  2069. {CKA_DECRYPT, &true, sizeof(CK_BBOOL)},
  2070. {CKA_SIGN, &true, sizeof(CK_BBOOL)},
  2071. {CKA_SIGN_RECOVER, &true, sizeof(CK_BBOOL)},
  2072. {CKA_UNWRAP, &true, sizeof(CK_BBOOL)},
  2073. {CKA_EXTRACTABLE, &true, sizeof(CK_BBOOL)},
  2074. {CKA_ID, PKCS11_KEY_ID, 16}
  2075. };
  2076. CK_RV rv;
  2077. CK_ATTRIBUTE *pModulus = NULL;
  2078. CK_ATTRIBUTE *pExponent = NULL;
  2079. int ret = 1;
  2080. struct token_session *wrapper = NULL;
  2081. CK_SESSION_HANDLE session;
  2082. DBG_fprintf("%s\n", __FUNCTION__);
  2083. aPublicKeyTemplate[6].ulValueLen = BN_num_bytes(bn_e);
  2084. aPublicKeyTemplate[6].pValue = OPENSSL_malloc(aPublicKeyTemplate[6].ulValueLen);
  2085. i = BN_bn2bin(bn_e, aPublicKeyTemplate[6].pValue);
  2086. aPublicKeyTemplate[1].ulValueLen = sizeof(token);
  2087. aPublicKeyTemplate[1].pValue = &token;
  2088. aPrivateKeyTemplate[1].ulValueLen = sizeof(token);
  2089. aPrivateKeyTemplate[1].pValue = &token;
  2090. wrapper = pkcs11_getSession();
  2091. if (!wrapper)
  2092. return 0;
  2093. session = wrapper->session;
  2094. rv = pFunctionList->C_GenerateKeyPair(session,
  2095. pMechanism,
  2096. aPublicKeyTemplate,
  2097. ulPublicKeyAttributeCount,
  2098. aPrivateKeyTemplate,
  2099. ulPrivateKeyAttributeCount,
  2100. &hPublicKey,
  2101. &hPrivateKey);
  2102. if (rv != CKR_OK)
  2103. {
  2104. pkcs11_die(PKCS11_F_RSA_GEN_KEY, PKCS11_R_GEN_KEY, rv);
  2105. ret = 0;
  2106. goto err;
  2107. }
  2108. rv = pFunctionList->C_GetAttributeValue(session, hPublicKey, aPublicKeyResult, ulPublicKeyAttributeResultCount);
  2109. switch(rv)
  2110. {
  2111. case CKR_OK:
  2112. for(i = 0; i < ulPublicKeyAttributeResultCount; i++)
  2113. { /* Al locate required buffers */
  2114. if (((CK_LONG) aPublicKeyResult[i].ulValueLen) == -1)
  2115. { /* can't get this attribute */
  2116. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_NO_MODULUS_OR_NO_EXPONENT);
  2117. goto err;
  2118. }
  2119. else
  2120. {
  2121. aPublicKeyResult[i].pValue = OPENSSL_malloc(aPublicKeyResult[i].ulValueLen);
  2122. if (!aPublicKeyResult[i].pValue)
  2123. {
  2124. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_GEN_KEY);
  2125. goto err;
  2126. }
  2127. }
  2128. }
  2129. break;
  2130. case CKR_ATTRIBUTE_SENSITIVE:
  2131. case CKR_ATTRIBUTE_TYPE_INVALID:
  2132. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_ATTRIBUT_SENSITIVE_OR_INVALID);
  2133. goto err;
  2134. default:
  2135. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_GETATTRIBUTVALUE);
  2136. goto err;
  2137. }
  2138. /* Then get the values */
  2139. rv = pFunctionList->C_GetAttributeValue(session, hPublicKey, aPublicKeyResult,ulPublicKeyAttributeResultCount);
  2140. switch(rv)
  2141. {
  2142. case CKR_OK:
  2143. break;
  2144. case CKR_ATTRIBUTE_SENSITIVE:
  2145. case CKR_ATTRIBUTE_TYPE_INVALID:
  2146. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_ATTRIBUT_SENSITIVE_OR_INVALID);
  2147. goto err;
  2148. default:
  2149. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_GETATTRIBUTVALUE);
  2150. goto err;
  2151. }
  2152. /* recherche du Modulus */
  2153. for(i = 0; i < ulPublicKeyAttributeResultCount; i++)
  2154. {
  2155. if (aPublicKeyResult[i].type == CKA_MODULUS)
  2156. {
  2157. if (((CK_LONG) aPublicKeyResult[i].ulValueLen) != -1)
  2158. {
  2159. pModulus = &(aPublicKeyResult[i]);
  2160. }
  2161. break;
  2162. }
  2163. }
  2164. if (pModulus == NULL)
  2165. {
  2166. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_NO_MODULUS);
  2167. goto err;
  2168. }
  2169. /* set n */
  2170. rsa->n = BN_bin2bn(pModulus->pValue, pModulus->ulValueLen, rsa->n);
  2171. /* search Exponent */
  2172. for(i = 0; i < ulPublicKeyAttributeResultCount; i++)
  2173. {
  2174. if (aPublicKeyResult[i].type == CKA_PUBLIC_EXPONENT)
  2175. {
  2176. if (((CK_LONG) aPublicKeyResult[i].ulValueLen) != -1)
  2177. {
  2178. pExponent = &(aPublicKeyResult[i]);
  2179. }
  2180. break;
  2181. }
  2182. }
  2183. if (pExponent == NULL)
  2184. {
  2185. PKCS11err(PKCS11_F_RSA_GEN_KEY, PKCS11_R_NO_EXPONENT);
  2186. goto err;
  2187. }
  2188. /* set e */
  2189. rsa->e = bn_e;
  2190. bn_e = NULL;
  2191. RSA_set_ex_data(rsa, rsaPubKey, (char *)hPublicKey);
  2192. RSA_set_ex_data(rsa, rsaPrivKey, (char *)hPrivateKey);
  2193. err:
  2194. for(i = 0; i < ulPublicKeyAttributeResultCount; i++)
  2195. {
  2196. if (aPublicKeyResult[i].pValue)
  2197. {
  2198. OPENSSL_free(aPublicKeyResult[i].pValue);
  2199. aPublicKeyResult[i].pValue = NULL;
  2200. }
  2201. }
  2202. if (aPublicKeyTemplate[6].pValue != NULL)
  2203. {
  2204. OPENSSL_free(aPublicKeyTemplate[6].pValue);
  2205. aPublicKeyTemplate[6].pValue = NULL;
  2206. }
  2207. OPENSSL_free(wrapper);
  2208. return ret;
  2209. }
  2210. /* ************************************************************ */
  2211. /* */
  2212. /* function : pkcs11_RSA_generate_key */
  2213. /* */
  2214. /* ************************************************************ */
  2215. static int pkcs11_RSA_generate_key(RSA* rsa,
  2216. int bits,
  2217. BIGNUM *bn_e,
  2218. BN_GENCB *cb
  2219. )
  2220. {
  2221. CK_MECHANISM Mechanism = {CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0};
  2222. CK_BBOOL token = TRUE;
  2223. return pkcs11_RSA_generate_key_with_mechanism(rsa, &Mechanism, bits, bn_e, cb, token);
  2224. }
  2225. #if 0
  2226. RSA* pkcs11_RSA_generate_tmp_key(int bits,unsigned long e_value,void (*callback)(int,int,void *),void *cb_arg)
  2227. {
  2228. RSA *rsa;
  2229. CK_MECHANISM Mechanism = {CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0};
  2230. CK_BBOOL token = FALSE;
  2231. unsigned int deleteKey;
  2232. DBG_fprintf("%s\n", __FUNCTION__);
  2233. rsa=RSA_new();
  2234. if (rsa == NULL)
  2235. return NULL;
  2236. else
  2237. {
  2238. if (pkcs11_RSA_generate_key_with_mechanism(rsa, &Mechanism, bits, e_value, callback, cb_arg, token))
  2239. {
  2240. deleteKey = TRUE;
  2241. RSA_set_ex_data(rsa, deletePubKeyOnFree, (void *)deleteKey);
  2242. RSA_set_ex_data(rsa, deletePrivKeyOnFree, (void *)deleteKey);
  2243. return rsa;
  2244. }
  2245. else
  2246. return NULL;
  2247. }
  2248. }
  2249. #endif
  2250. /* The private is found from the public key stored in PEM format in "pubkey_file" */
  2251. static EVP_PKEY *pkcs11_load_privkey(ENGINE* e, const char* pubkey_file,
  2252. UI_METHOD *ui_method, void *callback_data)
  2253. {
  2254. EVP_PKEY *pkey=NULL;
  2255. FILE *pubkey;
  2256. CK_OBJECT_HANDLE hPrivateKey = CK_INVALID_HANDLE;
  2257. RSA *rsa;
  2258. DBG_fprintf("%s\n", __FUNCTION__);
  2259. if ((pubkey=fopen(pubkey_file,"r")) != NULL)
  2260. {
  2261. pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
  2262. fclose(pubkey);
  2263. if (pkey)
  2264. {
  2265. rsa = EVP_PKEY_get1_RSA(pkey);
  2266. if (rsa)
  2267. {
  2268. struct token_session *wrapper = NULL;
  2269. CK_SESSION_HANDLE session;
  2270. wrapper = pkcs11_getSession();
  2271. if (!wrapper)
  2272. return 0;
  2273. session = wrapper->session;
  2274. hPrivateKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PRIVATE_KEY, true);
  2275. if (hPrivateKey == CK_INVALID_HANDLE)
  2276. {
  2277. EVP_PKEY_free(pkey);
  2278. pkey = NULL;
  2279. }
  2280. OPENSSL_free(wrapper);
  2281. }
  2282. else
  2283. {
  2284. EVP_PKEY_free(pkey);
  2285. pkey = NULL;
  2286. }
  2287. }
  2288. }
  2289. return(pkey);
  2290. }
  2291. static EVP_PKEY *pkcs11_load_pubkey(ENGINE* e, const char* pubkey_file,
  2292. UI_METHOD *ui_method, void *callback_data)
  2293. {
  2294. EVP_PKEY *pkey=NULL;
  2295. FILE *pubkey;
  2296. CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE;
  2297. RSA *rsa;
  2298. DBG_fprintf("%s\n", __FUNCTION__);
  2299. if ((pubkey=fopen(pubkey_file,"r")) != NULL)
  2300. {
  2301. pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
  2302. fclose(pubkey);
  2303. if (pkey)
  2304. {
  2305. rsa = EVP_PKEY_get1_RSA(pkey);
  2306. if (rsa)
  2307. {
  2308. struct token_session *wrapper = NULL;
  2309. CK_SESSION_HANDLE session;
  2310. wrapper = pkcs11_getSession();
  2311. if (!wrapper)
  2312. return 0;
  2313. session = wrapper->session;
  2314. hPublicKey = pkcs11_FindOrCreateKey(session, rsa, CKO_PUBLIC_KEY, true);
  2315. if (hPublicKey == CK_INVALID_HANDLE)
  2316. {
  2317. EVP_PKEY_free(pkey);
  2318. pkey = NULL;
  2319. }
  2320. OPENSSL_free(wrapper);
  2321. }
  2322. else
  2323. {
  2324. EVP_PKEY_free(pkey);
  2325. pkey = NULL;
  2326. }
  2327. }
  2328. }
  2329. return(pkey);
  2330. }
  2331. #endif
  2332. static void pkcs11_rand_cleanup(void)
  2333. {
  2334. return;
  2335. }
  2336. static void pkcs11_rand_add(const void *buf,
  2337. int num,
  2338. double entropy)
  2339. {
  2340. CK_RV rv;
  2341. struct token_session *wrapper;
  2342. DBG_fprintf("%s\n", __FUNCTION__);
  2343. /* return any token */
  2344. wrapper = pkcs11_getSession();
  2345. if (!wrapper)
  2346. return;
  2347. rv = pFunctionList->C_SeedRandom(wrapper->session, (CK_BYTE_PTR)&entropy, sizeof(entropy));
  2348. if (rv != CKR_OK)
  2349. {
  2350. pkcs11_die(PKCS11_F_RAND_ADD, PKCS11_R_SEEDRANDOM, rv);
  2351. return;
  2352. }
  2353. rv = pFunctionList->C_GenerateRandom(wrapper->session, (CK_BYTE *)buf, num);
  2354. if (rv != CKR_OK)
  2355. {
  2356. pkcs11_die(PKCS11_F_RAND_ADD, PKCS11_R_GENERATERANDOM, rv);
  2357. }
  2358. pFunctionList->C_CloseSession(wrapper->session);
  2359. OPENSSL_free(wrapper);
  2360. }
  2361. static void pkcs11_rand_seed(const void *buf,
  2362. int num)
  2363. {
  2364. DBG_fprintf("%s\n", __FUNCTION__);
  2365. pkcs11_rand_add(buf, num, num);
  2366. }
  2367. static int pkcs11_rand_bytes(unsigned char *buf,
  2368. int num)
  2369. {
  2370. CK_RV rv;
  2371. struct token_session *wrapper;
  2372. DBG_fprintf("%s\n", __FUNCTION__);
  2373. /* return any token */
  2374. wrapper = pkcs11_getSession();
  2375. if (!wrapper)
  2376. return 0;
  2377. rv = pFunctionList->C_GenerateRandom(wrapper->session, buf, num);
  2378. if (rv != CKR_OK)
  2379. {
  2380. pkcs11_die(PKCS11_F_RAND_BYTES, PKCS11_R_GENERATERANDOM, rv);
  2381. pFunctionList->C_CloseSession(wrapper->session);
  2382. OPENSSL_free(wrapper);
  2383. return 0;
  2384. }
  2385. pFunctionList->C_CloseSession(wrapper->session);
  2386. OPENSSL_free(wrapper);
  2387. return 1;
  2388. }
  2389. static int pkcs11_rand_status(void)
  2390. {
  2391. DBG_fprintf("%s\n", __FUNCTION__);
  2392. return 1;
  2393. }
  2394. static int pkcs11_des_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key,
  2395. const unsigned char *iv, int enc)
  2396. {
  2397. return pkcs11_init_key(ctx, key, iv, enc, alg_des);
  2398. }
  2399. static int pkcs11_tdes_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key,
  2400. const unsigned char *iv, int enc)
  2401. {
  2402. return pkcs11_init_key(ctx, key, iv, enc, alg_tdes);
  2403. }
  2404. static int pkcs11_aes_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key,
  2405. const unsigned char *iv, int enc)
  2406. {
  2407. return pkcs11_init_key(ctx, key, iv, enc, alg_aes);
  2408. }
  2409. static inline int get_mech(int alg, EVP_CIPHER_CTX *ctx)
  2410. {
  2411. switch (alg) {
  2412. case alg_des:
  2413. if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_ECB_MODE)
  2414. return CKM_DES_ECB;
  2415. else if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CBC_MODE) {
  2416. return CKM_DES_CBC;
  2417. }
  2418. return -1;
  2419. case alg_tdes:
  2420. if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_ECB_MODE)
  2421. return CKM_DES3_ECB;
  2422. else if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CBC_MODE) {
  2423. return CKM_DES3_CBC;
  2424. }
  2425. return -1;
  2426. case alg_aes:
  2427. if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_ECB_MODE) {
  2428. return CKM_AES_ECB;
  2429. } else if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CBC_MODE) {
  2430. return CKM_AES_CBC;
  2431. }
  2432. return -1;
  2433. case alg_sha:
  2434. return CKM_SHA_1;
  2435. case alg_md5:
  2436. return CKM_MD5;
  2437. case alg_ripemd:
  2438. return CKM_RIPEMD160;
  2439. default:
  2440. return -1;
  2441. }
  2442. }
  2443. static int pkcs11_init_key(EVP_CIPHER_CTX * ctx, const unsigned char *key,
  2444. const unsigned char *iv, int enc, int alg)
  2445. {
  2446. int ret = 0;
  2447. CK_RV rv;
  2448. CK_MECHANISM_TYPE mech = get_mech(alg, ctx);
  2449. CK_MECHANISM mechanism = { mech, NULL, 0 };
  2450. CK_SESSION_HANDLE session;
  2451. struct _token *token;
  2452. struct token_session *wrapper = pkcs11_getSession();
  2453. CK_BBOOL true = TRUE;
  2454. CK_BBOOL boolenc;
  2455. CK_OBJECT_CLASS class = CKO_SECRET_KEY;
  2456. CK_KEY_TYPE keyType;
  2457. /* A secret key template */
  2458. CK_ATTRIBUTE template[] = {
  2459. {CKA_CLASS, &class, sizeof(class)},
  2460. {CKA_KEY_TYPE, &keyType, sizeof(keyType)},
  2461. {CKA_TOKEN, &true, sizeof(true)},
  2462. {CKA_ENCRYPT, &boolenc, sizeof(boolenc)},
  2463. {CKA_VALUE, (void *)key, EVP_CIPHER_CTX_key_length(ctx)}
  2464. };
  2465. /* and finally a cryptoki key handle */
  2466. CK_OBJECT_HANDLE hkey;
  2467. DBG_fprintf("%s\n", __FUNCTION__);
  2468. DBG_fprintf("EVP_CIPHER_CTX_mode(ctx): %lu, EVP_CIPH_CBC_MODE: %d, iv: %p, ctx->iv: %p\n",
  2469. EVP_CIPHER_CTX_mode(ctx), EVP_CIPH_CBC_MODE, iv, ctx->iv);
  2470. if (mech==-1) {
  2471. PKCS11err(PKCS11_F_INITKEY, PKCS11_R_BADMECHANISM);
  2472. goto out;
  2473. } else if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CBC_MODE) {
  2474. mechanism.pParameter = (CK_VOID_PTR)(iv ? iv : ctx->iv);
  2475. mechanism.ulParameterLen = EVP_CIPHER_CTX_iv_length(ctx);
  2476. if (mechanism.pParameter == NULL || mechanism.ulParameterLen == 0) {
  2477. PKCS11err(PKCS11_F_INITKEY, PKCS11_R_BADMECHANISM);
  2478. goto out;
  2479. }
  2480. }
  2481. if (!wrapper)
  2482. goto out;
  2483. /* Save the token number and session ID in the cipher context's
  2484. * private data area. The operation will have to continue on this
  2485. * token later.
  2486. */
  2487. token = wrapper->token;
  2488. session = wrapper->session;
  2489. CIPHER_DATA(ctx)->token = token;
  2490. CIPHER_DATA(ctx)->session = session;
  2491. OPENSSL_free(wrapper);
  2492. switch (alg) {
  2493. case alg_des:
  2494. keyType = CKK_DES;
  2495. break;
  2496. case alg_tdes:
  2497. keyType = CKK_DES3;
  2498. break;
  2499. case alg_aes:
  2500. keyType = CKK_AES;
  2501. break;
  2502. default:
  2503. PKCS11err(PKCS11_F_INITKEY, PKCS11_R_UNKNOWN_ALGORITHM_TYPE);
  2504. ERR_add_error_data(1, alg_to_string(alg));
  2505. goto out_closesession;
  2506. break;
  2507. }
  2508. boolenc = (enc ? TRUE : FALSE);
  2509. rv = pFunctionList->C_CreateObject(session, template, 5, &hkey);
  2510. if (rv != CKR_OK) {
  2511. pkcs11_die(PKCS11_F_INITKEY, PKCS11_R_CREATEOBJECT, rv);
  2512. goto out_closesession;
  2513. }
  2514. if (enc) {
  2515. rv = pFunctionList->C_EncryptInit(session, &mechanism, hkey);
  2516. if (rv != CKR_OK) {
  2517. pkcs11_die(PKCS11_F_INITKEY, PKCS11_R_ENCRYPTINIT, rv);
  2518. goto out_closesession;
  2519. }
  2520. } else {
  2521. rv = pFunctionList->C_DecryptInit(session, &mechanism, hkey);
  2522. if (rv != CKR_OK) {
  2523. pkcs11_die(PKCS11_F_INITKEY, PKCS11_R_DECRYPTINIT, rv);
  2524. goto out_closesession;
  2525. }
  2526. }
  2527. ret = 1;
  2528. goto out;
  2529. out_closesession:
  2530. /* Execute only if we opened a session, but then failed */
  2531. pFunctionList->C_CloseSession(session);
  2532. out:
  2533. return ret;
  2534. } // end pkcs11_init_key
  2535. static int
  2536. pkcs11_cipher_cleanup(EVP_CIPHER_CTX *ctx)
  2537. {
  2538. DBG_fprintf("%s\n", __FUNCTION__);
  2539. pFunctionList->C_CloseSession(CIPHER_DATA(ctx)->session);
  2540. CIPHER_DATA(ctx)->session = CK_INVALID_HANDLE;
  2541. return 1;
  2542. }
  2543. static inline int pkcs11_cipher(EVP_CIPHER_CTX * ctx, unsigned char *out,
  2544. const unsigned char *in, unsigned int inlen)
  2545. {
  2546. unsigned long outlen = inlen;
  2547. CK_RV rv;
  2548. CK_SESSION_HANDLE session;
  2549. DBG_fprintf("%s\n", __FUNCTION__);
  2550. session = CIPHER_DATA(ctx)->session;
  2551. if (ctx->encrypt) {
  2552. rv = pFunctionList->C_EncryptUpdate(session, (void *)in, inlen, (void *)out, &outlen);
  2553. if (rv) {
  2554. pkcs11_die(PKCS11_F_CIPHER_UPDATE, PKCS11_R_ENCRYPT, rv);
  2555. return 0;
  2556. }
  2557. } else {
  2558. rv = pFunctionList->C_DecryptUpdate(session, (void *)in, inlen, (void *)out, &outlen);
  2559. if (rv) {
  2560. pkcs11_die(PKCS11_F_CIPHER_UPDATE, PKCS11_R_DECRYPT, rv);
  2561. return 0;
  2562. }
  2563. }
  2564. return 1;
  2565. }
  2566. static inline int
  2567. pkcs11_sha1_init(EVP_MD_CTX *ctx)
  2568. {
  2569. return pkcs11_digest_init(ctx, alg_sha);
  2570. }
  2571. static inline int
  2572. pkcs11_sha224_init(EVP_MD_CTX *ctx)
  2573. {
  2574. return pkcs11_digest_init(ctx, alg_sha224);
  2575. }
  2576. static inline int
  2577. pkcs11_sha256_init(EVP_MD_CTX *ctx)
  2578. {
  2579. return pkcs11_digest_init(ctx, alg_sha256);
  2580. }
  2581. static inline int
  2582. pkcs11_sha384_init(EVP_MD_CTX *ctx)
  2583. {
  2584. return pkcs11_digest_init(ctx, alg_sha384);
  2585. }
  2586. static inline int
  2587. pkcs11_sha512_init(EVP_MD_CTX *ctx)
  2588. {
  2589. return pkcs11_digest_init(ctx, alg_sha512);
  2590. }
  2591. static inline int
  2592. pkcs11_md5_init(EVP_MD_CTX *ctx)
  2593. {
  2594. return pkcs11_digest_init(ctx, alg_md5);
  2595. }
  2596. static inline int
  2597. pkcs11_ripemd_init(EVP_MD_CTX *ctx)
  2598. {
  2599. return pkcs11_digest_init(ctx, alg_ripemd);
  2600. }
  2601. static inline int
  2602. pkcs11_digest_init(EVP_MD_CTX *ctx, int alg)
  2603. {
  2604. struct pkcs11_digest_ctx *ctx_data = ctx->md_data;
  2605. DBG_fprintf("%s, alg = %d\n", __FUNCTION__, alg);
  2606. memset(ctx_data, 0, sizeof(struct pkcs11_digest_ctx));
  2607. ctx_data->alg = alg;
  2608. ctx_data->ref_cnt = OPENSSL_malloc(sizeof(int));
  2609. DBG_fprintf("%s, ref_cnt = %p\n", __FUNCTION__, ctx_data->ref_cnt);
  2610. *ctx_data->ref_cnt = 0;
  2611. return 1;
  2612. }
  2613. static int
  2614. pkcs11_digest_update(EVP_MD_CTX *ctx, const void *in, size_t len)
  2615. {
  2616. struct pkcs11_digest_ctx *ctx_data;
  2617. DBG_fprintf("%s, len = %lu\n", __FUNCTION__, len);
  2618. if (!MD_DATA(ctx)) {
  2619. PKCS11err(PKCS11_F_DIGESTUPDATE, PKCS11_R_PASSED_NULL_PARAMETER);
  2620. return 0;
  2621. }
  2622. ctx_data = (struct pkcs11_digest_ctx *)MD_DATA(ctx);
  2623. while (len + ctx_data->len > ctx_data->size) {
  2624. ctx_data->size += PKCS11_DIGEST_BLOCK_SIZE;
  2625. ctx_data->data = realloc(ctx_data->data, ctx_data->size);
  2626. }
  2627. memcpy(ctx_data->data + ctx_data->len, in, len);
  2628. ctx_data->len += len;
  2629. return 1;
  2630. }
  2631. static int
  2632. pkcs11_digest_finish(EVP_MD_CTX *ctx, unsigned char *md)
  2633. {
  2634. CK_ULONG len = EVP_MD_CTX_size(ctx);
  2635. CK_RV rv;
  2636. struct pkcs11_digest_ctx *data = (struct pkcs11_digest_ctx *)MD_DATA(ctx);
  2637. int ret = 0, alg = data->alg;
  2638. struct token_session *wrapper = pkcs11_getSession();
  2639. CK_MECHANISM_TYPE mech = get_mech(alg, NULL);
  2640. CK_MECHANISM mechanism = {mech, NULL, 0};
  2641. DBG_fprintf("%s\n", __FUNCTION__);
  2642. if (!wrapper)
  2643. goto out;
  2644. switch (alg) {
  2645. case alg_sha:
  2646. mech = CKM_SHA_1;
  2647. break;
  2648. case alg_sha224:
  2649. mech = CKM_SHA224;
  2650. break;
  2651. case alg_sha256:
  2652. mech = CKM_SHA256;
  2653. break;
  2654. case alg_sha384:
  2655. mech = CKM_SHA384;
  2656. break;
  2657. case alg_sha512:
  2658. mech = CKM_SHA512;
  2659. break;
  2660. case alg_md5:
  2661. mech = CKM_MD5;
  2662. break;
  2663. case alg_ripemd:
  2664. mech = CKM_RIPEMD160;
  2665. break;
  2666. default:
  2667. PKCS11err(PKCS11_F_DIGESTFINISH, PKCS11_R_UNKNOWN_ALGORITHM_TYPE);
  2668. ERR_add_error_data(1, alg_to_string(alg));
  2669. goto out_endsession;
  2670. break;
  2671. }
  2672. rv = pFunctionList->C_DigestInit(wrapper->session, &mechanism);
  2673. if (rv != CKR_OK) {
  2674. pkcs11_die(PKCS11_F_DIGESTFINISH, PKCS11_R_DIGESTINIT, rv);
  2675. goto out_endsession;
  2676. }
  2677. rv = pFunctionList->C_Digest(wrapper->session, (CK_BYTE_PTR)data->data, data->len, md,
  2678. &len);
  2679. if (rv != CKR_OK) {
  2680. pkcs11_die(PKCS11_F_DIGESTFINISH, PKCS11_R_DIGEST, rv);
  2681. goto out_endsession;
  2682. }
  2683. if (*data->ref_cnt == 0) {
  2684. OPENSSL_free(data->data);
  2685. OPENSSL_free(data->ref_cnt);
  2686. } else
  2687. *(data->ref_cnt) -= 1;
  2688. memset(data, 0, sizeof(struct pkcs11_digest_ctx));
  2689. ret = 1;
  2690. out_endsession:
  2691. pFunctionList->C_CloseSession(wrapper->session);
  2692. OPENSSL_free(wrapper);
  2693. out:
  2694. return ret;
  2695. }
  2696. static int
  2697. pkcs11_digest_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in)
  2698. {
  2699. struct pkcs11_digest_ctx *data = out->md_data;
  2700. #if 0
  2701. struct pkcs11_digest_ctx *indata = in->md_data;
  2702. /* TODO: change this to a refcount */
  2703. data->data = (char *)OPENSSL_malloc(data->len);
  2704. memcpy(data->data, indata->data, data->len);
  2705. #else
  2706. DBG_fprintf("%s, ref_cnt addr: %p, val: %d\n", __FUNCTION__, data->ref_cnt,
  2707. *(data->ref_cnt));
  2708. *(data->ref_cnt) += 1;
  2709. DBG_fprintf("%s, ref_cnt addr: %p, val: %d\n", __FUNCTION__, data->ref_cnt,
  2710. *(data->ref_cnt));
  2711. #endif
  2712. return 1;
  2713. }
  2714. static inline int
  2715. pkcs11_digest_cleanup(EVP_MD_CTX *ctx)
  2716. {
  2717. return 1;
  2718. }
  2719. #endif
  2720. #endif