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.

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