e_capi.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905
  1. /*
  2. * Copyright 2008-2018 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (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 const WCHAR rsa_aes_cspname[] =
  346. L"Microsoft Enhanced RSA and AES Cryptographic Provider";
  347. static const WCHAR rsa_enh_cspname[] =
  348. L"Microsoft Enhanced Cryptographic Provider v1.0";
  349. static int capi_init(ENGINE *e)
  350. {
  351. CAPI_CTX *ctx;
  352. const RSA_METHOD *ossl_rsa_meth;
  353. # ifndef OPENSSL_NO_DSA
  354. const DSA_METHOD *ossl_dsa_meth;
  355. # endif
  356. HCRYPTPROV hprov;
  357. if (capi_idx < 0) {
  358. capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
  359. if (capi_idx < 0)
  360. goto memerr;
  361. cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
  362. /* Setup RSA_METHOD */
  363. rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
  364. ossl_rsa_meth = RSA_PKCS1_OpenSSL();
  365. if ( !RSA_meth_set_pub_enc(capi_rsa_method,
  366. RSA_meth_get_pub_enc(ossl_rsa_meth))
  367. || !RSA_meth_set_pub_dec(capi_rsa_method,
  368. RSA_meth_get_pub_dec(ossl_rsa_meth))
  369. || !RSA_meth_set_priv_enc(capi_rsa_method, capi_rsa_priv_enc)
  370. || !RSA_meth_set_priv_dec(capi_rsa_method, capi_rsa_priv_dec)
  371. || !RSA_meth_set_mod_exp(capi_rsa_method,
  372. RSA_meth_get_mod_exp(ossl_rsa_meth))
  373. || !RSA_meth_set_bn_mod_exp(capi_rsa_method,
  374. RSA_meth_get_bn_mod_exp(ossl_rsa_meth))
  375. || !RSA_meth_set_finish(capi_rsa_method, capi_rsa_free)
  376. || !RSA_meth_set_sign(capi_rsa_method, capi_rsa_sign)) {
  377. goto memerr;
  378. }
  379. # ifndef OPENSSL_NO_DSA
  380. /* Setup DSA Method */
  381. dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
  382. ossl_dsa_meth = DSA_OpenSSL();
  383. if ( !DSA_meth_set_sign(capi_dsa_method, capi_dsa_do_sign)
  384. || !DSA_meth_set_verify(capi_dsa_method,
  385. DSA_meth_get_verify(ossl_dsa_meth))
  386. || !DSA_meth_set_finish(capi_dsa_method, capi_dsa_free)
  387. || !DSA_meth_set_mod_exp(capi_dsa_method,
  388. DSA_meth_get_mod_exp(ossl_dsa_meth))
  389. || !DSA_meth_set_bn_mod_exp(capi_dsa_method,
  390. DSA_meth_get_bn_mod_exp(ossl_dsa_meth))) {
  391. goto memerr;
  392. }
  393. # endif
  394. }
  395. ctx = capi_ctx_new();
  396. if (ctx == NULL)
  397. goto memerr;
  398. ENGINE_set_ex_data(e, capi_idx, ctx);
  399. # ifdef OPENSSL_CAPIENG_DIALOG
  400. {
  401. HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
  402. HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
  403. if (cryptui)
  404. ctx->certselectdlg =
  405. (CERTDLG) GetProcAddress(cryptui,
  406. "CryptUIDlgSelectCertificateFromStore");
  407. if (kernel)
  408. ctx->getconswindow =
  409. (GETCONSWIN) GetProcAddress(kernel, "GetConsoleWindow");
  410. if (cryptui && !OPENSSL_isservice())
  411. ctx->client_cert_select = cert_select_dialog;
  412. }
  413. # endif
  414. /* See if there is RSA+AES CSP */
  415. if (CryptAcquireContextW(&hprov, NULL, rsa_aes_cspname, PROV_RSA_AES,
  416. CRYPT_VERIFYCONTEXT)) {
  417. use_aes_csp = 1;
  418. CryptReleaseContext(hprov, 0);
  419. }
  420. return 1;
  421. memerr:
  422. CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
  423. return 0;
  424. return 1;
  425. }
  426. static int capi_destroy(ENGINE *e)
  427. {
  428. RSA_meth_free(capi_rsa_method);
  429. capi_rsa_method = NULL;
  430. # ifndef OPENSSL_NO_DSA
  431. DSA_meth_free(capi_dsa_method);
  432. capi_dsa_method = NULL;
  433. # endif
  434. ERR_unload_CAPI_strings();
  435. return 1;
  436. }
  437. static int capi_finish(ENGINE *e)
  438. {
  439. CAPI_CTX *ctx;
  440. ctx = ENGINE_get_ex_data(e, capi_idx);
  441. capi_ctx_free(ctx);
  442. ENGINE_set_ex_data(e, capi_idx, NULL);
  443. return 1;
  444. }
  445. /*
  446. * CryptoAPI key application data. This contains a handle to the private key
  447. * container (for sign operations) and a handle to the key (for decrypt
  448. * operations).
  449. */
  450. struct CAPI_KEY_st {
  451. /* Associated certificate context (if any) */
  452. PCCERT_CONTEXT pcert;
  453. HCRYPTPROV hprov;
  454. HCRYPTKEY key;
  455. DWORD keyspec;
  456. };
  457. static int bind_capi(ENGINE *e)
  458. {
  459. capi_rsa_method = RSA_meth_new("CryptoAPI RSA method", 0);
  460. if (capi_rsa_method == NULL)
  461. return 0;
  462. # ifndef OPENSSL_NO_DSA
  463. capi_dsa_method = DSA_meth_new("CryptoAPI DSA method", 0);
  464. if (capi_dsa_method == NULL)
  465. goto memerr;
  466. # endif
  467. if (!ENGINE_set_id(e, engine_capi_id)
  468. || !ENGINE_set_name(e, engine_capi_name)
  469. || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
  470. || !ENGINE_set_init_function(e, capi_init)
  471. || !ENGINE_set_finish_function(e, capi_finish)
  472. || !ENGINE_set_destroy_function(e, capi_destroy)
  473. || !ENGINE_set_RSA(e, capi_rsa_method)
  474. # ifndef OPENSSL_NO_DSA
  475. || !ENGINE_set_DSA(e, capi_dsa_method)
  476. # endif
  477. || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
  478. || !ENGINE_set_load_ssl_client_cert_function(e,
  479. capi_load_ssl_client_cert)
  480. || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
  481. || !ENGINE_set_ctrl_function(e, capi_ctrl))
  482. goto memerr;
  483. ERR_load_CAPI_strings();
  484. return 1;
  485. memerr:
  486. RSA_meth_free(capi_rsa_method);
  487. capi_rsa_method = NULL;
  488. # ifndef OPENSSL_NO_DSA
  489. DSA_meth_free(capi_dsa_method);
  490. capi_dsa_method = NULL;
  491. # endif
  492. return 0;
  493. }
  494. # ifndef OPENSSL_NO_DYNAMIC_ENGINE
  495. static int bind_helper(ENGINE *e, const char *id)
  496. {
  497. if (id && (strcmp(id, engine_capi_id) != 0))
  498. return 0;
  499. if (!bind_capi(e))
  500. return 0;
  501. return 1;
  502. }
  503. IMPLEMENT_DYNAMIC_CHECK_FN()
  504. IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
  505. # else
  506. static ENGINE *engine_capi(void)
  507. {
  508. ENGINE *ret = ENGINE_new();
  509. if (ret == NULL)
  510. return NULL;
  511. if (!bind_capi(ret)) {
  512. ENGINE_free(ret);
  513. return NULL;
  514. }
  515. return ret;
  516. }
  517. void engine_load_capi_int(void)
  518. {
  519. /* Copied from eng_[openssl|dyn].c */
  520. ENGINE *toadd = engine_capi();
  521. if (!toadd)
  522. return;
  523. ENGINE_add(toadd);
  524. ENGINE_free(toadd);
  525. ERR_clear_error();
  526. }
  527. # endif
  528. static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
  529. {
  530. int i;
  531. /*
  532. * Reverse buffer in place: since this is a keyblob structure that will
  533. * be freed up after conversion anyway it doesn't matter if we change
  534. * it.
  535. */
  536. for (i = 0; i < binlen / 2; i++) {
  537. unsigned char c;
  538. c = bin[i];
  539. bin[i] = bin[binlen - i - 1];
  540. bin[binlen - i - 1] = c;
  541. }
  542. if (!BN_bin2bn(bin, binlen, bn))
  543. return 0;
  544. return 1;
  545. }
  546. /* Given a CAPI_KEY get an EVP_PKEY structure */
  547. static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY *key)
  548. {
  549. unsigned char *pubkey = NULL;
  550. DWORD len;
  551. BLOBHEADER *bh;
  552. RSA *rkey = NULL;
  553. DSA *dkey = NULL;
  554. EVP_PKEY *ret = NULL;
  555. if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
  556. CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
  557. capi_addlasterror();
  558. return NULL;
  559. }
  560. pubkey = OPENSSL_malloc(len);
  561. if (pubkey == NULL)
  562. goto memerr;
  563. if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
  564. CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
  565. capi_addlasterror();
  566. goto err;
  567. }
  568. bh = (BLOBHEADER *) pubkey;
  569. if (bh->bType != PUBLICKEYBLOB) {
  570. CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
  571. goto err;
  572. }
  573. if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
  574. RSAPUBKEY *rp;
  575. DWORD rsa_modlen;
  576. BIGNUM *e = NULL, *n = NULL;
  577. unsigned char *rsa_modulus;
  578. rp = (RSAPUBKEY *) (bh + 1);
  579. if (rp->magic != 0x31415352) {
  580. char magstr[10];
  581. BIO_snprintf(magstr, 10, "%lx", rp->magic);
  582. CAPIerr(CAPI_F_CAPI_GET_PKEY,
  583. CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
  584. ERR_add_error_data(2, "magic=0x", magstr);
  585. goto err;
  586. }
  587. rsa_modulus = (unsigned char *)(rp + 1);
  588. rkey = RSA_new_method(eng);
  589. if (!rkey)
  590. goto memerr;
  591. e = BN_new();
  592. n = BN_new();
  593. if (e == NULL || n == NULL) {
  594. BN_free(e);
  595. BN_free(n);
  596. goto memerr;
  597. }
  598. RSA_set0_key(rkey, n, e, NULL);
  599. if (!BN_set_word(e, rp->pubexp))
  600. goto memerr;
  601. rsa_modlen = rp->bitlen / 8;
  602. if (!lend_tobn(n, rsa_modulus, rsa_modlen))
  603. goto memerr;
  604. RSA_set_ex_data(rkey, rsa_capi_idx, key);
  605. if ((ret = EVP_PKEY_new()) == NULL)
  606. goto memerr;
  607. EVP_PKEY_assign_RSA(ret, rkey);
  608. rkey = NULL;
  609. # ifndef OPENSSL_NO_DSA
  610. } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
  611. DSSPUBKEY *dp;
  612. DWORD dsa_plen;
  613. unsigned char *btmp;
  614. BIGNUM *p, *q, *g, *pub_key;
  615. dp = (DSSPUBKEY *) (bh + 1);
  616. if (dp->magic != 0x31535344) {
  617. char magstr[10];
  618. BIO_snprintf(magstr, 10, "%lx", dp->magic);
  619. CAPIerr(CAPI_F_CAPI_GET_PKEY,
  620. CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
  621. ERR_add_error_data(2, "magic=0x", magstr);
  622. goto err;
  623. }
  624. dsa_plen = dp->bitlen / 8;
  625. btmp = (unsigned char *)(dp + 1);
  626. dkey = DSA_new_method(eng);
  627. if (!dkey)
  628. goto memerr;
  629. p = BN_new();
  630. q = BN_new();
  631. g = BN_new();
  632. pub_key = BN_new();
  633. if (p == NULL || q == NULL || g == NULL || pub_key == NULL) {
  634. BN_free(p);
  635. BN_free(q);
  636. BN_free(g);
  637. BN_free(pub_key);
  638. goto memerr;
  639. }
  640. DSA_set0_pqg(dkey, p, q, g);
  641. DSA_set0_key(dkey, pub_key, NULL);
  642. if (!lend_tobn(p, btmp, dsa_plen))
  643. goto memerr;
  644. btmp += dsa_plen;
  645. if (!lend_tobn(q, btmp, 20))
  646. goto memerr;
  647. btmp += 20;
  648. if (!lend_tobn(g, btmp, dsa_plen))
  649. goto memerr;
  650. btmp += dsa_plen;
  651. if (!lend_tobn(pub_key, btmp, dsa_plen))
  652. goto memerr;
  653. btmp += dsa_plen;
  654. DSA_set_ex_data(dkey, dsa_capi_idx, key);
  655. if ((ret = EVP_PKEY_new()) == NULL)
  656. goto memerr;
  657. EVP_PKEY_assign_DSA(ret, dkey);
  658. dkey = NULL;
  659. # endif
  660. } else {
  661. char algstr[10];
  662. BIO_snprintf(algstr, 10, "%ux", bh->aiKeyAlg);
  663. CAPIerr(CAPI_F_CAPI_GET_PKEY,
  664. CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
  665. ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
  666. goto err;
  667. }
  668. err:
  669. OPENSSL_free(pubkey);
  670. if (!ret) {
  671. RSA_free(rkey);
  672. # ifndef OPENSSL_NO_DSA
  673. DSA_free(dkey);
  674. # endif
  675. }
  676. return ret;
  677. memerr:
  678. CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
  679. goto err;
  680. }
  681. static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
  682. UI_METHOD *ui_method, void *callback_data)
  683. {
  684. CAPI_CTX *ctx;
  685. CAPI_KEY *key;
  686. EVP_PKEY *ret;
  687. ctx = ENGINE_get_ex_data(eng, capi_idx);
  688. if (!ctx) {
  689. CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
  690. return NULL;
  691. }
  692. key = capi_find_key(ctx, key_id);
  693. if (!key)
  694. return NULL;
  695. ret = capi_get_pkey(eng, key);
  696. if (!ret)
  697. capi_free_key(key);
  698. return ret;
  699. }
  700. /* CryptoAPI RSA operations */
  701. int capi_rsa_priv_enc(int flen, const unsigned char *from,
  702. unsigned char *to, RSA *rsa, int padding)
  703. {
  704. CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
  705. return -1;
  706. }
  707. int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
  708. unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
  709. {
  710. ALG_ID alg;
  711. HCRYPTHASH hash;
  712. DWORD slen;
  713. unsigned int i;
  714. int ret = -1;
  715. CAPI_KEY *capi_key;
  716. CAPI_CTX *ctx;
  717. ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
  718. CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
  719. capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
  720. if (!capi_key) {
  721. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
  722. return -1;
  723. }
  724. /* Convert the signature type to a CryptoAPI algorithm ID */
  725. switch (dtype) {
  726. case NID_sha256:
  727. alg = CALG_SHA_256;
  728. break;
  729. case NID_sha384:
  730. alg = CALG_SHA_384;
  731. break;
  732. case NID_sha512:
  733. alg = CALG_SHA_512;
  734. break;
  735. case NID_sha1:
  736. alg = CALG_SHA1;
  737. break;
  738. case NID_md5:
  739. alg = CALG_MD5;
  740. break;
  741. case NID_md5_sha1:
  742. alg = CALG_SSL3_SHAMD5;
  743. break;
  744. default:
  745. {
  746. char algstr[10];
  747. BIO_snprintf(algstr, 10, "%x", dtype);
  748. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
  749. ERR_add_error_data(2, "NID=0x", algstr);
  750. return -1;
  751. }
  752. }
  753. /* Create the hash object */
  754. if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
  755. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
  756. capi_addlasterror();
  757. return -1;
  758. }
  759. /* Set the hash value to the value passed */
  760. if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
  761. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
  762. capi_addlasterror();
  763. goto err;
  764. }
  765. /* Finally sign it */
  766. slen = RSA_size(rsa);
  767. if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
  768. CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
  769. capi_addlasterror();
  770. goto err;
  771. } else {
  772. ret = 1;
  773. /* Inplace byte reversal of signature */
  774. for (i = 0; i < slen / 2; i++) {
  775. unsigned char c;
  776. c = sigret[i];
  777. sigret[i] = sigret[slen - i - 1];
  778. sigret[slen - i - 1] = c;
  779. }
  780. *siglen = slen;
  781. }
  782. /* Now cleanup */
  783. err:
  784. CryptDestroyHash(hash);
  785. return ret;
  786. }
  787. int capi_rsa_priv_dec(int flen, const unsigned char *from,
  788. unsigned char *to, RSA *rsa, int padding)
  789. {
  790. int i;
  791. unsigned char *tmpbuf;
  792. CAPI_KEY *capi_key;
  793. CAPI_CTX *ctx;
  794. DWORD flags = 0;
  795. DWORD dlen;
  796. if (flen <= 0)
  797. return flen;
  798. ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
  799. CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
  800. capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
  801. if (!capi_key) {
  802. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
  803. return -1;
  804. }
  805. switch (padding) {
  806. case RSA_PKCS1_PADDING:
  807. /* Nothing to do */
  808. break;
  809. #ifdef CRYPT_DECRYPT_RSA_NO_PADDING_CHECK
  810. case RSA_NO_PADDING:
  811. flags = CRYPT_DECRYPT_RSA_NO_PADDING_CHECK;
  812. break;
  813. #endif
  814. default:
  815. {
  816. char errstr[10];
  817. BIO_snprintf(errstr, 10, "%d", padding);
  818. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
  819. ERR_add_error_data(2, "padding=", errstr);
  820. return -1;
  821. }
  822. }
  823. /* Create temp reverse order version of input */
  824. if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
  825. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
  826. return -1;
  827. }
  828. for (i = 0; i < flen; i++)
  829. tmpbuf[flen - i - 1] = from[i];
  830. /* Finally decrypt it */
  831. dlen = flen;
  832. if (!CryptDecrypt(capi_key->key, 0, TRUE, flags, tmpbuf, &dlen)) {
  833. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
  834. capi_addlasterror();
  835. OPENSSL_cleanse(tmpbuf, dlen);
  836. OPENSSL_free(tmpbuf);
  837. return -1;
  838. } else {
  839. memcpy(to, tmpbuf, (flen = (int)dlen));
  840. }
  841. OPENSSL_cleanse(tmpbuf, flen);
  842. OPENSSL_free(tmpbuf);
  843. return flen;
  844. }
  845. static int capi_rsa_free(RSA *rsa)
  846. {
  847. CAPI_KEY *capi_key;
  848. capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
  849. capi_free_key(capi_key);
  850. RSA_set_ex_data(rsa, rsa_capi_idx, 0);
  851. return 1;
  852. }
  853. # ifndef OPENSSL_NO_DSA
  854. /* CryptoAPI DSA operations */
  855. static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
  856. DSA *dsa)
  857. {
  858. HCRYPTHASH hash;
  859. DWORD slen;
  860. DSA_SIG *ret = NULL;
  861. CAPI_KEY *capi_key;
  862. CAPI_CTX *ctx;
  863. unsigned char csigbuf[40];
  864. ctx = ENGINE_get_ex_data(DSA_get0_engine(dsa), capi_idx);
  865. CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
  866. capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
  867. if (!capi_key) {
  868. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
  869. return NULL;
  870. }
  871. if (dlen != 20) {
  872. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
  873. return NULL;
  874. }
  875. /* Create the hash object */
  876. if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
  877. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
  878. capi_addlasterror();
  879. return NULL;
  880. }
  881. /* Set the hash value to the value passed */
  882. if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
  883. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
  884. capi_addlasterror();
  885. goto err;
  886. }
  887. /* Finally sign it */
  888. slen = sizeof(csigbuf);
  889. if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
  890. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
  891. capi_addlasterror();
  892. goto err;
  893. } else {
  894. BIGNUM *r = BN_new(), *s = BN_new();
  895. if (r == NULL || s == NULL
  896. || !lend_tobn(r, csigbuf, 20)
  897. || !lend_tobn(s, csigbuf + 20, 20)
  898. || (ret = DSA_SIG_new()) == NULL) {
  899. BN_free(r); /* BN_free checks for BIGNUM * being NULL */
  900. BN_free(s);
  901. goto err;
  902. }
  903. DSA_SIG_set0(ret, r, s);
  904. }
  905. /* Now cleanup */
  906. err:
  907. OPENSSL_cleanse(csigbuf, 40);
  908. CryptDestroyHash(hash);
  909. return ret;
  910. }
  911. static int capi_dsa_free(DSA *dsa)
  912. {
  913. CAPI_KEY *capi_key;
  914. capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
  915. capi_free_key(capi_key);
  916. DSA_set_ex_data(dsa, dsa_capi_idx, 0);
  917. return 1;
  918. }
  919. # endif
  920. static void capi_vtrace(CAPI_CTX *ctx, int level, char *format,
  921. va_list argptr)
  922. {
  923. BIO *out;
  924. if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
  925. return;
  926. out = BIO_new_file(ctx->debug_file, "a+");
  927. if (out == NULL) {
  928. CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
  929. return;
  930. }
  931. BIO_vprintf(out, format, argptr);
  932. BIO_free(out);
  933. }
  934. static void CAPI_trace(CAPI_CTX *ctx, char *format, ...)
  935. {
  936. va_list args;
  937. va_start(args, format);
  938. capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
  939. va_end(args);
  940. }
  941. static void capi_addlasterror(void)
  942. {
  943. capi_adderror(GetLastError());
  944. }
  945. static void capi_adderror(DWORD err)
  946. {
  947. char errstr[10];
  948. BIO_snprintf(errstr, 10, "%lX", err);
  949. ERR_add_error_data(2, "Error code= 0x", errstr);
  950. }
  951. static char *wide_to_asc(LPCWSTR wstr)
  952. {
  953. char *str;
  954. int len_0, sz;
  955. if (!wstr)
  956. return NULL;
  957. len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
  958. sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
  959. if (!sz) {
  960. CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
  961. return NULL;
  962. }
  963. str = OPENSSL_malloc(sz);
  964. if (str == NULL) {
  965. CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
  966. return NULL;
  967. }
  968. if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
  969. OPENSSL_free(str);
  970. CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
  971. return NULL;
  972. }
  973. return str;
  974. }
  975. static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype,
  976. DWORD idx)
  977. {
  978. DWORD len, err;
  979. LPTSTR name;
  980. CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
  981. if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
  982. err = GetLastError();
  983. if (err == ERROR_NO_MORE_ITEMS)
  984. return 2;
  985. CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
  986. capi_adderror(err);
  987. return 0;
  988. }
  989. name = OPENSSL_malloc(len);
  990. if (name == NULL) {
  991. CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
  992. return 0;
  993. }
  994. if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
  995. err = GetLastError();
  996. OPENSSL_free(name);
  997. if (err == ERROR_NO_MORE_ITEMS)
  998. return 2;
  999. CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
  1000. capi_adderror(err);
  1001. return 0;
  1002. }
  1003. if (sizeof(TCHAR) != sizeof(char)) {
  1004. *pname = wide_to_asc((WCHAR *)name);
  1005. OPENSSL_free(name);
  1006. if (*pname == NULL)
  1007. return 0;
  1008. } else {
  1009. *pname = (char *)name;
  1010. }
  1011. CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
  1012. *ptype);
  1013. return 1;
  1014. }
  1015. static int capi_list_providers(CAPI_CTX *ctx, BIO *out)
  1016. {
  1017. DWORD idx, ptype;
  1018. int ret;
  1019. LPSTR provname = NULL;
  1020. CAPI_trace(ctx, "capi_list_providers\n");
  1021. BIO_printf(out, "Available CSPs:\n");
  1022. for (idx = 0;; idx++) {
  1023. ret = capi_get_provname(ctx, &provname, &ptype, idx);
  1024. if (ret == 2)
  1025. break;
  1026. if (ret == 0)
  1027. break;
  1028. BIO_printf(out, "%lu. %s, type %lu\n", idx, provname, ptype);
  1029. OPENSSL_free(provname);
  1030. }
  1031. return 1;
  1032. }
  1033. static int capi_list_containers(CAPI_CTX *ctx, BIO *out)
  1034. {
  1035. int ret = 1;
  1036. HCRYPTPROV hprov;
  1037. DWORD err, idx, flags, buflen = 0, clen;
  1038. LPSTR cname;
  1039. LPWSTR cspname = NULL;
  1040. CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
  1041. ctx->csptype);
  1042. if (ctx->cspname != NULL) {
  1043. if ((clen = MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
  1044. NULL, 0))) {
  1045. cspname = alloca(clen * sizeof(WCHAR));
  1046. MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
  1047. clen);
  1048. }
  1049. if (cspname == NULL) {
  1050. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
  1051. capi_addlasterror();
  1052. return 0;
  1053. }
  1054. }
  1055. if (!CryptAcquireContextW(&hprov, NULL, cspname, ctx->csptype,
  1056. CRYPT_VERIFYCONTEXT)) {
  1057. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
  1058. CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
  1059. capi_addlasterror();
  1060. return 0;
  1061. }
  1062. if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen,
  1063. CRYPT_FIRST)) {
  1064. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
  1065. capi_addlasterror();
  1066. CryptReleaseContext(hprov, 0);
  1067. return 0;
  1068. }
  1069. CAPI_trace(ctx, "Got max container len %d\n", buflen);
  1070. if (buflen == 0)
  1071. buflen = 1024;
  1072. cname = OPENSSL_malloc(buflen);
  1073. if (cname == NULL) {
  1074. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
  1075. goto err;
  1076. }
  1077. for (idx = 0;; idx++) {
  1078. clen = buflen;
  1079. cname[0] = 0;
  1080. if (idx == 0)
  1081. flags = CRYPT_FIRST;
  1082. else
  1083. flags = 0;
  1084. if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, (BYTE *)cname,
  1085. &clen, flags)) {
  1086. err = GetLastError();
  1087. if (err == ERROR_NO_MORE_ITEMS)
  1088. goto done;
  1089. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
  1090. capi_adderror(err);
  1091. goto err;
  1092. }
  1093. CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
  1094. cname, clen, idx, flags);
  1095. if (!cname[0] && (clen == buflen)) {
  1096. CAPI_trace(ctx, "Enumerate bug: using workaround\n");
  1097. goto done;
  1098. }
  1099. BIO_printf(out, "%lu. %s\n", idx, cname);
  1100. }
  1101. err:
  1102. ret = 0;
  1103. done:
  1104. OPENSSL_free(cname);
  1105. CryptReleaseContext(hprov, 0);
  1106. return ret;
  1107. }
  1108. static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx,
  1109. PCCERT_CONTEXT cert)
  1110. {
  1111. DWORD len;
  1112. CRYPT_KEY_PROV_INFO *pinfo;
  1113. if (!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
  1114. NULL, &len))
  1115. return NULL;
  1116. pinfo = OPENSSL_malloc(len);
  1117. if (pinfo == NULL) {
  1118. CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
  1119. return NULL;
  1120. }
  1121. if (!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
  1122. pinfo, &len)) {
  1123. CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
  1124. CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
  1125. capi_addlasterror();
  1126. OPENSSL_free(pinfo);
  1127. return NULL;
  1128. }
  1129. return pinfo;
  1130. }
  1131. static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out,
  1132. CRYPT_KEY_PROV_INFO *pinfo)
  1133. {
  1134. char *provname = NULL, *contname = NULL;
  1135. if (pinfo == NULL) {
  1136. BIO_printf(out, " No Private Key\n");
  1137. return;
  1138. }
  1139. provname = wide_to_asc(pinfo->pwszProvName);
  1140. contname = wide_to_asc(pinfo->pwszContainerName);
  1141. if (provname == NULL || contname == NULL)
  1142. goto err;
  1143. BIO_printf(out, " Private Key Info:\n");
  1144. BIO_printf(out, " Provider Name: %s, Provider Type %lu\n", provname,
  1145. pinfo->dwProvType);
  1146. BIO_printf(out, " Container Name: %s, Key Type %lu\n", contname,
  1147. pinfo->dwKeySpec);
  1148. err:
  1149. OPENSSL_free(provname);
  1150. OPENSSL_free(contname);
  1151. }
  1152. static char *capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
  1153. {
  1154. LPWSTR wfname;
  1155. DWORD dlen;
  1156. CAPI_trace(ctx, "capi_cert_get_fname\n");
  1157. if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
  1158. NULL, &dlen))
  1159. return NULL;
  1160. wfname = OPENSSL_malloc(dlen);
  1161. if (wfname == NULL)
  1162. return NULL;
  1163. if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
  1164. wfname, &dlen)) {
  1165. char *fname = wide_to_asc(wfname);
  1166. OPENSSL_free(wfname);
  1167. return fname;
  1168. }
  1169. CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
  1170. capi_addlasterror();
  1171. OPENSSL_free(wfname);
  1172. return NULL;
  1173. }
  1174. static void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert)
  1175. {
  1176. X509 *x;
  1177. const unsigned char *p;
  1178. unsigned long flags = ctx->dump_flags;
  1179. if (flags & CAPI_DMP_FNAME) {
  1180. char *fname;
  1181. fname = capi_cert_get_fname(ctx, cert);
  1182. if (fname) {
  1183. BIO_printf(out, " Friendly Name \"%s\"\n", fname);
  1184. OPENSSL_free(fname);
  1185. } else {
  1186. BIO_printf(out, " <No Friendly Name>\n");
  1187. }
  1188. }
  1189. p = cert->pbCertEncoded;
  1190. x = d2i_X509(NULL, &p, cert->cbCertEncoded);
  1191. if (!x)
  1192. BIO_printf(out, " <Can't parse certificate>\n");
  1193. if (flags & CAPI_DMP_SUMMARY) {
  1194. BIO_printf(out, " Subject: ");
  1195. X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
  1196. BIO_printf(out, "\n Issuer: ");
  1197. X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
  1198. BIO_printf(out, "\n");
  1199. }
  1200. if (flags & CAPI_DMP_FULL)
  1201. X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
  1202. if (flags & CAPI_DMP_PKEYINFO) {
  1203. CRYPT_KEY_PROV_INFO *pinfo;
  1204. pinfo = capi_get_prov_info(ctx, cert);
  1205. capi_dump_prov_info(ctx, out, pinfo);
  1206. OPENSSL_free(pinfo);
  1207. }
  1208. if (flags & CAPI_DMP_PEM)
  1209. PEM_write_bio_X509(out, x);
  1210. X509_free(x);
  1211. }
  1212. static HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename)
  1213. {
  1214. HCERTSTORE hstore;
  1215. if (!storename)
  1216. storename = ctx->storename;
  1217. if (!storename)
  1218. storename = "MY";
  1219. CAPI_trace(ctx, "Opening certificate store %s\n", storename);
  1220. hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
  1221. ctx->store_flags, storename);
  1222. if (!hstore) {
  1223. CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
  1224. capi_addlasterror();
  1225. }
  1226. return hstore;
  1227. }
  1228. int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id)
  1229. {
  1230. char *storename;
  1231. int idx;
  1232. int ret = 1;
  1233. HCERTSTORE hstore;
  1234. PCCERT_CONTEXT cert = NULL;
  1235. storename = ctx->storename;
  1236. if (!storename)
  1237. storename = "MY";
  1238. CAPI_trace(ctx, "Listing certs for store %s\n", storename);
  1239. hstore = capi_open_store(ctx, storename);
  1240. if (!hstore)
  1241. return 0;
  1242. if (id) {
  1243. cert = capi_find_cert(ctx, id, hstore);
  1244. if (!cert) {
  1245. ret = 0;
  1246. goto err;
  1247. }
  1248. capi_dump_cert(ctx, out, cert);
  1249. CertFreeCertificateContext(cert);
  1250. } else {
  1251. for (idx = 0;; idx++) {
  1252. cert = CertEnumCertificatesInStore(hstore, cert);
  1253. if (!cert)
  1254. break;
  1255. BIO_printf(out, "Certificate %d\n", idx);
  1256. capi_dump_cert(ctx, out, cert);
  1257. }
  1258. }
  1259. err:
  1260. CertCloseStore(hstore, 0);
  1261. return ret;
  1262. }
  1263. static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id,
  1264. HCERTSTORE hstore)
  1265. {
  1266. PCCERT_CONTEXT cert = NULL;
  1267. char *fname = NULL;
  1268. int match;
  1269. switch (ctx->lookup_method) {
  1270. case CAPI_LU_SUBSTR:
  1271. return CertFindCertificateInStore(hstore, X509_ASN_ENCODING, 0,
  1272. CERT_FIND_SUBJECT_STR_A, id, NULL);
  1273. case CAPI_LU_FNAME:
  1274. for (;;) {
  1275. cert = CertEnumCertificatesInStore(hstore, cert);
  1276. if (!cert)
  1277. return NULL;
  1278. fname = capi_cert_get_fname(ctx, cert);
  1279. if (fname) {
  1280. if (strcmp(fname, id))
  1281. match = 0;
  1282. else
  1283. match = 1;
  1284. OPENSSL_free(fname);
  1285. if (match)
  1286. return cert;
  1287. }
  1288. }
  1289. default:
  1290. return NULL;
  1291. }
  1292. }
  1293. static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const WCHAR *contname,
  1294. const WCHAR *provname, DWORD ptype,
  1295. DWORD keyspec)
  1296. {
  1297. DWORD dwFlags = 0;
  1298. CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
  1299. if (key == NULL)
  1300. return NULL;
  1301. /* If PROV_RSA_AES supported use it instead */
  1302. if (ptype == PROV_RSA_FULL && use_aes_csp &&
  1303. wcscmp(provname, rsa_enh_cspname) == 0) {
  1304. provname = rsa_aes_cspname;
  1305. ptype = PROV_RSA_AES;
  1306. }
  1307. if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
  1308. /*
  1309. * above 'if' is [complementary] copy from CAPI_trace and serves
  1310. * as optimization to minimize [below] malloc-ations
  1311. */
  1312. char *_contname = wide_to_asc(contname);
  1313. char *_provname = wide_to_asc(provname);
  1314. CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
  1315. _contname, _provname, ptype);
  1316. OPENSSL_free(_provname);
  1317. OPENSSL_free(_contname);
  1318. }
  1319. if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
  1320. dwFlags = CRYPT_MACHINE_KEYSET;
  1321. if (!CryptAcquireContextW(&key->hprov, contname, provname, ptype,
  1322. dwFlags)) {
  1323. CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
  1324. capi_addlasterror();
  1325. goto err;
  1326. }
  1327. if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
  1328. CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
  1329. capi_addlasterror();
  1330. CryptReleaseContext(key->hprov, 0);
  1331. goto err;
  1332. }
  1333. key->keyspec = keyspec;
  1334. key->pcert = NULL;
  1335. return key;
  1336. err:
  1337. OPENSSL_free(key);
  1338. return NULL;
  1339. }
  1340. static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
  1341. {
  1342. CAPI_KEY *key = NULL;
  1343. CRYPT_KEY_PROV_INFO *pinfo = NULL;
  1344. pinfo = capi_get_prov_info(ctx, cert);
  1345. if (pinfo != NULL)
  1346. key = capi_get_key(ctx, pinfo->pwszContainerName, pinfo->pwszProvName,
  1347. pinfo->dwProvType, pinfo->dwKeySpec);
  1348. OPENSSL_free(pinfo);
  1349. return key;
  1350. }
  1351. CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id)
  1352. {
  1353. PCCERT_CONTEXT cert;
  1354. HCERTSTORE hstore;
  1355. CAPI_KEY *key = NULL;
  1356. switch (ctx->lookup_method) {
  1357. case CAPI_LU_SUBSTR:
  1358. case CAPI_LU_FNAME:
  1359. hstore = capi_open_store(ctx, NULL);
  1360. if (!hstore)
  1361. return NULL;
  1362. cert = capi_find_cert(ctx, id, hstore);
  1363. if (cert) {
  1364. key = capi_get_cert_key(ctx, cert);
  1365. CertFreeCertificateContext(cert);
  1366. }
  1367. CertCloseStore(hstore, 0);
  1368. break;
  1369. case CAPI_LU_CONTNAME:
  1370. {
  1371. WCHAR *contname, *provname;
  1372. DWORD len;
  1373. if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
  1374. (contname = alloca(len * sizeof(WCHAR)),
  1375. MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
  1376. (len = MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
  1377. NULL, 0)) &&
  1378. (provname = alloca(len * sizeof(WCHAR)),
  1379. MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
  1380. provname, len)))
  1381. key = capi_get_key(ctx, contname, provname,
  1382. ctx->csptype, ctx->keytype);
  1383. }
  1384. break;
  1385. }
  1386. return key;
  1387. }
  1388. void capi_free_key(CAPI_KEY *key)
  1389. {
  1390. if (!key)
  1391. return;
  1392. CryptDestroyKey(key->key);
  1393. CryptReleaseContext(key->hprov, 0);
  1394. if (key->pcert)
  1395. CertFreeCertificateContext(key->pcert);
  1396. OPENSSL_free(key);
  1397. }
  1398. /* Initialize a CAPI_CTX structure */
  1399. static CAPI_CTX *capi_ctx_new(void)
  1400. {
  1401. CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
  1402. if (ctx == NULL) {
  1403. CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
  1404. return NULL;
  1405. }
  1406. ctx->csptype = PROV_RSA_FULL;
  1407. ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
  1408. ctx->keytype = AT_KEYEXCHANGE;
  1409. ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
  1410. CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
  1411. ctx->lookup_method = CAPI_LU_SUBSTR;
  1412. ctx->client_cert_select = cert_select_simple;
  1413. return ctx;
  1414. }
  1415. static void capi_ctx_free(CAPI_CTX *ctx)
  1416. {
  1417. CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
  1418. if (!ctx)
  1419. return;
  1420. OPENSSL_free(ctx->cspname);
  1421. OPENSSL_free(ctx->debug_file);
  1422. OPENSSL_free(ctx->storename);
  1423. OPENSSL_free(ctx->ssl_client_store);
  1424. OPENSSL_free(ctx);
  1425. }
  1426. static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type,
  1427. int check)
  1428. {
  1429. LPSTR tmpcspname;
  1430. CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
  1431. if (check) {
  1432. HCRYPTPROV hprov;
  1433. LPWSTR name = NULL;
  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. if (name == NULL || !CryptAcquireContextW(&hprov, NULL, name, type,
  1440. CRYPT_VERIFYCONTEXT)) {
  1441. CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
  1442. CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
  1443. capi_addlasterror();
  1444. return 0;
  1445. }
  1446. CryptReleaseContext(hprov, 0);
  1447. }
  1448. tmpcspname = OPENSSL_strdup(pname);
  1449. if (tmpcspname == NULL) {
  1450. CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, ERR_R_MALLOC_FAILURE);
  1451. return 0;
  1452. }
  1453. OPENSSL_free(ctx->cspname);
  1454. ctx->cspname = tmpcspname;
  1455. ctx->csptype = type;
  1456. return 1;
  1457. }
  1458. static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx)
  1459. {
  1460. LPSTR pname;
  1461. DWORD type;
  1462. int res;
  1463. if (capi_get_provname(ctx, &pname, &type, idx) != 1)
  1464. return 0;
  1465. res = capi_ctx_set_provname(ctx, pname, type, 0);
  1466. OPENSSL_free(pname);
  1467. return res;
  1468. }
  1469. static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
  1470. {
  1471. int i;
  1472. X509_NAME *nm;
  1473. /* Special case: empty list: match anything */
  1474. if (sk_X509_NAME_num(ca_dn) <= 0)
  1475. return 1;
  1476. for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
  1477. nm = sk_X509_NAME_value(ca_dn, i);
  1478. if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
  1479. return 1;
  1480. }
  1481. return 0;
  1482. }
  1483. static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
  1484. STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
  1485. EVP_PKEY **pkey, STACK_OF(X509) **pother,
  1486. UI_METHOD *ui_method,
  1487. void *callback_data)
  1488. {
  1489. STACK_OF(X509) *certs = NULL;
  1490. X509 *x;
  1491. char *storename;
  1492. const unsigned char *p;
  1493. int i, client_cert_idx;
  1494. HCERTSTORE hstore;
  1495. PCCERT_CONTEXT cert = NULL, excert = NULL;
  1496. CAPI_CTX *ctx;
  1497. CAPI_KEY *key;
  1498. ctx = ENGINE_get_ex_data(e, capi_idx);
  1499. *pcert = NULL;
  1500. *pkey = NULL;
  1501. storename = ctx->ssl_client_store;
  1502. if (!storename)
  1503. storename = "MY";
  1504. hstore = capi_open_store(ctx, storename);
  1505. if (!hstore)
  1506. return 0;
  1507. /* Enumerate all certificates collect any matches */
  1508. for (i = 0;; i++) {
  1509. cert = CertEnumCertificatesInStore(hstore, cert);
  1510. if (!cert)
  1511. break;
  1512. p = cert->pbCertEncoded;
  1513. x = d2i_X509(NULL, &p, cert->cbCertEncoded);
  1514. if (!x) {
  1515. CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
  1516. continue;
  1517. }
  1518. if (cert_issuer_match(ca_dn, x)
  1519. && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
  1520. key = capi_get_cert_key(ctx, cert);
  1521. if (!key) {
  1522. X509_free(x);
  1523. continue;
  1524. }
  1525. /*
  1526. * Match found: attach extra data to it so we can retrieve the
  1527. * key later.
  1528. */
  1529. excert = CertDuplicateCertificateContext(cert);
  1530. key->pcert = excert;
  1531. X509_set_ex_data(x, cert_capi_idx, key);
  1532. if (!certs)
  1533. certs = sk_X509_new_null();
  1534. sk_X509_push(certs, x);
  1535. } else {
  1536. X509_free(x);
  1537. }
  1538. }
  1539. if (cert)
  1540. CertFreeCertificateContext(cert);
  1541. if (hstore)
  1542. CertCloseStore(hstore, 0);
  1543. if (!certs)
  1544. return 0;
  1545. /* Select the appropriate certificate */
  1546. client_cert_idx = ctx->client_cert_select(e, ssl, certs);
  1547. /* Set the selected certificate and free the rest */
  1548. for (i = 0; i < sk_X509_num(certs); i++) {
  1549. x = sk_X509_value(certs, i);
  1550. if (i == client_cert_idx)
  1551. *pcert = x;
  1552. else {
  1553. key = X509_get_ex_data(x, cert_capi_idx);
  1554. capi_free_key(key);
  1555. X509_free(x);
  1556. }
  1557. }
  1558. sk_X509_free(certs);
  1559. if (*pcert == NULL)
  1560. return 0;
  1561. /* Setup key for selected certificate */
  1562. key = X509_get_ex_data(*pcert, cert_capi_idx);
  1563. *pkey = capi_get_pkey(e, key);
  1564. X509_set_ex_data(*pcert, cert_capi_idx, NULL);
  1565. return 1;
  1566. }
  1567. /* Simple client cert selection function: always select first */
  1568. static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
  1569. {
  1570. return 0;
  1571. }
  1572. # ifdef OPENSSL_CAPIENG_DIALOG
  1573. /*
  1574. * More complex cert selection function, using standard function
  1575. * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
  1576. */
  1577. /*
  1578. * Definitions which are in cryptuiapi.h but this is not present in older
  1579. * versions of headers.
  1580. */
  1581. # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
  1582. # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
  1583. # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
  1584. # endif
  1585. # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
  1586. # define dlg_prompt L"Select a certificate to use for authentication"
  1587. # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
  1588. |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
  1589. static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
  1590. {
  1591. X509 *x;
  1592. HCERTSTORE dstore;
  1593. PCCERT_CONTEXT cert;
  1594. CAPI_CTX *ctx;
  1595. CAPI_KEY *key;
  1596. HWND hwnd;
  1597. int i, idx = -1;
  1598. if (sk_X509_num(certs) == 1)
  1599. return 0;
  1600. ctx = ENGINE_get_ex_data(e, capi_idx);
  1601. /* Create an in memory store of certificates */
  1602. dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
  1603. CERT_STORE_CREATE_NEW_FLAG, NULL);
  1604. if (!dstore) {
  1605. CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
  1606. capi_addlasterror();
  1607. goto err;
  1608. }
  1609. /* Add all certificates to store */
  1610. for (i = 0; i < sk_X509_num(certs); i++) {
  1611. x = sk_X509_value(certs, i);
  1612. key = X509_get_ex_data(x, cert_capi_idx);
  1613. if (!CertAddCertificateContextToStore(dstore, key->pcert,
  1614. CERT_STORE_ADD_NEW, NULL)) {
  1615. CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
  1616. capi_addlasterror();
  1617. goto err;
  1618. }
  1619. }
  1620. hwnd = GetForegroundWindow();
  1621. if (!hwnd)
  1622. hwnd = GetActiveWindow();
  1623. if (!hwnd && ctx->getconswindow)
  1624. hwnd = ctx->getconswindow();
  1625. /* Call dialog to select one */
  1626. cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
  1627. dlg_columns, 0, NULL);
  1628. /* Find matching cert from list */
  1629. if (cert) {
  1630. for (i = 0; i < sk_X509_num(certs); i++) {
  1631. x = sk_X509_value(certs, i);
  1632. key = X509_get_ex_data(x, cert_capi_idx);
  1633. if (CertCompareCertificate
  1634. (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
  1635. key->pcert->pCertInfo)) {
  1636. idx = i;
  1637. break;
  1638. }
  1639. }
  1640. }
  1641. err:
  1642. if (dstore)
  1643. CertCloseStore(dstore, 0);
  1644. return idx;
  1645. }
  1646. # endif
  1647. #else /* !__COMPILE_CAPIENG */
  1648. # include <openssl/engine.h>
  1649. # ifndef OPENSSL_NO_DYNAMIC_ENGINE
  1650. OPENSSL_EXPORT
  1651. int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
  1652. OPENSSL_EXPORT
  1653. int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
  1654. {
  1655. return 0;
  1656. }
  1657. IMPLEMENT_DYNAMIC_CHECK_FN()
  1658. # else
  1659. void engine_load_capi_int(void);
  1660. void engine_load_capi_int(void)
  1661. {
  1662. }
  1663. # endif
  1664. #endif