e_capi.c 54 KB

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