Remove X509_PAIR
[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();
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         if (ctx->storename)
364             OPENSSL_free(ctx->storename);
365         ctx->storename = BUF_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 = BUF_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     RSA_FLAG_SIGN_VER,          /* 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_SSLeay();
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)
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)
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(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)
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 || !rkey->n)
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()))
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 || !dkey->q || !dkey->g || !dkey->pub_key)
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()))
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, "%lx", 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     if (pubkey)
755         OPENSSL_free(pubkey);
756     if (!ret) {
757         if (rkey)
758             RSA_free(rkey);
759         if (dkey)
760             DSA_free(dkey);
761     }
762
763     return ret;
764
765  memerr:
766     CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
767     goto err;
768
769 }
770
771 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
772                                    UI_METHOD *ui_method, void *callback_data)
773 {
774     CAPI_CTX *ctx;
775     CAPI_KEY *key;
776     EVP_PKEY *ret;
777     ctx = ENGINE_get_ex_data(eng, capi_idx);
778
779     if (!ctx) {
780         CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
781         return NULL;
782     }
783
784     key = capi_find_key(ctx, key_id);
785
786     if (!key)
787         return NULL;
788
789     ret = capi_get_pkey(eng, key);
790
791     if (!ret)
792         capi_free_key(key);
793     return ret;
794
795 }
796
797 /* CryptoAPI RSA operations */
798
799 int capi_rsa_priv_enc(int flen, const unsigned char *from,
800                       unsigned char *to, RSA *rsa, int padding)
801 {
802     CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
803     return -1;
804 }
805
806 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
807                   unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
808 {
809     ALG_ID alg;
810     HCRYPTHASH hash;
811     DWORD slen;
812     unsigned int i;
813     int ret = -1;
814     CAPI_KEY *capi_key;
815     CAPI_CTX *ctx;
816
817     ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
818
819     CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
820
821     capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
822     if (!capi_key) {
823         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
824         return -1;
825     }
826 /* Convert the signature type to a CryptoAPI algorithm ID */
827     switch (dtype) {
828     case NID_sha256:
829         alg = CALG_SHA_256;
830         break;
831
832     case NID_sha384:
833         alg = CALG_SHA_384;
834         break;
835
836     case NID_sha512:
837         alg = CALG_SHA_512;
838         break;
839
840     case NID_sha1:
841         alg = CALG_SHA1;
842         break;
843
844     case NID_md5:
845         alg = CALG_MD5;
846         break;
847
848     case NID_md5_sha1:
849         alg = CALG_SSL3_SHAMD5;
850         break;
851     default:
852         {
853             char algstr[10];
854             BIO_snprintf(algstr, 10, "%lx", dtype);
855             CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
856             ERR_add_error_data(2, "NID=0x", algstr);
857             return -1;
858         }
859     }
860
861 /* Create the hash object */
862     if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
863         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
864         capi_addlasterror();
865         return -1;
866     }
867 /* Set the hash value to the value passed */
868
869     if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
870         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
871         capi_addlasterror();
872         goto err;
873     }
874
875 /* Finally sign it */
876     slen = RSA_size(rsa);
877     if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
878         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
879         capi_addlasterror();
880         goto err;
881     } else {
882         ret = 1;
883         /* Inplace byte reversal of signature */
884         for (i = 0; i < slen / 2; i++) {
885             unsigned char c;
886             c = sigret[i];
887             sigret[i] = sigret[slen - i - 1];
888             sigret[slen - i - 1] = c;
889         }
890         *siglen = slen;
891     }
892
893     /* Now cleanup */
894
895  err:
896     CryptDestroyHash(hash);
897
898     return ret;
899 }
900
901 int capi_rsa_priv_dec(int flen, const unsigned char *from,
902                       unsigned char *to, RSA *rsa, int padding)
903 {
904     int i;
905     unsigned char *tmpbuf;
906     CAPI_KEY *capi_key;
907     CAPI_CTX *ctx;
908     ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
909
910     CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
911
912     capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
913     if (!capi_key) {
914         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
915         return -1;
916     }
917
918     if (padding != RSA_PKCS1_PADDING) {
919         char errstr[10];
920         BIO_snprintf(errstr, 10, "%d", padding);
921         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
922         ERR_add_error_data(2, "padding=", errstr);
923         return -1;
924     }
925
926     /* Create temp reverse order version of input */
927     if (!(tmpbuf = OPENSSL_malloc(flen))) {
928         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
929         return -1;
930     }
931     for (i = 0; i < flen; i++)
932         tmpbuf[flen - i - 1] = from[i];
933
934     /* Finally decrypt it */
935     if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen)) {
936         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
937         capi_addlasterror();
938         OPENSSL_free(tmpbuf);
939         return -1;
940     } else
941         memcpy(to, tmpbuf, flen);
942
943     OPENSSL_free(tmpbuf);
944
945     return flen;
946 }
947
948 static int capi_rsa_free(RSA *rsa)
949 {
950     CAPI_KEY *capi_key;
951     capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
952     capi_free_key(capi_key);
953     RSA_set_ex_data(rsa, rsa_capi_idx, 0);
954     return 1;
955 }
956
957 /* CryptoAPI DSA operations */
958
959 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
960                                  DSA *dsa)
961 {
962     HCRYPTHASH hash;
963     DWORD slen;
964     DSA_SIG *ret = NULL;
965     CAPI_KEY *capi_key;
966     CAPI_CTX *ctx;
967     unsigned char csigbuf[40];
968
969     ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
970
971     CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
972
973     capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
974
975     if (!capi_key) {
976         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
977         return NULL;
978     }
979
980     if (dlen != 20) {
981         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
982         return NULL;
983     }
984
985     /* Create the hash object */
986     if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
987         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
988         capi_addlasterror();
989         return NULL;
990     }
991
992     /* Set the hash value to the value passed */
993     if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
994         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
995         capi_addlasterror();
996         goto err;
997     }
998
999     /* Finally sign it */
1000     slen = sizeof(csigbuf);
1001     if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
1002         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1003         capi_addlasterror();
1004         goto err;
1005     } else {
1006         ret = DSA_SIG_new();
1007         if (!ret)
1008             goto err;
1009         ret->r = BN_new();
1010         ret->s = BN_new();
1011         if (!ret->r || !ret->s)
1012             goto err;
1013         if (!lend_tobn(ret->r, csigbuf, 20)
1014             || !lend_tobn(ret->s, csigbuf + 20, 20)) {
1015             DSA_SIG_free(ret);
1016             ret = NULL;
1017             goto err;
1018         }
1019     }
1020
1021     /* Now cleanup */
1022
1023  err:
1024     OPENSSL_cleanse(csigbuf, 40);
1025     CryptDestroyHash(hash);
1026     return ret;
1027 }
1028
1029 static int capi_dsa_free(DSA *dsa)
1030 {
1031     CAPI_KEY *capi_key;
1032     capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1033     capi_free_key(capi_key);
1034     DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1035     return 1;
1036 }
1037
1038 static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
1039                         va_list argptr)
1040 {
1041     BIO *out;
1042
1043     if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1044         return;
1045     out = BIO_new_file(ctx->debug_file, "a+");
1046     if (out == NULL) {
1047         CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
1048         return;
1049     }
1050     BIO_vprintf(out, format, argptr);
1051     BIO_free(out);
1052 }
1053
1054 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
1055 {
1056     va_list args;
1057     va_start(args, format);
1058     capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1059     va_end(args);
1060 }
1061
1062 static void capi_addlasterror(void)
1063 {
1064     capi_adderror(GetLastError());
1065 }
1066
1067 static void capi_adderror(DWORD err)
1068 {
1069     char errstr[10];
1070     BIO_snprintf(errstr, 10, "%lX", err);
1071     ERR_add_error_data(2, "Error code= 0x", errstr);
1072 }
1073
1074 static char *wide_to_asc(LPCWSTR wstr)
1075 {
1076     char *str;
1077     int len_0, sz;
1078
1079     if (!wstr)
1080         return NULL;
1081     len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1082     sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1083     if (!sz) {
1084         CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1085         return NULL;
1086     }
1087     str = OPENSSL_malloc(sz);
1088     if (!str) {
1089         CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1090         return NULL;
1091     }
1092     if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1093         OPENSSL_free(str);
1094         CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1095         return NULL;
1096     }
1097     return str;
1098 }
1099
1100 static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
1101                              DWORD idx)
1102 {
1103     DWORD len, err;
1104     LPTSTR name;
1105     CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1106     if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1107         err = GetLastError();
1108         if (err == ERROR_NO_MORE_ITEMS)
1109             return 2;
1110         CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1111         capi_adderror(err);
1112         return 0;
1113     }
1114     name = OPENSSL_malloc(len);
1115     if (name == NULL) {
1116         CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1117         return 0;
1118     }
1119     if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1120         err = GetLastError();
1121         OPENSSL_free(name);
1122         if (err == ERROR_NO_MORE_ITEMS)
1123             return 2;
1124         CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1125         capi_adderror(err);
1126         return 0;
1127     }
1128     if (sizeof(TCHAR) != sizeof(char)) {
1129         *pname = wide_to_asc((WCHAR *)name);
1130         OPENSSL_free(name);
1131         if (*pname == NULL)
1132             return 0;
1133     } else
1134         *pname = (char *)name;
1135     CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1136                *ptype);
1137
1138     return 1;
1139 }
1140
1141 static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
1142 {
1143     DWORD idx, ptype;
1144     int ret;
1145     LPSTR provname = NULL;
1146     CAPI_trace(ctx, "capi_list_providers\n");
1147     BIO_printf(out, "Available CSPs:\n");
1148     for (idx = 0;; idx++) {
1149         ret = capi_get_provname(ctx, &provname, &ptype, idx);
1150         if (ret == 2)
1151             break;
1152         if (ret == 0)
1153             break;
1154         BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
1155         OPENSSL_free(provname);
1156     }
1157     return 1;
1158 }
1159
1160 static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
1161 {
1162     int ret = 1;
1163     HCRYPTPROV hprov;
1164     DWORD err, idx, flags, buflen = 0, clen;
1165     LPSTR cname;
1166     LPTSTR cspname = NULL;
1167
1168     CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1169                ctx->csptype);
1170     if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
1171         if ((clen =
1172              MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
1173             cspname = alloca(clen * sizeof(WCHAR));
1174             MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1175                                 clen);
1176         }
1177         if (!cspname) {
1178             CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1179             capi_addlasterror();
1180             return 0;
1181         }
1182     } else
1183         cspname = (TCHAR *)ctx->cspname;
1184     if (!CryptAcquireContext
1185         (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
1186         CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1187                 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1188         capi_addlasterror();
1189         return 0;
1190     }
1191     if (!CryptGetProvParam
1192         (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
1193         CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1194         capi_addlasterror();
1195         CryptReleaseContext(hprov, 0);
1196         return 0;
1197     }
1198     CAPI_trace(ctx, "Got max container len %d\n", buflen);
1199     if (buflen == 0)
1200         buflen = 1024;
1201     cname = OPENSSL_malloc(buflen);
1202     if (!cname) {
1203         CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1204         goto err;
1205     }
1206
1207     for (idx = 0;; idx++) {
1208         clen = buflen;
1209         cname[0] = 0;
1210
1211         if (idx == 0)
1212             flags = CRYPT_FIRST;
1213         else
1214             flags = 0;
1215         if (!CryptGetProvParam
1216             (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
1217             err = GetLastError();
1218             if (err == ERROR_NO_MORE_ITEMS)
1219                 goto done;
1220             CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1221             capi_adderror(err);
1222             goto err;
1223         }
1224         CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1225                    cname, clen, idx, flags);
1226         if (!cname[0] && (clen == buflen)) {
1227             CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1228             goto done;
1229         }
1230         BIO_printf(out, "%d. %s\n", idx, cname);
1231     }
1232  err:
1233
1234     ret = 0;
1235
1236  done:
1237     if (cname)
1238         OPENSSL_free(cname);
1239     CryptReleaseContext(hprov, 0);
1240
1241     return ret;
1242 }
1243
1244 CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1245 {
1246     DWORD len;
1247     CRYPT_KEY_PROV_INFO *pinfo;
1248
1249     if (!CertGetCertificateContextProperty
1250         (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1251         return NULL;
1252     pinfo = OPENSSL_malloc(len);
1253     if (!pinfo) {
1254         CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1255         return NULL;
1256     }
1257     if (!CertGetCertificateContextProperty
1258         (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
1259         CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1260                 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1261         capi_addlasterror();
1262         OPENSSL_free(pinfo);
1263         return NULL;
1264     }
1265     return pinfo;
1266 }
1267
1268 static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
1269                                 CRYPT_KEY_PROV_INFO * pinfo)
1270 {
1271     char *provname = NULL, *contname = NULL;
1272     if (!pinfo) {
1273         BIO_printf(out, "  No Private Key\n");
1274         return;
1275     }
1276     provname = wide_to_asc(pinfo->pwszProvName);
1277     contname = wide_to_asc(pinfo->pwszContainerName);
1278     if (!provname || !contname)
1279         goto err;
1280
1281     BIO_printf(out, "  Private Key Info:\n");
1282     BIO_printf(out, "    Provider Name:  %s, Provider Type %d\n", provname,
1283                pinfo->dwProvType);
1284     BIO_printf(out, "    Container Name: %s, Key Type %d\n", contname,
1285                pinfo->dwKeySpec);
1286  err:
1287     if (provname)
1288         OPENSSL_free(provname);
1289     if (contname)
1290         OPENSSL_free(contname);
1291 }
1292
1293 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 void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
1319 {
1320     X509 *x;
1321     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         if (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 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     CAPI_KEY *key;
1453     DWORD dwFlags = 0;
1454     key = OPENSSL_malloc(sizeof(CAPI_KEY));
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         if (_provname)
1468             OPENSSL_free(_provname);
1469         if (_contname)
1470             OPENSSL_free(_contname);
1471     }
1472     if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1473         dwFlags = CRYPT_MACHINE_KEYSET;
1474     if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
1475         CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1476         capi_addlasterror();
1477         goto err;
1478     }
1479     if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1480         CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1481         capi_addlasterror();
1482         CryptReleaseContext(key->hprov, 0);
1483         goto err;
1484     }
1485     key->keyspec = keyspec;
1486     key->pcert = NULL;
1487     return key;
1488
1489  err:
1490     OPENSSL_free(key);
1491     return NULL;
1492 }
1493
1494 static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1495 {
1496     CAPI_KEY *key = NULL;
1497     CRYPT_KEY_PROV_INFO *pinfo = NULL;
1498     char *provname = NULL, *contname = NULL;
1499     pinfo = capi_get_prov_info(ctx, cert);
1500     if (!pinfo)
1501         goto err;
1502     if (sizeof(TCHAR) != sizeof(char))
1503         key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1504                            (TCHAR *)pinfo->pwszProvName,
1505                            pinfo->dwProvType, pinfo->dwKeySpec);
1506     else {
1507         provname = wide_to_asc(pinfo->pwszProvName);
1508         contname = wide_to_asc(pinfo->pwszContainerName);
1509         if (!provname || !contname)
1510             goto err;
1511         key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1512                            pinfo->dwProvType, pinfo->dwKeySpec);
1513     }
1514
1515  err:
1516     if (pinfo)
1517         OPENSSL_free(pinfo);
1518     if (provname)
1519         OPENSSL_free(provname);
1520     if (contname)
1521         OPENSSL_free(contname);
1522     return key;
1523 }
1524
1525 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
1526 {
1527     PCCERT_CONTEXT cert;
1528     HCERTSTORE hstore;
1529     CAPI_KEY *key = NULL;
1530     switch (ctx->lookup_method) {
1531     case CAPI_LU_SUBSTR:
1532     case CAPI_LU_FNAME:
1533         hstore = capi_open_store(ctx, NULL);
1534         if (!hstore)
1535             return NULL;
1536         cert = capi_find_cert(ctx, id, hstore);
1537         if (cert) {
1538             key = capi_get_cert_key(ctx, cert);
1539             CertFreeCertificateContext(cert);
1540         }
1541         CertCloseStore(hstore, 0);
1542         break;
1543
1544     case CAPI_LU_CONTNAME:
1545         if (sizeof(TCHAR) != sizeof(char)) {
1546             WCHAR *contname, *provname;
1547             DWORD len;
1548
1549             if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1550                 (contname = alloca(len * sizeof(WCHAR)),
1551                  MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1552                 (len =
1553                  MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
1554                 && (provname =
1555                     alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
1556                                                                      0,
1557                                                                      ctx->cspname,
1558                                                                      -1,
1559                                                                      provname,
1560                                                                      len)))
1561                 key =
1562                     capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1563                                  ctx->csptype, ctx->keytype);
1564         } else
1565             key = capi_get_key(ctx, (TCHAR *)id,
1566                                (TCHAR *)ctx->cspname,
1567                                ctx->csptype, ctx->keytype);
1568         break;
1569     }
1570
1571     return key;
1572 }
1573
1574 void capi_free_key(CAPI_KEY * key)
1575 {
1576     if (!key)
1577         return;
1578     CryptDestroyKey(key->key);
1579     CryptReleaseContext(key->hprov, 0);
1580     if (key->pcert)
1581         CertFreeCertificateContext(key->pcert);
1582     OPENSSL_free(key);
1583 }
1584
1585 /* Initialize a CAPI_CTX structure */
1586
1587 static CAPI_CTX *capi_ctx_new()
1588 {
1589     CAPI_CTX *ctx;
1590     ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
1591     if (!ctx) {
1592         CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1593         return NULL;
1594     }
1595     ctx->cspname = NULL;
1596     ctx->csptype = PROV_RSA_FULL;
1597     ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1598     ctx->keytype = AT_KEYEXCHANGE;
1599     ctx->storename = NULL;
1600     ctx->ssl_client_store = NULL;
1601     ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1602         CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1603     ctx->lookup_method = CAPI_LU_SUBSTR;
1604     ctx->debug_level = 0;
1605     ctx->debug_file = NULL;
1606     ctx->client_cert_select = cert_select_simple;
1607     return ctx;
1608 }
1609
1610 static void capi_ctx_free(CAPI_CTX * ctx)
1611 {
1612     CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1613     if (!ctx)
1614         return;
1615     if (ctx->cspname)
1616         OPENSSL_free(ctx->cspname);
1617     if (ctx->debug_file)
1618         OPENSSL_free(ctx->debug_file);
1619     if (ctx->storename)
1620         OPENSSL_free(ctx->storename);
1621     if (ctx->ssl_client_store)
1622         OPENSSL_free(ctx->ssl_client_store);
1623     OPENSSL_free(ctx);
1624 }
1625
1626 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
1627                                  int check)
1628 {
1629     CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1630     if (check) {
1631         HCRYPTPROV hprov;
1632         LPTSTR name = NULL;
1633
1634         if (sizeof(TCHAR) != sizeof(char)) {
1635             DWORD len;
1636             if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1637                 name = alloca(len * sizeof(WCHAR));
1638                 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1639             }
1640         } else
1641             name = (TCHAR *)pname;
1642
1643         if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1644                                           CRYPT_VERIFYCONTEXT)) {
1645             CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1646                     CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1647             capi_addlasterror();
1648             return 0;
1649         }
1650         CryptReleaseContext(hprov, 0);
1651     }
1652     if (ctx->cspname)
1653         OPENSSL_free(ctx->cspname);
1654     ctx->cspname = BUF_strdup(pname);
1655     ctx->csptype = type;
1656     return 1;
1657 }
1658
1659 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
1660 {
1661     LPSTR pname;
1662     DWORD type;
1663     int res;
1664     if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1665         return 0;
1666     res = capi_ctx_set_provname(ctx, pname, type, 0);
1667     OPENSSL_free(pname);
1668     return res;
1669 }
1670
1671 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1672 {
1673     int i;
1674     X509_NAME *nm;
1675     /* Special case: empty list: match anything */
1676     if (sk_X509_NAME_num(ca_dn) <= 0)
1677         return 1;
1678     for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1679         nm = sk_X509_NAME_value(ca_dn, i);
1680         if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1681             return 1;
1682     }
1683     return 0;
1684 }
1685
1686 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1687                                      STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1688                                      EVP_PKEY **pkey, STACK_OF(X509) **pother,
1689                                      UI_METHOD *ui_method,
1690                                      void *callback_data)
1691 {
1692     STACK_OF(X509) *certs = NULL;
1693     X509 *x;
1694     char *storename;
1695     const char *p;
1696     int i, client_cert_idx;
1697     HCERTSTORE hstore;
1698     PCCERT_CONTEXT cert = NULL, excert = NULL;
1699     CAPI_CTX *ctx;
1700     CAPI_KEY *key;
1701     ctx = ENGINE_get_ex_data(e, capi_idx);
1702
1703     *pcert = NULL;
1704     *pkey = NULL;
1705
1706     storename = ctx->ssl_client_store;
1707     if (!storename)
1708         storename = "MY";
1709
1710     hstore = capi_open_store(ctx, storename);
1711     if (!hstore)
1712         return 0;
1713     /* Enumerate all certificates collect any matches */
1714     for (i = 0;; i++) {
1715         cert = CertEnumCertificatesInStore(hstore, cert);
1716         if (!cert)
1717             break;
1718         p = cert->pbCertEncoded;
1719         x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1720         if (!x) {
1721             CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1722             continue;
1723         }
1724         if (cert_issuer_match(ca_dn, x)
1725             && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1726             key = capi_get_cert_key(ctx, cert);
1727             if (!key) {
1728                 X509_free(x);
1729                 continue;
1730             }
1731             /*
1732              * Match found: attach extra data to it so we can retrieve the
1733              * key later.
1734              */
1735             excert = CertDuplicateCertificateContext(cert);
1736             key->pcert = excert;
1737             X509_set_ex_data(x, cert_capi_idx, key);
1738
1739             if (!certs)
1740                 certs = sk_X509_new_null();
1741
1742             sk_X509_push(certs, x);
1743         } else
1744             X509_free(x);
1745
1746     }
1747
1748     if (cert)
1749         CertFreeCertificateContext(cert);
1750     if (hstore)
1751         CertCloseStore(hstore, 0);
1752
1753     if (!certs)
1754         return 0;
1755
1756     /* Select the appropriate certificate */
1757
1758     client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1759
1760     /* Set the selected certificate and free the rest */
1761
1762     for (i = 0; i < sk_X509_num(certs); i++) {
1763         x = sk_X509_value(certs, i);
1764         if (i == client_cert_idx)
1765             *pcert = x;
1766         else {
1767             key = X509_get_ex_data(x, cert_capi_idx);
1768             capi_free_key(key);
1769             X509_free(x);
1770         }
1771     }
1772
1773     sk_X509_free(certs);
1774
1775     if (!*pcert)
1776         return 0;
1777
1778     /* Setup key for selected certificate */
1779
1780     key = X509_get_ex_data(*pcert, cert_capi_idx);
1781     *pkey = capi_get_pkey(e, key);
1782     X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1783
1784     return 1;
1785
1786 }
1787
1788 /* Simple client cert selection function: always select first */
1789
1790 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1791 {
1792     return 0;
1793 }
1794
1795 # ifdef OPENSSL_CAPIENG_DIALOG
1796
1797 /*
1798  * More complex cert selection function, using standard function
1799  * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1800  */
1801
1802 /*
1803  * Definitions which are in cryptuiapi.h but this is not present in older
1804  * versions of headers.
1805  */
1806
1807 #  ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1808 #   define CRYPTUI_SELECT_LOCATION_COLUMN                   0x000000010
1809 #   define CRYPTUI_SELECT_INTENDEDUSE_COLUMN                0x000000004
1810 #  endif
1811
1812 #  define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1813 #  define dlg_prompt L"Select a certificate to use for authentication"
1814 #  define dlg_columns      CRYPTUI_SELECT_LOCATION_COLUMN \
1815                         |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1816
1817 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1818 {
1819     X509 *x;
1820     HCERTSTORE dstore;
1821     PCCERT_CONTEXT cert;
1822     CAPI_CTX *ctx;
1823     CAPI_KEY *key;
1824     HWND hwnd;
1825     int i, idx = -1;
1826     if (sk_X509_num(certs) == 1)
1827         return 0;
1828     ctx = ENGINE_get_ex_data(e, capi_idx);
1829     /* Create an in memory store of certificates */
1830     dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1831                            CERT_STORE_CREATE_NEW_FLAG, NULL);
1832     if (!dstore) {
1833         CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1834         capi_addlasterror();
1835         goto err;
1836     }
1837     /* Add all certificates to store */
1838     for (i = 0; i < sk_X509_num(certs); i++) {
1839         x = sk_X509_value(certs, i);
1840         key = X509_get_ex_data(x, cert_capi_idx);
1841
1842         if (!CertAddCertificateContextToStore(dstore, key->pcert,
1843                                               CERT_STORE_ADD_NEW, NULL)) {
1844             CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1845             capi_addlasterror();
1846             goto err;
1847         }
1848
1849     }
1850     hwnd = GetForegroundWindow();
1851     if (!hwnd)
1852         hwnd = GetActiveWindow();
1853     if (!hwnd && ctx->getconswindow)
1854         hwnd = ctx->getconswindow();
1855     /* Call dialog to select one */
1856     cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1857                               dlg_columns, 0, NULL);
1858
1859     /* Find matching cert from list */
1860     if (cert) {
1861         for (i = 0; i < sk_X509_num(certs); i++) {
1862             x = sk_X509_value(certs, i);
1863             key = X509_get_ex_data(x, cert_capi_idx);
1864             if (CertCompareCertificate
1865                 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1866                  key->pcert->pCertInfo)) {
1867                 idx = i;
1868                 break;
1869             }
1870         }
1871     }
1872
1873  err:
1874     if (dstore)
1875         CertCloseStore(dstore, 0);
1876     return idx;
1877
1878 }
1879 # endif
1880
1881 #else                           /* !__COMPILE_CAPIENG */
1882 # include <openssl/engine.h>
1883 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1884 OPENSSL_EXPORT
1885     int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1886 OPENSSL_EXPORT
1887     int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1888 {
1889     return 0;
1890 }
1891
1892 IMPLEMENT_DYNAMIC_CHECK_FN()
1893 # else
1894 void ENGINE_load_capi(void)
1895 {
1896 }
1897 # endif
1898 #endif