e_capi.c 55 KB

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