e_capi.c 54 KB

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