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