2
0

e_capi.c 55 KB

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