e_capi.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909
  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-2018 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. DWORD flags = 0;
  780. ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
  781. CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
  782. capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
  783. if (!capi_key) {
  784. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
  785. return -1;
  786. }
  787. switch (padding) {
  788. case RSA_PKCS1_PADDING:
  789. /* Nothing to do */
  790. break;
  791. #ifdef CRYPT_DECRYPT_RSA_NO_PADDING_CHECK
  792. case RSA_NO_PADDING:
  793. flags = CRYPT_DECRYPT_RSA_NO_PADDING_CHECK;
  794. break;
  795. #endif
  796. default:
  797. {
  798. char errstr[10];
  799. BIO_snprintf(errstr, 10, "%d", padding);
  800. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
  801. ERR_add_error_data(2, "padding=", errstr);
  802. return -1;
  803. }
  804. }
  805. /* Create temp reverse order version of input */
  806. if (!(tmpbuf = OPENSSL_malloc(flen))) {
  807. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
  808. return -1;
  809. }
  810. for (i = 0; i < flen; i++)
  811. tmpbuf[flen - i - 1] = from[i];
  812. /* Finally decrypt it */
  813. if (!CryptDecrypt(capi_key->key, 0, TRUE, flags, tmpbuf, &flen)) {
  814. CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
  815. capi_addlasterror();
  816. OPENSSL_cleanse(tmpbuf, flen);
  817. OPENSSL_free(tmpbuf);
  818. return -1;
  819. } else {
  820. memcpy(to, tmpbuf, flen);
  821. }
  822. OPENSSL_cleanse(tmpbuf, flen);
  823. OPENSSL_free(tmpbuf);
  824. return flen;
  825. }
  826. static int capi_rsa_free(RSA *rsa)
  827. {
  828. CAPI_KEY *capi_key;
  829. capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
  830. capi_free_key(capi_key);
  831. RSA_set_ex_data(rsa, rsa_capi_idx, 0);
  832. return 1;
  833. }
  834. /* CryptoAPI DSA operations */
  835. static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
  836. DSA *dsa)
  837. {
  838. HCRYPTHASH hash;
  839. DWORD slen;
  840. DSA_SIG *ret = NULL;
  841. CAPI_KEY *capi_key;
  842. CAPI_CTX *ctx;
  843. unsigned char csigbuf[40];
  844. ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
  845. CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
  846. capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
  847. if (!capi_key) {
  848. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
  849. return NULL;
  850. }
  851. if (dlen != 20) {
  852. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
  853. return NULL;
  854. }
  855. /* Create the hash object */
  856. if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
  857. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
  858. capi_addlasterror();
  859. return NULL;
  860. }
  861. /* Set the hash value to the value passed */
  862. if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
  863. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
  864. capi_addlasterror();
  865. goto err;
  866. }
  867. /* Finally sign it */
  868. slen = sizeof(csigbuf);
  869. if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
  870. CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
  871. capi_addlasterror();
  872. goto err;
  873. } else {
  874. ret = DSA_SIG_new();
  875. if (!ret)
  876. goto err;
  877. ret->r = BN_new();
  878. ret->s = BN_new();
  879. if (!ret->r || !ret->s)
  880. goto err;
  881. if (!lend_tobn(ret->r, csigbuf, 20)
  882. || !lend_tobn(ret->s, csigbuf + 20, 20)) {
  883. DSA_SIG_free(ret);
  884. ret = NULL;
  885. goto err;
  886. }
  887. }
  888. /* Now cleanup */
  889. err:
  890. OPENSSL_cleanse(csigbuf, 40);
  891. CryptDestroyHash(hash);
  892. return ret;
  893. }
  894. static int capi_dsa_free(DSA *dsa)
  895. {
  896. CAPI_KEY *capi_key;
  897. capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
  898. capi_free_key(capi_key);
  899. DSA_set_ex_data(dsa, dsa_capi_idx, 0);
  900. return 1;
  901. }
  902. static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
  903. va_list argptr)
  904. {
  905. BIO *out;
  906. if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
  907. return;
  908. out = BIO_new_file(ctx->debug_file, "a+");
  909. BIO_vprintf(out, format, argptr);
  910. BIO_free(out);
  911. }
  912. static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
  913. {
  914. va_list args;
  915. va_start(args, format);
  916. capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
  917. va_end(args);
  918. }
  919. static void capi_addlasterror(void)
  920. {
  921. capi_adderror(GetLastError());
  922. }
  923. static void capi_adderror(DWORD err)
  924. {
  925. char errstr[10];
  926. BIO_snprintf(errstr, 10, "%lX", err);
  927. ERR_add_error_data(2, "Error code= 0x", errstr);
  928. }
  929. static char *wide_to_asc(LPCWSTR wstr)
  930. {
  931. char *str;
  932. int len_0, sz;
  933. if (!wstr)
  934. return NULL;
  935. len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
  936. sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
  937. if (!sz) {
  938. CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
  939. return NULL;
  940. }
  941. str = OPENSSL_malloc(sz);
  942. if (!str) {
  943. CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
  944. return NULL;
  945. }
  946. if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
  947. OPENSSL_free(str);
  948. CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
  949. return NULL;
  950. }
  951. return str;
  952. }
  953. static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
  954. DWORD idx)
  955. {
  956. DWORD len, err;
  957. LPTSTR name;
  958. CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
  959. if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
  960. err = GetLastError();
  961. if (err == ERROR_NO_MORE_ITEMS)
  962. return 2;
  963. CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
  964. capi_adderror(err);
  965. return 0;
  966. }
  967. if (sizeof(TCHAR) != sizeof(char))
  968. name = alloca(len);
  969. else
  970. name = OPENSSL_malloc(len);
  971. if (name == NULL) {
  972. CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
  973. return 0;
  974. }
  975. if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
  976. err = GetLastError();
  977. if (err == ERROR_NO_MORE_ITEMS)
  978. return 2;
  979. CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
  980. capi_adderror(err);
  981. return 0;
  982. }
  983. if (sizeof(TCHAR) != sizeof(char))
  984. *pname = wide_to_asc((WCHAR *)name);
  985. else
  986. *pname = (char *)name;
  987. CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
  988. *ptype);
  989. return 1;
  990. }
  991. static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
  992. {
  993. DWORD idx, ptype;
  994. int ret;
  995. LPSTR provname = NULL;
  996. CAPI_trace(ctx, "capi_list_providers\n");
  997. BIO_printf(out, "Available CSPs:\n");
  998. for (idx = 0;; idx++) {
  999. ret = capi_get_provname(ctx, &provname, &ptype, idx);
  1000. if (ret == 2)
  1001. break;
  1002. if (ret == 0)
  1003. break;
  1004. BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
  1005. OPENSSL_free(provname);
  1006. }
  1007. return 1;
  1008. }
  1009. static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
  1010. {
  1011. int ret = 1;
  1012. HCRYPTPROV hprov;
  1013. DWORD err, idx, flags, buflen = 0, clen;
  1014. LPSTR cname;
  1015. LPTSTR cspname = NULL;
  1016. CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
  1017. ctx->csptype);
  1018. if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
  1019. if ((clen =
  1020. MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
  1021. cspname = alloca(clen * sizeof(WCHAR));
  1022. MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
  1023. clen);
  1024. }
  1025. if (!cspname) {
  1026. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
  1027. capi_addlasterror();
  1028. return 0;
  1029. }
  1030. } else
  1031. cspname = (TCHAR *)ctx->cspname;
  1032. if (!CryptAcquireContext
  1033. (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
  1034. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
  1035. CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
  1036. capi_addlasterror();
  1037. return 0;
  1038. }
  1039. if (!CryptGetProvParam
  1040. (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
  1041. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
  1042. capi_addlasterror();
  1043. CryptReleaseContext(hprov, 0);
  1044. return 0;
  1045. }
  1046. CAPI_trace(ctx, "Got max container len %d\n", buflen);
  1047. if (buflen == 0)
  1048. buflen = 1024;
  1049. cname = OPENSSL_malloc(buflen);
  1050. if (!cname) {
  1051. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
  1052. goto err;
  1053. }
  1054. for (idx = 0;; idx++) {
  1055. clen = buflen;
  1056. cname[0] = 0;
  1057. if (idx == 0)
  1058. flags = CRYPT_FIRST;
  1059. else
  1060. flags = 0;
  1061. if (!CryptGetProvParam
  1062. (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
  1063. err = GetLastError();
  1064. if (err == ERROR_NO_MORE_ITEMS)
  1065. goto done;
  1066. CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
  1067. capi_adderror(err);
  1068. goto err;
  1069. }
  1070. CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
  1071. cname, clen, idx, flags);
  1072. if (!cname[0] && (clen == buflen)) {
  1073. CAPI_trace(ctx, "Enumerate bug: using workaround\n");
  1074. goto done;
  1075. }
  1076. BIO_printf(out, "%d. %s\n", idx, cname);
  1077. }
  1078. err:
  1079. ret = 0;
  1080. done:
  1081. if (cname)
  1082. OPENSSL_free(cname);
  1083. CryptReleaseContext(hprov, 0);
  1084. return ret;
  1085. }
  1086. CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
  1087. {
  1088. DWORD len;
  1089. CRYPT_KEY_PROV_INFO *pinfo;
  1090. if (!CertGetCertificateContextProperty
  1091. (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
  1092. return NULL;
  1093. pinfo = OPENSSL_malloc(len);
  1094. if (!pinfo) {
  1095. CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
  1096. return NULL;
  1097. }
  1098. if (!CertGetCertificateContextProperty
  1099. (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
  1100. CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
  1101. CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
  1102. capi_addlasterror();
  1103. OPENSSL_free(pinfo);
  1104. return NULL;
  1105. }
  1106. return pinfo;
  1107. }
  1108. static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
  1109. CRYPT_KEY_PROV_INFO * pinfo)
  1110. {
  1111. char *provname = NULL, *contname = NULL;
  1112. if (!pinfo) {
  1113. BIO_printf(out, " No Private Key\n");
  1114. return;
  1115. }
  1116. provname = wide_to_asc(pinfo->pwszProvName);
  1117. contname = wide_to_asc(pinfo->pwszContainerName);
  1118. if (!provname || !contname)
  1119. goto err;
  1120. BIO_printf(out, " Private Key Info:\n");
  1121. BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname,
  1122. pinfo->dwProvType);
  1123. BIO_printf(out, " Container Name: %s, Key Type %d\n", contname,
  1124. pinfo->dwKeySpec);
  1125. err:
  1126. if (provname)
  1127. OPENSSL_free(provname);
  1128. if (contname)
  1129. OPENSSL_free(contname);
  1130. }
  1131. char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
  1132. {
  1133. LPWSTR wfname;
  1134. DWORD dlen;
  1135. CAPI_trace(ctx, "capi_cert_get_fname\n");
  1136. if (!CertGetCertificateContextProperty
  1137. (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
  1138. return NULL;
  1139. wfname = OPENSSL_malloc(dlen);
  1140. if (wfname == NULL) {
  1141. CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, ERR_R_MALLOC_FAILURE);
  1142. return NULL;
  1143. }
  1144. if (CertGetCertificateContextProperty
  1145. (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
  1146. char *fname = wide_to_asc(wfname);
  1147. OPENSSL_free(wfname);
  1148. return fname;
  1149. }
  1150. CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
  1151. capi_addlasterror();
  1152. OPENSSL_free(wfname);
  1153. return NULL;
  1154. }
  1155. void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
  1156. {
  1157. X509 *x;
  1158. unsigned char *p;
  1159. unsigned long flags = ctx->dump_flags;
  1160. if (flags & CAPI_DMP_FNAME) {
  1161. char *fname;
  1162. fname = capi_cert_get_fname(ctx, cert);
  1163. if (fname) {
  1164. BIO_printf(out, " Friendly Name \"%s\"\n", fname);
  1165. OPENSSL_free(fname);
  1166. } else
  1167. BIO_printf(out, " <No Friendly Name>\n");
  1168. }
  1169. p = cert->pbCertEncoded;
  1170. x = d2i_X509(NULL, &p, cert->cbCertEncoded);
  1171. if (!x)
  1172. BIO_printf(out, " <Can't parse certificate>\n");
  1173. if (flags & CAPI_DMP_SUMMARY) {
  1174. BIO_printf(out, " Subject: ");
  1175. X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
  1176. BIO_printf(out, "\n Issuer: ");
  1177. X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
  1178. BIO_printf(out, "\n");
  1179. }
  1180. if (flags & CAPI_DMP_FULL)
  1181. X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
  1182. if (flags & CAPI_DMP_PKEYINFO) {
  1183. CRYPT_KEY_PROV_INFO *pinfo;
  1184. pinfo = capi_get_prov_info(ctx, cert);
  1185. capi_dump_prov_info(ctx, out, pinfo);
  1186. if (pinfo)
  1187. OPENSSL_free(pinfo);
  1188. }
  1189. if (flags & CAPI_DMP_PEM)
  1190. PEM_write_bio_X509(out, x);
  1191. X509_free(x);
  1192. }
  1193. HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
  1194. {
  1195. HCERTSTORE hstore;
  1196. if (!storename)
  1197. storename = ctx->storename;
  1198. if (!storename)
  1199. storename = "MY";
  1200. CAPI_trace(ctx, "Opening certificate store %s\n", storename);
  1201. hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
  1202. ctx->store_flags, storename);
  1203. if (!hstore) {
  1204. CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
  1205. capi_addlasterror();
  1206. }
  1207. return hstore;
  1208. }
  1209. int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
  1210. {
  1211. char *storename;
  1212. int idx;
  1213. int ret = 1;
  1214. HCERTSTORE hstore;
  1215. PCCERT_CONTEXT cert = NULL;
  1216. storename = ctx->storename;
  1217. if (!storename)
  1218. storename = "MY";
  1219. CAPI_trace(ctx, "Listing certs for store %s\n", storename);
  1220. hstore = capi_open_store(ctx, storename);
  1221. if (!hstore)
  1222. return 0;
  1223. if (id) {
  1224. cert = capi_find_cert(ctx, id, hstore);
  1225. if (!cert) {
  1226. ret = 0;
  1227. goto err;
  1228. }
  1229. capi_dump_cert(ctx, out, cert);
  1230. CertFreeCertificateContext(cert);
  1231. } else {
  1232. for (idx = 0;; idx++) {
  1233. cert = CertEnumCertificatesInStore(hstore, cert);
  1234. if (!cert)
  1235. break;
  1236. BIO_printf(out, "Certificate %d\n", idx);
  1237. capi_dump_cert(ctx, out, cert);
  1238. }
  1239. }
  1240. err:
  1241. CertCloseStore(hstore, 0);
  1242. return ret;
  1243. }
  1244. static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
  1245. HCERTSTORE hstore)
  1246. {
  1247. PCCERT_CONTEXT cert = NULL;
  1248. char *fname = NULL;
  1249. int match;
  1250. switch (ctx->lookup_method) {
  1251. case CAPI_LU_SUBSTR:
  1252. return CertFindCertificateInStore(hstore,
  1253. X509_ASN_ENCODING, 0,
  1254. CERT_FIND_SUBJECT_STR_A, id, NULL);
  1255. case CAPI_LU_FNAME:
  1256. for (;;) {
  1257. cert = CertEnumCertificatesInStore(hstore, cert);
  1258. if (!cert)
  1259. return NULL;
  1260. fname = capi_cert_get_fname(ctx, cert);
  1261. if (fname) {
  1262. if (strcmp(fname, id))
  1263. match = 0;
  1264. else
  1265. match = 1;
  1266. OPENSSL_free(fname);
  1267. if (match)
  1268. return cert;
  1269. }
  1270. }
  1271. default:
  1272. return NULL;
  1273. }
  1274. }
  1275. static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
  1276. TCHAR *provname, DWORD ptype, DWORD keyspec)
  1277. {
  1278. CAPI_KEY *key;
  1279. DWORD dwFlags = 0;
  1280. key = OPENSSL_malloc(sizeof(CAPI_KEY));
  1281. if (key == NULL) {
  1282. CAPIerr(CAPI_F_CAPI_GET_KEY, ERR_R_MALLOC_FAILURE);
  1283. capi_addlasterror();
  1284. goto err;
  1285. }
  1286. if (sizeof(TCHAR) == sizeof(char))
  1287. CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
  1288. contname, provname, ptype);
  1289. else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
  1290. /* above 'if' is optimization to minimize malloc-ations */
  1291. char *_contname = wide_to_asc((WCHAR *)contname);
  1292. char *_provname = wide_to_asc((WCHAR *)provname);
  1293. CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
  1294. _contname, _provname, ptype);
  1295. if (_provname)
  1296. OPENSSL_free(_provname);
  1297. if (_contname)
  1298. OPENSSL_free(_contname);
  1299. }
  1300. if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
  1301. dwFlags = CRYPT_MACHINE_KEYSET;
  1302. if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
  1303. CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
  1304. capi_addlasterror();
  1305. goto err;
  1306. }
  1307. if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
  1308. CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
  1309. capi_addlasterror();
  1310. CryptReleaseContext(key->hprov, 0);
  1311. goto err;
  1312. }
  1313. key->keyspec = keyspec;
  1314. key->pcert = NULL;
  1315. return key;
  1316. err:
  1317. OPENSSL_free(key);
  1318. return NULL;
  1319. }
  1320. static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
  1321. {
  1322. CAPI_KEY *key = NULL;
  1323. CRYPT_KEY_PROV_INFO *pinfo = NULL;
  1324. char *provname = NULL, *contname = NULL;
  1325. pinfo = capi_get_prov_info(ctx, cert);
  1326. if (!pinfo)
  1327. goto err;
  1328. if (sizeof(TCHAR) != sizeof(char))
  1329. key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
  1330. (TCHAR *)pinfo->pwszProvName,
  1331. pinfo->dwProvType, pinfo->dwKeySpec);
  1332. else {
  1333. provname = wide_to_asc(pinfo->pwszProvName);
  1334. contname = wide_to_asc(pinfo->pwszContainerName);
  1335. if (!provname || !contname)
  1336. goto err;
  1337. key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
  1338. pinfo->dwProvType, pinfo->dwKeySpec);
  1339. }
  1340. err:
  1341. if (pinfo)
  1342. OPENSSL_free(pinfo);
  1343. if (provname)
  1344. OPENSSL_free(provname);
  1345. if (contname)
  1346. OPENSSL_free(contname);
  1347. return key;
  1348. }
  1349. CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
  1350. {
  1351. PCCERT_CONTEXT cert;
  1352. HCERTSTORE hstore;
  1353. CAPI_KEY *key = NULL;
  1354. switch (ctx->lookup_method) {
  1355. case CAPI_LU_SUBSTR:
  1356. case CAPI_LU_FNAME:
  1357. hstore = capi_open_store(ctx, NULL);
  1358. if (!hstore)
  1359. return NULL;
  1360. cert = capi_find_cert(ctx, id, hstore);
  1361. if (cert) {
  1362. key = capi_get_cert_key(ctx, cert);
  1363. CertFreeCertificateContext(cert);
  1364. }
  1365. CertCloseStore(hstore, 0);
  1366. break;
  1367. case CAPI_LU_CONTNAME:
  1368. if (sizeof(TCHAR) != sizeof(char)) {
  1369. WCHAR *contname, *provname;
  1370. DWORD len;
  1371. if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
  1372. (contname = alloca(len * sizeof(WCHAR)),
  1373. MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
  1374. (len =
  1375. MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
  1376. && (provname =
  1377. alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
  1378. 0,
  1379. ctx->cspname,
  1380. -1,
  1381. provname,
  1382. len)))
  1383. key =
  1384. capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
  1385. ctx->csptype, ctx->keytype);
  1386. } else
  1387. key = capi_get_key(ctx, (TCHAR *)id,
  1388. (TCHAR *)ctx->cspname,
  1389. ctx->csptype, ctx->keytype);
  1390. break;
  1391. }
  1392. return key;
  1393. }
  1394. void capi_free_key(CAPI_KEY * key)
  1395. {
  1396. if (!key)
  1397. return;
  1398. CryptDestroyKey(key->key);
  1399. CryptReleaseContext(key->hprov, 0);
  1400. if (key->pcert)
  1401. CertFreeCertificateContext(key->pcert);
  1402. OPENSSL_free(key);
  1403. }
  1404. /* Initialize a CAPI_CTX structure */
  1405. static CAPI_CTX *capi_ctx_new()
  1406. {
  1407. CAPI_CTX *ctx;
  1408. ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
  1409. if (!ctx) {
  1410. CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
  1411. return NULL;
  1412. }
  1413. ctx->cspname = NULL;
  1414. ctx->csptype = PROV_RSA_FULL;
  1415. ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
  1416. ctx->keytype = AT_KEYEXCHANGE;
  1417. ctx->storename = NULL;
  1418. ctx->ssl_client_store = NULL;
  1419. ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
  1420. CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
  1421. ctx->lookup_method = CAPI_LU_SUBSTR;
  1422. ctx->debug_level = 0;
  1423. ctx->debug_file = NULL;
  1424. ctx->client_cert_select = cert_select_simple;
  1425. return ctx;
  1426. }
  1427. static void capi_ctx_free(CAPI_CTX * ctx)
  1428. {
  1429. CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
  1430. if (!ctx)
  1431. return;
  1432. if (ctx->cspname)
  1433. OPENSSL_free(ctx->cspname);
  1434. if (ctx->debug_file)
  1435. OPENSSL_free(ctx->debug_file);
  1436. if (ctx->storename)
  1437. OPENSSL_free(ctx->storename);
  1438. if (ctx->ssl_client_store)
  1439. OPENSSL_free(ctx->ssl_client_store);
  1440. OPENSSL_free(ctx);
  1441. }
  1442. static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
  1443. int check)
  1444. {
  1445. CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
  1446. if (check) {
  1447. HCRYPTPROV hprov;
  1448. LPTSTR name = NULL;
  1449. if (sizeof(TCHAR) != sizeof(char)) {
  1450. DWORD len;
  1451. if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
  1452. name = alloca(len * sizeof(WCHAR));
  1453. MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
  1454. }
  1455. } else
  1456. name = (TCHAR *)pname;
  1457. if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
  1458. CRYPT_VERIFYCONTEXT)) {
  1459. CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
  1460. CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
  1461. capi_addlasterror();
  1462. return 0;
  1463. }
  1464. CryptReleaseContext(hprov, 0);
  1465. }
  1466. if (ctx->cspname)
  1467. OPENSSL_free(ctx->cspname);
  1468. ctx->cspname = BUF_strdup(pname);
  1469. ctx->csptype = type;
  1470. return 1;
  1471. }
  1472. static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
  1473. {
  1474. LPSTR pname;
  1475. DWORD type;
  1476. int res;
  1477. if (capi_get_provname(ctx, &pname, &type, idx) != 1)
  1478. return 0;
  1479. res = capi_ctx_set_provname(ctx, pname, type, 0);
  1480. OPENSSL_free(pname);
  1481. return res;
  1482. }
  1483. static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
  1484. {
  1485. int i;
  1486. X509_NAME *nm;
  1487. /* Special case: empty list: match anything */
  1488. if (sk_X509_NAME_num(ca_dn) <= 0)
  1489. return 1;
  1490. for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
  1491. nm = sk_X509_NAME_value(ca_dn, i);
  1492. if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
  1493. return 1;
  1494. }
  1495. return 0;
  1496. }
  1497. static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
  1498. STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
  1499. EVP_PKEY **pkey, STACK_OF(X509) **pother,
  1500. UI_METHOD *ui_method,
  1501. void *callback_data)
  1502. {
  1503. STACK_OF(X509) *certs = NULL;
  1504. X509 *x;
  1505. char *storename;
  1506. const char *p;
  1507. int i, client_cert_idx;
  1508. HCERTSTORE hstore;
  1509. PCCERT_CONTEXT cert = NULL, excert = NULL;
  1510. CAPI_CTX *ctx;
  1511. CAPI_KEY *key;
  1512. ctx = ENGINE_get_ex_data(e, capi_idx);
  1513. *pcert = NULL;
  1514. *pkey = NULL;
  1515. storename = ctx->ssl_client_store;
  1516. if (!storename)
  1517. storename = "MY";
  1518. hstore = capi_open_store(ctx, storename);
  1519. if (!hstore)
  1520. return 0;
  1521. /* Enumerate all certificates collect any matches */
  1522. for (i = 0;; i++) {
  1523. cert = CertEnumCertificatesInStore(hstore, cert);
  1524. if (!cert)
  1525. break;
  1526. p = cert->pbCertEncoded;
  1527. x = d2i_X509(NULL, &p, cert->cbCertEncoded);
  1528. if (!x) {
  1529. CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
  1530. continue;
  1531. }
  1532. if (cert_issuer_match(ca_dn, x)
  1533. && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
  1534. key = capi_get_cert_key(ctx, cert);
  1535. if (!key) {
  1536. X509_free(x);
  1537. continue;
  1538. }
  1539. /*
  1540. * Match found: attach extra data to it so we can retrieve the
  1541. * key later.
  1542. */
  1543. excert = CertDuplicateCertificateContext(cert);
  1544. key->pcert = excert;
  1545. X509_set_ex_data(x, cert_capi_idx, key);
  1546. if (!certs)
  1547. certs = sk_X509_new_null();
  1548. sk_X509_push(certs, x);
  1549. } else
  1550. X509_free(x);
  1551. }
  1552. if (cert)
  1553. CertFreeCertificateContext(cert);
  1554. if (hstore)
  1555. CertCloseStore(hstore, 0);
  1556. if (!certs)
  1557. return 0;
  1558. /* Select the appropriate certificate */
  1559. client_cert_idx = ctx->client_cert_select(e, ssl, certs);
  1560. /* Set the selected certificate and free the rest */
  1561. for (i = 0; i < sk_X509_num(certs); i++) {
  1562. x = sk_X509_value(certs, i);
  1563. if (i == client_cert_idx)
  1564. *pcert = x;
  1565. else {
  1566. key = X509_get_ex_data(x, cert_capi_idx);
  1567. capi_free_key(key);
  1568. X509_free(x);
  1569. }
  1570. }
  1571. sk_X509_free(certs);
  1572. if (!*pcert)
  1573. return 0;
  1574. /* Setup key for selected certificate */
  1575. key = X509_get_ex_data(*pcert, cert_capi_idx);
  1576. *pkey = capi_get_pkey(e, key);
  1577. X509_set_ex_data(*pcert, cert_capi_idx, NULL);
  1578. return 1;
  1579. }
  1580. /* Simple client cert selection function: always select first */
  1581. static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
  1582. {
  1583. return 0;
  1584. }
  1585. # ifdef OPENSSL_CAPIENG_DIALOG
  1586. /*
  1587. * More complex cert selection function, using standard function
  1588. * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
  1589. */
  1590. /*
  1591. * Definitions which are in cryptuiapi.h but this is not present in older
  1592. * versions of headers.
  1593. */
  1594. # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
  1595. # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
  1596. # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
  1597. # endif
  1598. # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
  1599. # define dlg_prompt L"Select a certificate to use for authentication"
  1600. # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
  1601. |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
  1602. static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
  1603. {
  1604. X509 *x;
  1605. HCERTSTORE dstore;
  1606. PCCERT_CONTEXT cert;
  1607. CAPI_CTX *ctx;
  1608. CAPI_KEY *key;
  1609. HWND hwnd;
  1610. int i, idx = -1;
  1611. if (sk_X509_num(certs) == 1)
  1612. return 0;
  1613. ctx = ENGINE_get_ex_data(e, capi_idx);
  1614. /* Create an in memory store of certificates */
  1615. dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
  1616. CERT_STORE_CREATE_NEW_FLAG, NULL);
  1617. if (!dstore) {
  1618. CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
  1619. capi_addlasterror();
  1620. goto err;
  1621. }
  1622. /* Add all certificates to store */
  1623. for (i = 0; i < sk_X509_num(certs); i++) {
  1624. x = sk_X509_value(certs, i);
  1625. key = X509_get_ex_data(x, cert_capi_idx);
  1626. if (!CertAddCertificateContextToStore(dstore, key->pcert,
  1627. CERT_STORE_ADD_NEW, NULL)) {
  1628. CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
  1629. capi_addlasterror();
  1630. goto err;
  1631. }
  1632. }
  1633. hwnd = GetForegroundWindow();
  1634. if (!hwnd)
  1635. hwnd = GetActiveWindow();
  1636. if (!hwnd && ctx->getconswindow)
  1637. hwnd = ctx->getconswindow();
  1638. /* Call dialog to select one */
  1639. cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
  1640. dlg_columns, 0, NULL);
  1641. /* Find matching cert from list */
  1642. if (cert) {
  1643. for (i = 0; i < sk_X509_num(certs); i++) {
  1644. x = sk_X509_value(certs, i);
  1645. key = X509_get_ex_data(x, cert_capi_idx);
  1646. if (CertCompareCertificate
  1647. (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
  1648. key->pcert->pCertInfo)) {
  1649. idx = i;
  1650. break;
  1651. }
  1652. }
  1653. }
  1654. err:
  1655. if (dstore)
  1656. CertCloseStore(dstore, 0);
  1657. return idx;
  1658. }
  1659. # endif
  1660. #else /* !__COMPILE_CAPIENG */
  1661. # include <openssl/engine.h>
  1662. # ifndef OPENSSL_NO_DYNAMIC_ENGINE
  1663. OPENSSL_EXPORT
  1664. int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
  1665. OPENSSL_EXPORT
  1666. int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
  1667. {
  1668. return 0;
  1669. }
  1670. IMPLEMENT_DYNAMIC_CHECK_FN()
  1671. # else
  1672. void ENGINE_load_capi(void)
  1673. {
  1674. }
  1675. # endif
  1676. #endif