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