e_capi.c 55 KB

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