2
0

e_capi.c 55 KB

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