e_capi.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905
  1. /*
  2. * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #ifdef _WIN32
  10. # ifndef _WIN32_WINNT
  11. # define _WIN32_WINNT 0x0400
  12. # endif
  13. # include <windows.h>
  14. # include <wincrypt.h>
  15. # include <stdio.h>
  16. # include <string.h>
  17. # include <stdlib.h>
  18. # include <malloc.h>
  19. # ifndef alloca
  20. # define alloca _alloca
  21. # endif
  22. # include <openssl/crypto.h>
  23. # ifndef OPENSSL_NO_CAPIENG
  24. # include <openssl/buffer.h>
  25. # include <openssl/bn.h>
  26. # include <openssl/rsa.h>
  27. # include <openssl/dsa.h>
  28. /*
  29. * This module uses several "new" interfaces, among which is
  30. * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is
  31. * one of possible values you can pass to function in question. By
  32. * checking if it's defined we can see if wincrypt.h and accompanying
  33. * crypt32.lib are in shape. The native MingW32 headers up to and
  34. * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the
  35. * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG,
  36. * so we check for these too and avoid compiling.
  37. * Yes, it's rather "weak" test and if compilation fails,
  38. * then re-configure with -DOPENSSL_NO_CAPIENG.
  39. */
  40. # if defined(CERT_KEY_PROV_INFO_PROP_ID) && \
  41. defined(CERT_STORE_PROV_SYSTEM_A) && \
  42. defined(CERT_STORE_READONLY_FLAG)
  43. # define __COMPILE_CAPIENG
  44. # endif /* CERT_KEY_PROV_INFO_PROP_ID */
  45. # endif /* OPENSSL_NO_CAPIENG */
  46. #endif /* _WIN32 */
  47. #ifdef __COMPILE_CAPIENG
  48. # undef X509_EXTENSIONS
  49. /* Definitions which may be missing from earlier version of headers */
  50. # ifndef CERT_STORE_OPEN_EXISTING_FLAG
  51. # define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
  52. # endif
  53. # ifndef CERT_STORE_CREATE_NEW_FLAG
  54. # define CERT_STORE_CREATE_NEW_FLAG 0x00002000
  55. # endif
  56. # ifndef CERT_SYSTEM_STORE_CURRENT_USER
  57. # define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000
  58. # endif
  59. # ifndef ALG_SID_SHA_256
  60. # define ALG_SID_SHA_256 12
  61. # endif
  62. # ifndef ALG_SID_SHA_384
  63. # define ALG_SID_SHA_384 13
  64. # endif
  65. # ifndef ALG_SID_SHA_512
  66. # define ALG_SID_SHA_512 14
  67. # endif
  68. # ifndef CALG_SHA_256
  69. # define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
  70. # endif
  71. # ifndef CALG_SHA_384
  72. # define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
  73. # endif
  74. # ifndef CALG_SHA_512
  75. # define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
  76. # endif
  77. # ifndef PROV_RSA_AES
  78. # define PROV_RSA_AES 24
  79. # endif
  80. # include <openssl/engine.h>
  81. # include <openssl/pem.h>
  82. # include <openssl/x509v3.h>
  83. # include "e_capi_err.h"
  84. # include "e_capi_err.c"
  85. static const char *engine_capi_id = "capi";
  86. static const char *engine_capi_name = "CryptoAPI ENGINE";
  87. typedef struct CAPI_CTX_st CAPI_CTX;
  88. typedef struct CAPI_KEY_st CAPI_KEY;
  89. static void capi_addlasterror(void);
  90. static void capi_adderror(DWORD err);
  91. static void CAPI_trace(CAPI_CTX * ctx, char *format, ...);
  92. static int capi_list_providers(CAPI_CTX * ctx, BIO *out);
  93. static int capi_list_containers(CAPI_CTX * ctx, BIO *out);
  94. int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *storename);
  95. void capi_free_key(CAPI_KEY * key);
  96. static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
  97. HCERTSTORE hstore);
  98. CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id);
  99. static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
  100. UI_METHOD *ui_method, void *callback_data);
  101. static int capi_rsa_sign(int dtype, const unsigned char *m,
  102. unsigned int m_len, unsigned char *sigret,
  103. unsigned int *siglen, const RSA *rsa);
  104. static int capi_rsa_priv_enc(int flen, const unsigned char *from,
  105. unsigned char *to, RSA *rsa, int padding);
  106. static int capi_rsa_priv_dec(int flen, const unsigned char *from,
  107. unsigned char *to, RSA *rsa, int padding);
  108. static int capi_rsa_free(RSA *rsa);
  109. # ifndef OPENSSL_NO_DSA
  110. static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
  111. DSA *dsa);
  112. static int capi_dsa_free(DSA *dsa);
  113. # endif
  114. static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
  115. STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
  116. EVP_PKEY **pkey, STACK_OF(X509) **pother,
  117. UI_METHOD *ui_method,
  118. void *callback_data);
  119. static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
  120. # ifdef OPENSSL_CAPIENG_DIALOG
  121. static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
  122. # endif
  123. void engine_load_capi_int(void);
  124. typedef PCCERT_CONTEXT(WINAPI *CERTDLG)(HCERTSTORE, HWND, LPCWSTR,
  125. LPCWSTR, DWORD, DWORD, void *);
  126. typedef HWND(WINAPI *GETCONSWIN)(void);
  127. /*
  128. * This structure contains CAPI ENGINE specific data: it contains various
  129. * global options and affects how other functions behave.
  130. */
  131. # define CAPI_DBG_TRACE 2
  132. # define CAPI_DBG_ERROR 1
  133. struct CAPI_CTX_st {
  134. int debug_level;
  135. char *debug_file;
  136. /* Parameters to use for container lookup */
  137. DWORD keytype;
  138. LPSTR cspname;
  139. DWORD csptype;
  140. /* Certificate store name to use */
  141. LPSTR storename;
  142. LPSTR ssl_client_store;
  143. /* System store flags */
  144. DWORD store_flags;
  145. /* Lookup string meanings in load_private_key */
  146. # define CAPI_LU_SUBSTR 1 /* Substring of subject: uses "storename" */
  147. # define CAPI_LU_FNAME 2 /* Friendly name: uses storename */
  148. # define CAPI_LU_CONTNAME 3 /* Container name: uses cspname, keytype */
  149. int lookup_method;
  150. /* Info to dump with dumpcerts option */
  151. # define CAPI_DMP_SUMMARY 0x1 /* Issuer and serial name strings */
  152. # define CAPI_DMP_FNAME 0x2 /* Friendly name */
  153. # define CAPI_DMP_FULL 0x4 /* Full X509_print dump */
  154. # define CAPI_DMP_PEM 0x8 /* Dump PEM format certificate */
  155. # define CAPI_DMP_PSKEY 0x10 /* Dump pseudo key (if possible) */
  156. # define CAPI_DMP_PKEYINFO 0x20 /* Dump key info (if possible) */
  157. DWORD dump_flags;
  158. int (*client_cert_select) (ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
  159. CERTDLG certselectdlg;
  160. GETCONSWIN getconswindow;
  161. };
  162. static CAPI_CTX *capi_ctx_new(void);
  163. static void capi_ctx_free(CAPI_CTX * ctx);
  164. static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
  165. int check);
  166. static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx);
  167. # define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
  168. # define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
  169. # define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
  170. # define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
  171. # define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
  172. # define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
  173. # define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
  174. # define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
  175. # define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
  176. # define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
  177. # define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
  178. # define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
  179. # define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
  180. # define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
  181. static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
  182. {CAPI_CMD_LIST_CERTS,
  183. "list_certs",
  184. "List all certificates in store",
  185. ENGINE_CMD_FLAG_NO_INPUT},
  186. {CAPI_CMD_LOOKUP_CERT,
  187. "lookup_cert",
  188. "Lookup and output certificates",
  189. ENGINE_CMD_FLAG_STRING},
  190. {CAPI_CMD_DEBUG_LEVEL,
  191. "debug_level",
  192. "debug level (1=errors, 2=trace)",
  193. ENGINE_CMD_FLAG_NUMERIC},
  194. {CAPI_CMD_DEBUG_FILE,
  195. "debug_file",
  196. "debugging filename)",
  197. ENGINE_CMD_FLAG_STRING},
  198. {CAPI_CMD_KEYTYPE,
  199. "key_type",
  200. "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
  201. ENGINE_CMD_FLAG_NUMERIC},
  202. {CAPI_CMD_LIST_CSPS,
  203. "list_csps",
  204. "List all CSPs",
  205. ENGINE_CMD_FLAG_NO_INPUT},
  206. {CAPI_CMD_SET_CSP_IDX,
  207. "csp_idx",
  208. "Set CSP by index",
  209. ENGINE_CMD_FLAG_NUMERIC},
  210. {CAPI_CMD_SET_CSP_NAME,
  211. "csp_name",
  212. "Set CSP name, (default CSP used if not specified)",
  213. ENGINE_CMD_FLAG_STRING},
  214. {CAPI_CMD_SET_CSP_TYPE,
  215. "csp_type",
  216. "Set CSP type, (default RSA_PROV_FULL)",
  217. ENGINE_CMD_FLAG_NUMERIC},
  218. {CAPI_CMD_LIST_CONTAINERS,
  219. "list_containers",
  220. "list container names",
  221. ENGINE_CMD_FLAG_NO_INPUT},
  222. {CAPI_CMD_LIST_OPTIONS,
  223. "list_options",
  224. "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
  225. "32=private key info)",
  226. ENGINE_CMD_FLAG_NUMERIC},
  227. {CAPI_CMD_LOOKUP_METHOD,
  228. "lookup_method",
  229. "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
  230. ENGINE_CMD_FLAG_NUMERIC},
  231. {CAPI_CMD_STORE_NAME,
  232. "store_name",
  233. "certificate store name, default \"MY\"",
  234. ENGINE_CMD_FLAG_STRING},
  235. {CAPI_CMD_STORE_FLAGS,
  236. "store_flags",
  237. "Certificate store flags: 1 = system store",
  238. ENGINE_CMD_FLAG_NUMERIC},
  239. {0, NULL, NULL, 0}
  240. };
  241. static int capi_idx = -1;
  242. static int rsa_capi_idx = -1;
  243. static int dsa_capi_idx = -1;
  244. static int cert_capi_idx = -1;
  245. static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
  246. {
  247. int ret = 1;
  248. CAPI_CTX *ctx;
  249. BIO *out;
  250. LPSTR tmpstr;
  251. if (capi_idx == -1) {
  252. CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
  253. return 0;
  254. }
  255. ctx = ENGINE_get_ex_data(e, capi_idx);
  256. out = BIO_new_fp(stdout, BIO_NOCLOSE);
  257. if (out == NULL) {
  258. CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_FILE_OPEN_ERROR);
  259. return 0;
  260. }
  261. switch (cmd) {
  262. case CAPI_CMD_LIST_CSPS:
  263. ret = capi_list_providers(ctx, out);
  264. break;
  265. case CAPI_CMD_LIST_CERTS:
  266. ret = capi_list_certs(ctx, out, NULL);
  267. break;
  268. case CAPI_CMD_LOOKUP_CERT:
  269. ret = capi_list_certs(ctx, out, p);
  270. break;
  271. case CAPI_CMD_LIST_CONTAINERS:
  272. ret = capi_list_containers(ctx, out);
  273. break;
  274. case CAPI_CMD_STORE_NAME:
  275. tmpstr = OPENSSL_strdup(p);
  276. if (tmpstr != NULL) {
  277. OPENSSL_free(ctx->storename);
  278. ctx->storename = tmpstr;
  279. CAPI_trace(ctx, "Setting store name to %s\n", p);
  280. } else {
  281. CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
  282. ret = 0;
  283. }
  284. break;
  285. case CAPI_CMD_STORE_FLAGS:
  286. if (i & 1) {
  287. ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
  288. ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
  289. } else {
  290. ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
  291. ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
  292. }
  293. CAPI_trace(ctx, "Setting flags to %d\n", i);
  294. break;
  295. case CAPI_CMD_DEBUG_LEVEL:
  296. ctx->debug_level = (int)i;
  297. CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
  298. break;
  299. case CAPI_CMD_DEBUG_FILE:
  300. tmpstr = OPENSSL_strdup(p);
  301. if (tmpstr != NULL) {
  302. ctx->debug_file = tmpstr;
  303. CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
  304. } else {
  305. CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
  306. ret = 0;
  307. }
  308. break;
  309. case CAPI_CMD_KEYTYPE:
  310. ctx->keytype = i;
  311. CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
  312. break;
  313. case CAPI_CMD_SET_CSP_IDX:
  314. ret = capi_ctx_set_provname_idx(ctx, i);
  315. break;
  316. case CAPI_CMD_LIST_OPTIONS:
  317. ctx->dump_flags = i;
  318. break;
  319. case CAPI_CMD_LOOKUP_METHOD:
  320. if (i < 1 || i > 3) {
  321. CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
  322. BIO_free(out);
  323. return 0;
  324. }
  325. ctx->lookup_method = i;
  326. break;
  327. case CAPI_CMD_SET_CSP_NAME:
  328. ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
  329. break;
  330. case CAPI_CMD_SET_CSP_TYPE:
  331. ctx->csptype = i;
  332. break;
  333. default:
  334. CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
  335. ret = 0;
  336. }
  337. BIO_free(out);
  338. return ret;
  339. }
  340. static RSA_METHOD *capi_rsa_method = NULL;
  341. # ifndef OPENSSL_NO_DSA
  342. static DSA_METHOD *capi_dsa_method = NULL;
  343. # endif
  344. static int use_aes_csp = 0;
  345. static int capi_init(ENGINE *e)
  346. {
  347. CAPI_CTX *ctx;
  348. const RSA_METHOD *ossl_rsa_meth;
  349. # ifndef OPENSSL_NO_DSA
  350. const DSA_METHOD *ossl_dsa_meth;
  351. # endif
  352. HCRYPTPROV hprov;
  353. if (capi_idx < 0) {
  354. capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
  355. if (capi_idx < 0)
  356. goto memerr;
  357. cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
  358. /* Setup RSA_METHOD */
  359. rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
  360. ossl_rsa_meth = RSA_PKCS1_OpenSSL();
  361. if ( !RSA_meth_set_pub_enc(capi_rsa_method,
  362. RSA_meth_get_pub_enc(ossl_rsa_meth))
  363. || !RSA_meth_set_pub_dec(capi_rsa_method,
  364. RSA_meth_get_pub_dec(ossl_rsa_meth))
  365. || !RSA_meth_set_priv_enc(capi_rsa_method, capi_rsa_priv_enc)
  366. || !RSA_meth_set_priv_dec(capi_rsa_method, capi_rsa_priv_dec)
  367. || !RSA_meth_set_mod_exp(capi_rsa_method,
  368. RSA_meth_get_mod_exp(ossl_rsa_meth))
  369. || !RSA_meth_set_bn_mod_exp(capi_rsa_method,
  370. RSA_meth_get_bn_mod_exp(ossl_rsa_meth))
  371. || !RSA_meth_set_finish(capi_rsa_method, capi_rsa_free)
  372. || !RSA_meth_set_sign(capi_rsa_method, capi_rsa_sign)) {
  373. goto memerr;
  374. }
  375. # ifndef OPENSSL_NO_DSA
  376. /* Setup DSA Method */
  377. dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
  378. ossl_dsa_meth = DSA_OpenSSL();
  379. if ( !DSA_meth_set_sign(capi_dsa_method, capi_dsa_do_sign)
  380. || !DSA_meth_set_verify(capi_dsa_method,
  381. DSA_meth_get_verify(ossl_dsa_meth))
  382. || !DSA_meth_set_finish(capi_dsa_method, capi_dsa_free)
  383. || !DSA_meth_set_mod_exp(capi_dsa_method,
  384. DSA_meth_get_mod_exp(ossl_dsa_meth))
  385. || !DSA_meth_set_bn_mod_exp(capi_dsa_method,
  386. DSA_meth_get_bn_mod_exp(ossl_dsa_meth))) {
  387. goto memerr;
  388. }
  389. # endif
  390. }
  391. ctx = capi_ctx_new();
  392. if (ctx == NULL)
  393. goto memerr;
  394. ENGINE_set_ex_data(e, capi_idx, ctx);
  395. # ifdef OPENSSL_CAPIENG_DIALOG
  396. {
  397. HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
  398. HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
  399. if (cryptui)
  400. ctx->certselectdlg =
  401. (CERTDLG) GetProcAddress(cryptui,
  402. "CryptUIDlgSelectCertificateFromStore");
  403. if (kernel)
  404. ctx->getconswindow =
  405. (GETCONSWIN) GetProcAddress(kernel, "GetConsoleWindow");
  406. if (cryptui && !OPENSSL_isservice())
  407. ctx->client_cert_select = cert_select_dialog;
  408. }
  409. # endif
  410. /* See if we support AES CSP */
  411. if (CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_AES,
  412. CRYPT_VERIFYCONTEXT)) {
  413. use_aes_csp = 1;
  414. CryptReleaseContext(hprov, 0);
  415. }
  416. return 1;
  417. memerr:
  418. CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
  419. return 0;
  420. return 1;
  421. }
  422. static int capi_destroy(ENGINE *e)
  423. {
  424. RSA_meth_free(capi_rsa_method);
  425. capi_rsa_method = NULL;
  426. # ifndef OPENSSL_NO_DSA
  427. DSA_meth_free(capi_dsa_method);
  428. capi_dsa_method = NULL;
  429. # endif
  430. ERR_unload_CAPI_strings();
  431. return 1;
  432. }
  433. static int capi_finish(ENGINE *e)
  434. {
  435. CAPI_CTX *ctx;
  436. ctx = ENGINE_get_ex_data(e, capi_idx);
  437. capi_ctx_free(ctx);
  438. ENGINE_set_ex_data(e, capi_idx, NULL);
  439. return 1;
  440. }
  441. /*
  442. * CryptoAPI key application data. This contains a handle to the private key
  443. * container (for sign operations) and a handle to the key (for decrypt
  444. * operations).
  445. */
  446. struct CAPI_KEY_st {
  447. /* Associated certificate context (if any) */
  448. PCCERT_CONTEXT pcert;
  449. HCRYPTPROV hprov;
  450. HCRYPTKEY key;
  451. DWORD keyspec;
  452. };
  453. static int bind_capi(ENGINE *e)
  454. {
  455. capi_rsa_method = RSA_meth_new("CryptoAPI RSA method", 0);
  456. if (capi_rsa_method == NULL)
  457. return 0;
  458. # ifndef OPENSSL_NO_DSA
  459. capi_dsa_method = DSA_meth_new("CryptoAPI DSA method", 0);
  460. if (capi_dsa_method == NULL)
  461. goto memerr;
  462. # endif
  463. if (!ENGINE_set_id(e, engine_capi_id)
  464. || !ENGINE_set_name(e, engine_capi_name)
  465. || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
  466. || !ENGINE_set_init_function(e, capi_init)
  467. || !ENGINE_set_finish_function(e, capi_finish)
  468. || !ENGINE_set_destroy_function(e, capi_destroy)
  469. || !ENGINE_set_RSA(e, capi_rsa_method)
  470. # ifndef OPENSSL_NO_DSA
  471. || !ENGINE_set_DSA(e, capi_dsa_method)
  472. # endif
  473. || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
  474. || !ENGINE_set_load_ssl_client_cert_function(e,
  475. capi_load_ssl_client_cert)
  476. || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
  477. || !ENGINE_set_ctrl_function(e, capi_ctrl))
  478. goto memerr;
  479. ERR_load_CAPI_strings();
  480. return 1;
  481. memerr:
  482. RSA_meth_free(capi_rsa_method);
  483. capi_rsa_method = NULL;
  484. # ifndef OPENSSL_NO_DSA
  485. DSA_meth_free(capi_dsa_method);
  486. capi_dsa_method = NULL;
  487. # endif
  488. return 0;
  489. }
  490. # ifndef OPENSSL_NO_DYNAMIC_ENGINE
  491. static int bind_helper(ENGINE *e, const char *id)
  492. {
  493. if (id && (strcmp(id, engine_capi_id) != 0))
  494. return 0;
  495. if (!bind_capi(e))
  496. return 0;
  497. return 1;
  498. }
  499. IMPLEMENT_DYNAMIC_CHECK_FN()
  500. IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
  501. # else
  502. static ENGINE *engine_capi(void)
  503. {
  504. ENGINE *ret = ENGINE_new();
  505. if (ret == NULL)
  506. return NULL;
  507. if (!bind_capi(ret)) {
  508. ENGINE_free(ret);
  509. return NULL;
  510. }
  511. return ret;
  512. }
  513. void engine_load_capi_int(void)
  514. {
  515. /* Copied from eng_[openssl|dyn].c */
  516. ENGINE *toadd = engine_capi();
  517. if (!toadd)
  518. return;
  519. ENGINE_add(toadd);
  520. ENGINE_free(toadd);
  521. ERR_clear_error();
  522. }
  523. # endif
  524. static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
  525. {
  526. int i;
  527. /*
  528. * Reverse buffer in place: since this is a keyblob structure that will
  529. * be freed up after conversion anyway it doesn't matter if we change
  530. * it.
  531. */
  532. for (i = 0; i < binlen / 2; i++) {
  533. unsigned char c;
  534. c = bin[i];
  535. bin[i] = bin[binlen - i - 1];
  536. bin[binlen - i - 1] = c;
  537. }
  538. if (!BN_bin2bn(bin, binlen, bn))
  539. return 0;
  540. return 1;
  541. }
  542. /* Given a CAPI_KEY get an EVP_PKEY structure */
  543. static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
  544. {
  545. unsigned char *pubkey = NULL;
  546. DWORD len;
  547. BLOBHEADER *bh;
  548. RSA *rkey = NULL;
  549. DSA *dkey = NULL;
  550. EVP_PKEY *ret = NULL;
  551. if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
  552. CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
  553. capi_addlasterror();
  554. return NULL;
  555. }
  556. pubkey = OPENSSL_malloc(len);
  557. if (pubkey == NULL)
  558. goto memerr;
  559. if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
  560. CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
  561. capi_addlasterror();
  562. goto err;
  563. }
  564. bh = (BLOBHEADER *) pubkey;
  565. if (bh->bType != PUBLICKEYBLOB) {
  566. CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
  567. goto err;
  568. }
  569. if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
  570. RSAPUBKEY *rp;
  571. DWORD rsa_modlen;
  572. BIGNUM *e = NULL, *n = NULL;
  573. unsigned char *rsa_modulus;
  574. rp = (RSAPUBKEY *) (bh + 1);
  575. if (rp->magic != 0x31415352) {
  576. char magstr[10];
  577. BIO_snprintf(magstr, 10, "%lx", rp->magic);
  578. CAPIerr(CAPI_F_CAPI_GET_PKEY,
  579. CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
  580. ERR_add_error_data(2, "magic=0x", magstr);
  581. goto err;
  582. }
  583. rsa_modulus = (unsigned char *)(rp + 1);
  584. rkey = RSA_new_method(eng);
  585. if (!rkey)
  586. goto memerr;
  587. e = BN_new();
  588. n = BN_new();
  589. if (e == NULL || n == NULL) {
  590. BN_free(e);
  591. BN_free(n);
  592. goto memerr;
  593. }
  594. RSA_set0_key(rkey, n, e, NULL);
  595. if (!BN_set_word(e, rp->pubexp))
  596. goto memerr;
  597. rsa_modlen = rp->bitlen / 8;
  598. if (!lend_tobn(n, rsa_modulus, rsa_modlen))
  599. goto memerr;
  600. RSA_set_ex_data(rkey, rsa_capi_idx, key);
  601. if ((ret = EVP_PKEY_new()) == NULL)
  602. goto memerr;
  603. EVP_PKEY_assign_RSA(ret, rkey);
  604. rkey = NULL;
  605. # ifndef OPENSSL_NO_DSA
  606. } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
  607. DSSPUBKEY *dp;
  608. DWORD dsa_plen;
  609. unsigned char *btmp;
  610. BIGNUM *p, *q, *g, *pub_key;
  611. dp = (DSSPUBKEY *) (bh + 1);
  612. if (dp->magic != 0x31535344) {
  613. char magstr[10];
  614. BIO_snprintf(magstr, 10, "%lx", dp->magic);
  615. CAPIerr(CAPI_F_CAPI_GET_PKEY,
  616. CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
  617. ERR_add_error_data(2, "magic=0x", magstr);
  618. goto err;
  619. }
  620. dsa_plen = dp->bitlen / 8;
  621. btmp = (unsigned char *)(dp + 1);
  622. dkey = DSA_new_method(eng);
  623. if (!dkey)
  624. goto memerr;
  625. p = BN_new();
  626. q = BN_new();
  627. g = BN_new();
  628. pub_key = BN_new();
  629. if (p == NULL || q == NULL || g == NULL || pub_key == NULL) {
  630. BN_free(p);
  631. BN_free(q);
  632. BN_free(g);
  633. BN_free(pub_key);
  634. goto memerr;
  635. }
  636. DSA_set0_pqg(dkey, p, q, g);
  637. DSA_set0_key(dkey, pub_key, NULL);
  638. if (!lend_tobn(p, btmp, dsa_plen))
  639. goto memerr;
  640. btmp += dsa_plen;
  641. if (!lend_tobn(q, btmp, 20))
  642. goto memerr;
  643. btmp += 20;
  644. if (!lend_tobn(g, btmp, dsa_plen))
  645. goto memerr;
  646. btmp += dsa_plen;
  647. if (!lend_tobn(pub_key, btmp, dsa_plen))
  648. goto memerr;
  649. btmp += dsa_plen;
  650. DSA_set_ex_data(dkey, dsa_capi_idx, key);
  651. if ((ret = EVP_PKEY_new()) == NULL)
  652. goto memerr;
  653. EVP_PKEY_assign_DSA(ret, dkey);
  654. dkey = NULL;
  655. # endif
  656. } else {
  657. char algstr[10];
  658. BIO_snprintf(algstr, 10, "%ux", bh->aiKeyAlg);
  659. CAPIerr(CAPI_F_CAPI_GET_PKEY,
  660. CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
  661. ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
  662. goto err;
  663. }
  664. err:
  665. OPENSSL_free(pubkey);
  666. if (!ret) {
  667. RSA_free(rkey);
  668. # ifndef OPENSSL_NO_DSA
  669. DSA_free(dkey);
  670. # endif
  671. }
  672. return ret;
  673. memerr:
  674. CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
  675. goto err;
  676. }
  677. static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
  678. UI_METHOD *ui_method, void *callback_data)
  679. {
  680. CAPI_CTX *ctx;
  681. CAPI_KEY *key;
  682. EVP_PKEY *ret;
  683. ctx = ENGINE_get_ex_data(eng, capi_idx);
  684. if (!ctx) {
  685. CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
  686. return NULL;
  687. }
  688. key = capi_find_key(ctx, key_id);
  689. if (!key)
  690. return NULL;
  691. ret = capi_get_pkey(eng, key);
  692. if (!ret)
  693. capi_free_key(key);
  694. return ret;
  695. }
  696. /* CryptoAPI RSA operations */
  697. int capi_rsa_priv_enc(int flen, const unsigned char *from,
  698. unsigned char *to, RSA *rsa, int padding)
  699. {
  700. CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
  701. return -1;
  702. }
  703. int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
  704. unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
  705. {
  706. ALG_ID alg;
  707. HCRYPTHASH hash;
  708. DWORD slen;
  709. unsigned int i;
  710. int ret = -1;
  711. CAPI_KEY *capi_key;
  712. CAPI_CTX *ctx;
  713. ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
  714. CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
  715. capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
  716. if (!capi_key) {
  717. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
  718. return -1;
  719. }
  720. /* Convert the signature type to a CryptoAPI algorithm ID */
  721. switch (dtype) {
  722. case NID_sha256:
  723. alg = CALG_SHA_256;
  724. break;
  725. case NID_sha384:
  726. alg = CALG_SHA_384;
  727. break;
  728. case NID_sha512:
  729. alg = CALG_SHA_512;
  730. break;
  731. case NID_sha1:
  732. alg = CALG_SHA1;
  733. break;
  734. case NID_md5:
  735. alg = CALG_MD5;
  736. break;
  737. case NID_md5_sha1:
  738. alg = CALG_SSL3_SHAMD5;
  739. break;
  740. default:
  741. {
  742. char algstr[10];
  743. BIO_snprintf(algstr, 10, "%x", dtype);
  744. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
  745. ERR_add_error_data(2, "NID=0x", algstr);
  746. return -1;
  747. }
  748. }
  749. /* Create the hash object */
  750. if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
  751. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
  752. capi_addlasterror();
  753. return -1;
  754. }
  755. /* Set the hash value to the value passed */
  756. if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
  757. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
  758. capi_addlasterror();
  759. goto err;
  760. }
  761. /* Finally sign it */
  762. slen = RSA_size(rsa);
  763. if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
  764. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
  765. capi_addlasterror();
  766. goto err;
  767. } else {
  768. ret = 1;
  769. /* Inplace byte reversal of signature */
  770. for (i = 0; i < slen / 2; i++) {
  771. unsigned char c;
  772. c = sigret[i];
  773. sigret[i] = sigret[slen - i - 1];
  774. sigret[slen - i - 1] = c;
  775. }
  776. *siglen = slen;
  777. }
  778. /* Now cleanup */
  779. err:
  780. CryptDestroyHash(hash);
  781. return ret;
  782. }
  783. int capi_rsa_priv_dec(int flen, const unsigned char *from,
  784. unsigned char *to, RSA *rsa, int padding)
  785. {
  786. int i;
  787. unsigned char *tmpbuf;
  788. CAPI_KEY *capi_key;
  789. CAPI_CTX *ctx;
  790. DWORD dlen;
  791. if (flen <= 0)
  792. return flen;
  793. ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
  794. CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
  795. capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
  796. if (!capi_key) {
  797. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
  798. return -1;
  799. }
  800. if (padding != RSA_PKCS1_PADDING) {
  801. char errstr[10];
  802. BIO_snprintf(errstr, 10, "%d", padding);
  803. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
  804. ERR_add_error_data(2, "padding=", errstr);
  805. return -1;
  806. }
  807. /* Create temp reverse order version of input */
  808. if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
  809. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
  810. return -1;
  811. }
  812. for (i = 0; i < flen; i++)
  813. tmpbuf[flen - i - 1] = from[i];
  814. /* Finally decrypt it */
  815. dlen = flen;
  816. if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &dlen)) {
  817. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
  818. capi_addlasterror();
  819. OPENSSL_free(tmpbuf);
  820. return -1;
  821. } else {
  822. memcpy(to, tmpbuf, (flen = (int)dlen));
  823. }
  824. OPENSSL_free(tmpbuf);
  825. return flen;
  826. }
  827. static int capi_rsa_free(RSA *rsa)
  828. {
  829. CAPI_KEY *capi_key;
  830. capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
  831. capi_free_key(capi_key);
  832. RSA_set_ex_data(rsa, rsa_capi_idx, 0);
  833. return 1;
  834. }
  835. # ifndef OPENSSL_NO_DSA
  836. /* CryptoAPI DSA operations */
  837. static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
  838. DSA *dsa)
  839. {
  840. HCRYPTHASH hash;
  841. DWORD slen;
  842. DSA_SIG *ret = NULL;
  843. CAPI_KEY *capi_key;
  844. CAPI_CTX *ctx;
  845. unsigned char csigbuf[40];
  846. ctx = ENGINE_get_ex_data(DSA_get0_engine(dsa), capi_idx);
  847. CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
  848. capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
  849. if (!capi_key) {
  850. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
  851. return NULL;
  852. }
  853. if (dlen != 20) {
  854. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
  855. return NULL;
  856. }
  857. /* Create the hash object */
  858. if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
  859. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
  860. capi_addlasterror();
  861. return NULL;
  862. }
  863. /* Set the hash value to the value passed */
  864. if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
  865. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
  866. capi_addlasterror();
  867. goto err;
  868. }
  869. /* Finally sign it */
  870. slen = sizeof(csigbuf);
  871. if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
  872. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
  873. capi_addlasterror();
  874. goto err;
  875. } else {
  876. BIGNUM *r = BN_new(), *s = BN_new();
  877. if (r == NULL || s == NULL
  878. || !lend_tobn(r, csigbuf, 20)
  879. || !lend_tobn(s, csigbuf + 20, 20)
  880. || (ret = DSA_SIG_new()) == NULL) {
  881. BN_free(r); /* BN_free checks for BIGNUM * being NULL */
  882. BN_free(s);
  883. goto err;
  884. }
  885. DSA_SIG_set0(ret, r, s);
  886. }
  887. /* Now cleanup */
  888. err:
  889. OPENSSL_cleanse(csigbuf, 40);
  890. CryptDestroyHash(hash);
  891. return ret;
  892. }
  893. static int capi_dsa_free(DSA *dsa)
  894. {
  895. CAPI_KEY *capi_key;
  896. capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
  897. capi_free_key(capi_key);
  898. DSA_set_ex_data(dsa, dsa_capi_idx, 0);
  899. return 1;
  900. }
  901. # endif
  902. static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
  903. va_list argptr)
  904. {
  905. BIO *out;
  906. if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
  907. return;
  908. out = BIO_new_file(ctx->debug_file, "a+");
  909. if (out == NULL) {
  910. CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
  911. return;
  912. }
  913. BIO_vprintf(out, format, argptr);
  914. BIO_free(out);
  915. }
  916. static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
  917. {
  918. va_list args;
  919. va_start(args, format);
  920. capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
  921. va_end(args);
  922. }
  923. static void capi_addlasterror(void)
  924. {
  925. capi_adderror(GetLastError());
  926. }
  927. static void capi_adderror(DWORD err)
  928. {
  929. char errstr[10];
  930. BIO_snprintf(errstr, 10, "%lX", err);
  931. ERR_add_error_data(2, "Error code= 0x", errstr);
  932. }
  933. static char *wide_to_asc(LPCWSTR wstr)
  934. {
  935. char *str;
  936. int len_0, sz;
  937. if (!wstr)
  938. return NULL;
  939. len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
  940. sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
  941. if (!sz) {
  942. CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
  943. return NULL;
  944. }
  945. str = OPENSSL_malloc(sz);
  946. if (str == NULL) {
  947. CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
  948. return NULL;
  949. }
  950. if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
  951. OPENSSL_free(str);
  952. CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
  953. return NULL;
  954. }
  955. return str;
  956. }
  957. static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
  958. DWORD idx)
  959. {
  960. DWORD len, err;
  961. LPTSTR name;
  962. CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
  963. if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
  964. err = GetLastError();
  965. if (err == ERROR_NO_MORE_ITEMS)
  966. return 2;
  967. CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
  968. capi_adderror(err);
  969. return 0;
  970. }
  971. name = OPENSSL_malloc(len);
  972. if (name == NULL) {
  973. CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
  974. return 0;
  975. }
  976. if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
  977. err = GetLastError();
  978. OPENSSL_free(name);
  979. if (err == ERROR_NO_MORE_ITEMS)
  980. return 2;
  981. CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
  982. capi_adderror(err);
  983. return 0;
  984. }
  985. if (sizeof(TCHAR) != sizeof(char)) {
  986. *pname = wide_to_asc((WCHAR *)name);
  987. OPENSSL_free(name);
  988. if (*pname == NULL)
  989. return 0;
  990. } else {
  991. *pname = (char *)name;
  992. }
  993. CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
  994. *ptype);
  995. return 1;
  996. }
  997. static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
  998. {
  999. DWORD idx, ptype;
  1000. int ret;
  1001. LPSTR provname = NULL;
  1002. CAPI_trace(ctx, "capi_list_providers\n");
  1003. BIO_printf(out, "Available CSPs:\n");
  1004. for (idx = 0;; idx++) {
  1005. ret = capi_get_provname(ctx, &provname, &ptype, idx);
  1006. if (ret == 2)
  1007. break;
  1008. if (ret == 0)
  1009. break;
  1010. BIO_printf(out, "%lu. %s, type %lu\n", idx, provname, ptype);
  1011. OPENSSL_free(provname);
  1012. }
  1013. return 1;
  1014. }
  1015. static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
  1016. {
  1017. int ret = 1;
  1018. HCRYPTPROV hprov;
  1019. DWORD err, idx, flags, buflen = 0, clen;
  1020. LPSTR cname;
  1021. LPTSTR cspname = NULL;
  1022. CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
  1023. ctx->csptype);
  1024. if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
  1025. if ((clen = MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
  1026. NULL, 0))) {
  1027. cspname = alloca(clen * sizeof(WCHAR));
  1028. MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
  1029. clen);
  1030. }
  1031. if (!cspname) {
  1032. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
  1033. capi_addlasterror();
  1034. return 0;
  1035. }
  1036. } else {
  1037. cspname = (TCHAR *)ctx->cspname;
  1038. }
  1039. if (!CryptAcquireContext(&hprov, NULL, cspname, ctx->csptype,
  1040. CRYPT_VERIFYCONTEXT)) {
  1041. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
  1042. CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
  1043. capi_addlasterror();
  1044. return 0;
  1045. }
  1046. if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen,
  1047. CRYPT_FIRST)) {
  1048. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
  1049. capi_addlasterror();
  1050. CryptReleaseContext(hprov, 0);
  1051. return 0;
  1052. }
  1053. CAPI_trace(ctx, "Got max container len %d\n", buflen);
  1054. if (buflen == 0)
  1055. buflen = 1024;
  1056. cname = OPENSSL_malloc(buflen);
  1057. if (cname == NULL) {
  1058. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
  1059. goto err;
  1060. }
  1061. for (idx = 0;; idx++) {
  1062. clen = buflen;
  1063. cname[0] = 0;
  1064. if (idx == 0)
  1065. flags = CRYPT_FIRST;
  1066. else
  1067. flags = 0;
  1068. if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, (BYTE *)cname,
  1069. &clen, flags)) {
  1070. err = GetLastError();
  1071. if (err == ERROR_NO_MORE_ITEMS)
  1072. goto done;
  1073. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
  1074. capi_adderror(err);
  1075. goto err;
  1076. }
  1077. CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
  1078. cname, clen, idx, flags);
  1079. if (!cname[0] && (clen == buflen)) {
  1080. CAPI_trace(ctx, "Enumerate bug: using workaround\n");
  1081. goto done;
  1082. }
  1083. BIO_printf(out, "%lu. %s\n", idx, cname);
  1084. }
  1085. err:
  1086. ret = 0;
  1087. done:
  1088. OPENSSL_free(cname);
  1089. CryptReleaseContext(hprov, 0);
  1090. return ret;
  1091. }
  1092. static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx,
  1093. PCCERT_CONTEXT cert)
  1094. {
  1095. DWORD len;
  1096. CRYPT_KEY_PROV_INFO *pinfo;
  1097. if (!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
  1098. NULL, &len))
  1099. return NULL;
  1100. pinfo = OPENSSL_malloc(len);
  1101. if (pinfo == NULL) {
  1102. CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
  1103. return NULL;
  1104. }
  1105. if (!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
  1106. pinfo, &len)) {
  1107. CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
  1108. CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
  1109. capi_addlasterror();
  1110. OPENSSL_free(pinfo);
  1111. return NULL;
  1112. }
  1113. return pinfo;
  1114. }
  1115. static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
  1116. CRYPT_KEY_PROV_INFO * pinfo)
  1117. {
  1118. char *provname = NULL, *contname = NULL;
  1119. if (!pinfo) {
  1120. BIO_printf(out, " No Private Key\n");
  1121. return;
  1122. }
  1123. provname = wide_to_asc(pinfo->pwszProvName);
  1124. contname = wide_to_asc(pinfo->pwszContainerName);
  1125. if (!provname || !contname)
  1126. goto err;
  1127. BIO_printf(out, " Private Key Info:\n");
  1128. BIO_printf(out, " Provider Name: %s, Provider Type %lu\n", provname,
  1129. pinfo->dwProvType);
  1130. BIO_printf(out, " Container Name: %s, Key Type %lu\n", contname,
  1131. pinfo->dwKeySpec);
  1132. err:
  1133. OPENSSL_free(provname);
  1134. OPENSSL_free(contname);
  1135. }
  1136. static char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
  1137. {
  1138. LPWSTR wfname;
  1139. DWORD dlen;
  1140. CAPI_trace(ctx, "capi_cert_get_fname\n");
  1141. if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
  1142. NULL, &dlen))
  1143. return NULL;
  1144. wfname = OPENSSL_malloc(dlen);
  1145. if (wfname == NULL)
  1146. return NULL;
  1147. if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
  1148. wfname, &dlen)) {
  1149. char *fname = wide_to_asc(wfname);
  1150. OPENSSL_free(wfname);
  1151. return fname;
  1152. }
  1153. CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
  1154. capi_addlasterror();
  1155. OPENSSL_free(wfname);
  1156. return NULL;
  1157. }
  1158. static void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
  1159. {
  1160. X509 *x;
  1161. const unsigned char *p;
  1162. unsigned long flags = ctx->dump_flags;
  1163. if (flags & CAPI_DMP_FNAME) {
  1164. char *fname;
  1165. fname = capi_cert_get_fname(ctx, cert);
  1166. if (fname) {
  1167. BIO_printf(out, " Friendly Name \"%s\"\n", fname);
  1168. OPENSSL_free(fname);
  1169. } else {
  1170. BIO_printf(out, " <No Friendly Name>\n");
  1171. }
  1172. }
  1173. p = cert->pbCertEncoded;
  1174. x = d2i_X509(NULL, &p, cert->cbCertEncoded);
  1175. if (!x)
  1176. BIO_printf(out, " <Can't parse certificate>\n");
  1177. if (flags & CAPI_DMP_SUMMARY) {
  1178. BIO_printf(out, " Subject: ");
  1179. X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
  1180. BIO_printf(out, "\n Issuer: ");
  1181. X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
  1182. BIO_printf(out, "\n");
  1183. }
  1184. if (flags & CAPI_DMP_FULL)
  1185. X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
  1186. if (flags & CAPI_DMP_PKEYINFO) {
  1187. CRYPT_KEY_PROV_INFO *pinfo;
  1188. pinfo = capi_get_prov_info(ctx, cert);
  1189. capi_dump_prov_info(ctx, out, pinfo);
  1190. OPENSSL_free(pinfo);
  1191. }
  1192. if (flags & CAPI_DMP_PEM)
  1193. PEM_write_bio_X509(out, x);
  1194. X509_free(x);
  1195. }
  1196. static HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
  1197. {
  1198. HCERTSTORE hstore;
  1199. if (!storename)
  1200. storename = ctx->storename;
  1201. if (!storename)
  1202. storename = "MY";
  1203. CAPI_trace(ctx, "Opening certificate store %s\n", storename);
  1204. hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
  1205. ctx->store_flags, storename);
  1206. if (!hstore) {
  1207. CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
  1208. capi_addlasterror();
  1209. }
  1210. return hstore;
  1211. }
  1212. int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
  1213. {
  1214. char *storename;
  1215. int idx;
  1216. int ret = 1;
  1217. HCERTSTORE hstore;
  1218. PCCERT_CONTEXT cert = NULL;
  1219. storename = ctx->storename;
  1220. if (!storename)
  1221. storename = "MY";
  1222. CAPI_trace(ctx, "Listing certs for store %s\n", storename);
  1223. hstore = capi_open_store(ctx, storename);
  1224. if (!hstore)
  1225. return 0;
  1226. if (id) {
  1227. cert = capi_find_cert(ctx, id, hstore);
  1228. if (!cert) {
  1229. ret = 0;
  1230. goto err;
  1231. }
  1232. capi_dump_cert(ctx, out, cert);
  1233. CertFreeCertificateContext(cert);
  1234. } else {
  1235. for (idx = 0;; idx++) {
  1236. cert = CertEnumCertificatesInStore(hstore, cert);
  1237. if (!cert)
  1238. break;
  1239. BIO_printf(out, "Certificate %d\n", idx);
  1240. capi_dump_cert(ctx, out, cert);
  1241. }
  1242. }
  1243. err:
  1244. CertCloseStore(hstore, 0);
  1245. return ret;
  1246. }
  1247. static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
  1248. HCERTSTORE hstore)
  1249. {
  1250. PCCERT_CONTEXT cert = NULL;
  1251. char *fname = NULL;
  1252. int match;
  1253. switch (ctx->lookup_method) {
  1254. case CAPI_LU_SUBSTR:
  1255. return CertFindCertificateInStore(hstore, X509_ASN_ENCODING, 0,
  1256. CERT_FIND_SUBJECT_STR_A, id, NULL);
  1257. case CAPI_LU_FNAME:
  1258. for (;;) {
  1259. cert = CertEnumCertificatesInStore(hstore, cert);
  1260. if (!cert)
  1261. return NULL;
  1262. fname = capi_cert_get_fname(ctx, cert);
  1263. if (fname) {
  1264. if (strcmp(fname, id))
  1265. match = 0;
  1266. else
  1267. match = 1;
  1268. OPENSSL_free(fname);
  1269. if (match)
  1270. return cert;
  1271. }
  1272. }
  1273. default:
  1274. return NULL;
  1275. }
  1276. }
  1277. static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
  1278. TCHAR *provname, DWORD ptype, DWORD keyspec)
  1279. {
  1280. DWORD dwFlags = 0;
  1281. CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
  1282. if (key == NULL)
  1283. return NULL;
  1284. /* If PROV_RSA_AES supported use it instead */
  1285. if (ptype == PROV_RSA_FULL && use_aes_csp) {
  1286. provname = NULL;
  1287. ptype = PROV_RSA_AES;
  1288. CAPI_trace(ctx, "capi_get_key, contname=%s, RSA_AES_CSP\n", contname);
  1289. } else if (sizeof(TCHAR) == sizeof(char)) {
  1290. CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
  1291. contname, provname, ptype);
  1292. } else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
  1293. /* above 'if' is optimization to minimize malloc-ations */
  1294. char *_contname = wide_to_asc((WCHAR *)contname);
  1295. char *_provname = wide_to_asc((WCHAR *)provname);
  1296. CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
  1297. _contname, _provname, ptype);
  1298. OPENSSL_free(_provname);
  1299. OPENSSL_free(_contname);
  1300. }
  1301. if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
  1302. dwFlags = CRYPT_MACHINE_KEYSET;
  1303. if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
  1304. CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
  1305. capi_addlasterror();
  1306. goto err;
  1307. }
  1308. if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
  1309. CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
  1310. capi_addlasterror();
  1311. CryptReleaseContext(key->hprov, 0);
  1312. goto err;
  1313. }
  1314. key->keyspec = keyspec;
  1315. key->pcert = NULL;
  1316. return key;
  1317. err:
  1318. OPENSSL_free(key);
  1319. return NULL;
  1320. }
  1321. static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
  1322. {
  1323. CAPI_KEY *key = NULL;
  1324. CRYPT_KEY_PROV_INFO *pinfo = NULL;
  1325. char *provname = NULL, *contname = NULL;
  1326. pinfo = capi_get_prov_info(ctx, cert);
  1327. if (!pinfo)
  1328. goto err;
  1329. if (sizeof(TCHAR) != sizeof(char))
  1330. key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
  1331. (TCHAR *)pinfo->pwszProvName,
  1332. pinfo->dwProvType, pinfo->dwKeySpec);
  1333. else {
  1334. provname = wide_to_asc(pinfo->pwszProvName);
  1335. contname = wide_to_asc(pinfo->pwszContainerName);
  1336. if (!provname || !contname)
  1337. goto err;
  1338. key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
  1339. pinfo->dwProvType, pinfo->dwKeySpec);
  1340. }
  1341. err:
  1342. OPENSSL_free(pinfo);
  1343. OPENSSL_free(provname);
  1344. OPENSSL_free(contname);
  1345. return key;
  1346. }
  1347. CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
  1348. {
  1349. PCCERT_CONTEXT cert;
  1350. HCERTSTORE hstore;
  1351. CAPI_KEY *key = NULL;
  1352. switch (ctx->lookup_method) {
  1353. case CAPI_LU_SUBSTR:
  1354. case CAPI_LU_FNAME:
  1355. hstore = capi_open_store(ctx, NULL);
  1356. if (!hstore)
  1357. return NULL;
  1358. cert = capi_find_cert(ctx, id, hstore);
  1359. if (cert) {
  1360. key = capi_get_cert_key(ctx, cert);
  1361. CertFreeCertificateContext(cert);
  1362. }
  1363. CertCloseStore(hstore, 0);
  1364. break;
  1365. case CAPI_LU_CONTNAME:
  1366. if (sizeof(TCHAR) != sizeof(char)) {
  1367. WCHAR *contname, *provname;
  1368. DWORD len;
  1369. if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
  1370. (contname = alloca(len * sizeof(WCHAR)),
  1371. MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
  1372. (len = MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
  1373. NULL, 0)) &&
  1374. (provname = alloca(len * sizeof(WCHAR)),
  1375. MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
  1376. provname, len)))
  1377. key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
  1378. ctx->csptype, ctx->keytype);
  1379. } else {
  1380. key = capi_get_key(ctx, (TCHAR *)id, (TCHAR *)ctx->cspname,
  1381. ctx->csptype, ctx->keytype);
  1382. }
  1383. break;
  1384. }
  1385. return key;
  1386. }
  1387. void capi_free_key(CAPI_KEY * key)
  1388. {
  1389. if (!key)
  1390. return;
  1391. CryptDestroyKey(key->key);
  1392. CryptReleaseContext(key->hprov, 0);
  1393. if (key->pcert)
  1394. CertFreeCertificateContext(key->pcert);
  1395. OPENSSL_free(key);
  1396. }
  1397. /* Initialize a CAPI_CTX structure */
  1398. static CAPI_CTX *capi_ctx_new(void)
  1399. {
  1400. CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
  1401. if (ctx == NULL) {
  1402. CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
  1403. return NULL;
  1404. }
  1405. ctx->csptype = PROV_RSA_FULL;
  1406. ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
  1407. ctx->keytype = AT_KEYEXCHANGE;
  1408. ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
  1409. CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
  1410. ctx->lookup_method = CAPI_LU_SUBSTR;
  1411. ctx->client_cert_select = cert_select_simple;
  1412. return ctx;
  1413. }
  1414. static void capi_ctx_free(CAPI_CTX * ctx)
  1415. {
  1416. CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
  1417. if (!ctx)
  1418. return;
  1419. OPENSSL_free(ctx->cspname);
  1420. OPENSSL_free(ctx->debug_file);
  1421. OPENSSL_free(ctx->storename);
  1422. OPENSSL_free(ctx->ssl_client_store);
  1423. OPENSSL_free(ctx);
  1424. }
  1425. static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
  1426. int check)
  1427. {
  1428. LPSTR tmpcspname;
  1429. CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
  1430. if (check) {
  1431. HCRYPTPROV hprov;
  1432. LPTSTR name = NULL;
  1433. if (sizeof(TCHAR) != sizeof(char)) {
  1434. DWORD len;
  1435. if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
  1436. name = alloca(len * sizeof(WCHAR));
  1437. MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
  1438. }
  1439. } else {
  1440. name = (TCHAR *)pname;
  1441. }
  1442. if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
  1443. CRYPT_VERIFYCONTEXT)) {
  1444. CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
  1445. CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
  1446. capi_addlasterror();
  1447. return 0;
  1448. }
  1449. CryptReleaseContext(hprov, 0);
  1450. }
  1451. tmpcspname = OPENSSL_strdup(pname);
  1452. if (tmpcspname == NULL) {
  1453. CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, ERR_R_MALLOC_FAILURE);
  1454. return 0;
  1455. }
  1456. OPENSSL_free(ctx->cspname);
  1457. ctx->cspname = tmpcspname;
  1458. ctx->csptype = type;
  1459. return 1;
  1460. }
  1461. static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
  1462. {
  1463. LPSTR pname;
  1464. DWORD type;
  1465. int res;
  1466. if (capi_get_provname(ctx, &pname, &type, idx) != 1)
  1467. return 0;
  1468. res = capi_ctx_set_provname(ctx, pname, type, 0);
  1469. OPENSSL_free(pname);
  1470. return res;
  1471. }
  1472. static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
  1473. {
  1474. int i;
  1475. X509_NAME *nm;
  1476. /* Special case: empty list: match anything */
  1477. if (sk_X509_NAME_num(ca_dn) <= 0)
  1478. return 1;
  1479. for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
  1480. nm = sk_X509_NAME_value(ca_dn, i);
  1481. if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
  1482. return 1;
  1483. }
  1484. return 0;
  1485. }
  1486. static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
  1487. STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
  1488. EVP_PKEY **pkey, STACK_OF(X509) **pother,
  1489. UI_METHOD *ui_method,
  1490. void *callback_data)
  1491. {
  1492. STACK_OF(X509) *certs = NULL;
  1493. X509 *x;
  1494. char *storename;
  1495. const unsigned char *p;
  1496. int i, client_cert_idx;
  1497. HCERTSTORE hstore;
  1498. PCCERT_CONTEXT cert = NULL, excert = NULL;
  1499. CAPI_CTX *ctx;
  1500. CAPI_KEY *key;
  1501. ctx = ENGINE_get_ex_data(e, capi_idx);
  1502. *pcert = NULL;
  1503. *pkey = NULL;
  1504. storename = ctx->ssl_client_store;
  1505. if (!storename)
  1506. storename = "MY";
  1507. hstore = capi_open_store(ctx, storename);
  1508. if (!hstore)
  1509. return 0;
  1510. /* Enumerate all certificates collect any matches */
  1511. for (i = 0;; i++) {
  1512. cert = CertEnumCertificatesInStore(hstore, cert);
  1513. if (!cert)
  1514. break;
  1515. p = cert->pbCertEncoded;
  1516. x = d2i_X509(NULL, &p, cert->cbCertEncoded);
  1517. if (!x) {
  1518. CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
  1519. continue;
  1520. }
  1521. if (cert_issuer_match(ca_dn, x)
  1522. && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
  1523. key = capi_get_cert_key(ctx, cert);
  1524. if (!key) {
  1525. X509_free(x);
  1526. continue;
  1527. }
  1528. /*
  1529. * Match found: attach extra data to it so we can retrieve the
  1530. * key later.
  1531. */
  1532. excert = CertDuplicateCertificateContext(cert);
  1533. key->pcert = excert;
  1534. X509_set_ex_data(x, cert_capi_idx, key);
  1535. if (!certs)
  1536. certs = sk_X509_new_null();
  1537. sk_X509_push(certs, x);
  1538. } else {
  1539. X509_free(x);
  1540. }
  1541. }
  1542. if (cert)
  1543. CertFreeCertificateContext(cert);
  1544. if (hstore)
  1545. CertCloseStore(hstore, 0);
  1546. if (!certs)
  1547. return 0;
  1548. /* Select the appropriate certificate */
  1549. client_cert_idx = ctx->client_cert_select(e, ssl, certs);
  1550. /* Set the selected certificate and free the rest */
  1551. for (i = 0; i < sk_X509_num(certs); i++) {
  1552. x = sk_X509_value(certs, i);
  1553. if (i == client_cert_idx)
  1554. *pcert = x;
  1555. else {
  1556. key = X509_get_ex_data(x, cert_capi_idx);
  1557. capi_free_key(key);
  1558. X509_free(x);
  1559. }
  1560. }
  1561. sk_X509_free(certs);
  1562. if (!*pcert)
  1563. return 0;
  1564. /* Setup key for selected certificate */
  1565. key = X509_get_ex_data(*pcert, cert_capi_idx);
  1566. *pkey = capi_get_pkey(e, key);
  1567. X509_set_ex_data(*pcert, cert_capi_idx, NULL);
  1568. return 1;
  1569. }
  1570. /* Simple client cert selection function: always select first */
  1571. static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
  1572. {
  1573. return 0;
  1574. }
  1575. # ifdef OPENSSL_CAPIENG_DIALOG
  1576. /*
  1577. * More complex cert selection function, using standard function
  1578. * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
  1579. */
  1580. /*
  1581. * Definitions which are in cryptuiapi.h but this is not present in older
  1582. * versions of headers.
  1583. */
  1584. # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
  1585. # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
  1586. # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
  1587. # endif
  1588. # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
  1589. # define dlg_prompt L"Select a certificate to use for authentication"
  1590. # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
  1591. |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
  1592. static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
  1593. {
  1594. X509 *x;
  1595. HCERTSTORE dstore;
  1596. PCCERT_CONTEXT cert;
  1597. CAPI_CTX *ctx;
  1598. CAPI_KEY *key;
  1599. HWND hwnd;
  1600. int i, idx = -1;
  1601. if (sk_X509_num(certs) == 1)
  1602. return 0;
  1603. ctx = ENGINE_get_ex_data(e, capi_idx);
  1604. /* Create an in memory store of certificates */
  1605. dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
  1606. CERT_STORE_CREATE_NEW_FLAG, NULL);
  1607. if (!dstore) {
  1608. CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
  1609. capi_addlasterror();
  1610. goto err;
  1611. }
  1612. /* Add all certificates to store */
  1613. for (i = 0; i < sk_X509_num(certs); i++) {
  1614. x = sk_X509_value(certs, i);
  1615. key = X509_get_ex_data(x, cert_capi_idx);
  1616. if (!CertAddCertificateContextToStore(dstore, key->pcert,
  1617. CERT_STORE_ADD_NEW, NULL)) {
  1618. CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
  1619. capi_addlasterror();
  1620. goto err;
  1621. }
  1622. }
  1623. hwnd = GetForegroundWindow();
  1624. if (!hwnd)
  1625. hwnd = GetActiveWindow();
  1626. if (!hwnd && ctx->getconswindow)
  1627. hwnd = ctx->getconswindow();
  1628. /* Call dialog to select one */
  1629. cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
  1630. dlg_columns, 0, NULL);
  1631. /* Find matching cert from list */
  1632. if (cert) {
  1633. for (i = 0; i < sk_X509_num(certs); i++) {
  1634. x = sk_X509_value(certs, i);
  1635. key = X509_get_ex_data(x, cert_capi_idx);
  1636. if (CertCompareCertificate
  1637. (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
  1638. key->pcert->pCertInfo)) {
  1639. idx = i;
  1640. break;
  1641. }
  1642. }
  1643. }
  1644. err:
  1645. if (dstore)
  1646. CertCloseStore(dstore, 0);
  1647. return idx;
  1648. }
  1649. # endif
  1650. #else /* !__COMPILE_CAPIENG */
  1651. # include <openssl/engine.h>
  1652. # ifndef OPENSSL_NO_DYNAMIC_ENGINE
  1653. OPENSSL_EXPORT
  1654. int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
  1655. OPENSSL_EXPORT
  1656. int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
  1657. {
  1658. return 0;
  1659. }
  1660. IMPLEMENT_DYNAMIC_CHECK_FN()
  1661. # else
  1662. void engine_load_capi_int(void);
  1663. void engine_load_capi_int(void)
  1664. {
  1665. }
  1666. # endif
  1667. #endif