e_capi.c 55 KB

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