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