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