4923eefa559e5b979b3398e55aa2f4df02013725
[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     LPSTR tmpstr;
299     if (capi_idx == -1) {
300         CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
301         return 0;
302     }
303     ctx = ENGINE_get_ex_data(e, capi_idx);
304     out = BIO_new_fp(stdout, BIO_NOCLOSE);
305     if (out == NULL) {
306         CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_FILE_OPEN_ERROR);
307         return 0;
308     }
309     switch (cmd) {
310     case CAPI_CMD_LIST_CSPS:
311         ret = capi_list_providers(ctx, out);
312         break;
313
314     case CAPI_CMD_LIST_CERTS:
315         ret = capi_list_certs(ctx, out, NULL);
316         break;
317
318     case CAPI_CMD_LOOKUP_CERT:
319         ret = capi_list_certs(ctx, out, p);
320         break;
321
322     case CAPI_CMD_LIST_CONTAINERS:
323         ret = capi_list_containers(ctx, out);
324         break;
325
326     case CAPI_CMD_STORE_NAME:
327         tmpstr = OPENSSL_strdup(p);
328         if (tmpstr != NULL) {
329             OPENSSL_free(ctx->storename);
330             ctx->storename = tmpstr;
331             CAPI_trace(ctx, "Setting store name to %s\n", p);
332         } else {
333             CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
334             ret = 0;
335         }
336         break;
337
338     case CAPI_CMD_STORE_FLAGS:
339         if (i & 1) {
340             ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
341             ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
342         } else {
343             ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
344             ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
345         }
346         CAPI_trace(ctx, "Setting flags to %d\n", i);
347         break;
348
349     case CAPI_CMD_DEBUG_LEVEL:
350         ctx->debug_level = (int)i;
351         CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
352         break;
353
354     case CAPI_CMD_DEBUG_FILE:
355         tmpstr = OPENSSL_strdup(p);
356         if (tmpstr != NULL) {
357             ctx->debug_file = tmpstr;
358             CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
359         } else {
360             CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
361             ret = 0;
362         }
363         break;
364
365     case CAPI_CMD_KEYTYPE:
366         ctx->keytype = i;
367         CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
368         break;
369
370     case CAPI_CMD_SET_CSP_IDX:
371         ret = capi_ctx_set_provname_idx(ctx, i);
372         break;
373
374     case CAPI_CMD_LIST_OPTIONS:
375         ctx->dump_flags = i;
376         break;
377
378     case CAPI_CMD_LOOKUP_METHOD:
379         if (i < 1 || i > 3) {
380             CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
381             BIO_free(out);
382             return 0;
383         }
384         ctx->lookup_method = i;
385         break;
386
387     case CAPI_CMD_SET_CSP_NAME:
388         ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
389         break;
390
391     case CAPI_CMD_SET_CSP_TYPE:
392         ctx->csptype = i;
393         break;
394
395     default:
396         CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
397         ret = 0;
398     }
399
400     BIO_free(out);
401     return ret;
402
403 }
404
405 static RSA_METHOD *capi_rsa_method = NULL;
406 # ifndef OPENSSL_NO_DSA
407 static DSA_METHOD *capi_dsa_method = NULL;
408 # endif
409
410 static int use_aes_csp = 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 we support AES CSP */
486
487     if (CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_AES,
488                             CRYPT_VERIFYCONTEXT)) {
489         use_aes_csp = 1;
490         CryptReleaseContext(hprov, 0);
491     }
492
493     return 1;
494
495  memerr:
496     CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
497     return 0;
498
499     return 1;
500 }
501
502 static int capi_destroy(ENGINE *e)
503 {
504     RSA_meth_free(capi_rsa_method);
505     capi_rsa_method = NULL;
506 # ifndef OPENSSL_NO_DSA
507     DSA_meth_free(capi_dsa_method);
508     capi_dsa_method = NULL;
509 # endif
510     ERR_unload_CAPI_strings();
511     return 1;
512 }
513
514 static int capi_finish(ENGINE *e)
515 {
516     CAPI_CTX *ctx;
517     ctx = ENGINE_get_ex_data(e, capi_idx);
518     capi_ctx_free(ctx);
519     ENGINE_set_ex_data(e, capi_idx, NULL);
520     return 1;
521 }
522
523 /*
524  * CryptoAPI key application data. This contains a handle to the private key
525  * container (for sign operations) and a handle to the key (for decrypt
526  * operations).
527  */
528
529 struct CAPI_KEY_st {
530     /* Associated certificate context (if any) */
531     PCCERT_CONTEXT pcert;
532     HCRYPTPROV hprov;
533     HCRYPTKEY key;
534     DWORD keyspec;
535 };
536
537 static int bind_capi(ENGINE *e)
538 {
539     capi_rsa_method = RSA_meth_new("CryptoAPI RSA method", 0);
540     if (capi_rsa_method == NULL)
541         return 0;
542 # ifndef OPENSSL_NO_DSA
543     capi_dsa_method = DSA_meth_new("CryptoAPI DSA method", 0);
544     if (capi_dsa_method == NULL)
545         goto memerr;
546 # endif
547     if (!ENGINE_set_id(e, engine_capi_id)
548         || !ENGINE_set_name(e, engine_capi_name)
549         || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
550         || !ENGINE_set_init_function(e, capi_init)
551         || !ENGINE_set_finish_function(e, capi_finish)
552         || !ENGINE_set_destroy_function(e, capi_destroy)
553         || !ENGINE_set_RSA(e, capi_rsa_method)
554 # ifndef OPENSSL_NO_DSA
555         || !ENGINE_set_DSA(e, capi_dsa_method)
556 # endif
557         || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
558         || !ENGINE_set_load_ssl_client_cert_function(e,
559                                                      capi_load_ssl_client_cert)
560         || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
561         || !ENGINE_set_ctrl_function(e, capi_ctrl))
562         goto memerr;
563     ERR_load_CAPI_strings();
564
565     return 1;
566  memerr:
567     RSA_meth_free(capi_rsa_method);
568     capi_rsa_method = NULL;
569 # ifndef OPENSSL_NO_DSA
570     DSA_meth_free(capi_dsa_method);
571     capi_dsa_method = NULL;
572 # endif
573     return 0;
574 }
575
576 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
577 static int bind_helper(ENGINE *e, const char *id)
578 {
579     if (id && (strcmp(id, engine_capi_id) != 0))
580         return 0;
581     if (!bind_capi(e))
582         return 0;
583     return 1;
584 }
585
586 IMPLEMENT_DYNAMIC_CHECK_FN()
587     IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
588 # else
589 static ENGINE *engine_capi(void)
590 {
591     ENGINE *ret = ENGINE_new();
592     if (ret == NULL)
593         return NULL;
594     if (!bind_capi(ret)) {
595         ENGINE_free(ret);
596         return NULL;
597     }
598     return ret;
599 }
600
601 void engine_load_capi_int(void)
602 {
603     /* Copied from eng_[openssl|dyn].c */
604     ENGINE *toadd = engine_capi();
605     if (!toadd)
606         return;
607     ENGINE_add(toadd);
608     ENGINE_free(toadd);
609     ERR_clear_error();
610 }
611 # endif
612
613 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
614 {
615     int i;
616     /*
617      * Reverse buffer in place: since this is a keyblob structure that will
618      * be freed up after conversion anyway it doesn't matter if we change
619      * it.
620      */
621     for (i = 0; i < binlen / 2; i++) {
622         unsigned char c;
623         c = bin[i];
624         bin[i] = bin[binlen - i - 1];
625         bin[binlen - i - 1] = c;
626     }
627
628     if (!BN_bin2bn(bin, binlen, bn))
629         return 0;
630     return 1;
631 }
632
633 /* Given a CAPI_KEY get an EVP_PKEY structure */
634
635 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
636 {
637     unsigned char *pubkey = NULL;
638     DWORD len;
639     BLOBHEADER *bh;
640     RSA *rkey = NULL;
641     DSA *dkey = NULL;
642     EVP_PKEY *ret = NULL;
643     if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
644         CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
645         capi_addlasterror();
646         return NULL;
647     }
648
649     pubkey = OPENSSL_malloc(len);
650
651     if (pubkey == NULL)
652         goto memerr;
653
654     if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
655         CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
656         capi_addlasterror();
657         goto err;
658     }
659
660     bh = (BLOBHEADER *) pubkey;
661     if (bh->bType != PUBLICKEYBLOB) {
662         CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
663         goto err;
664     }
665     if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
666         RSAPUBKEY *rp;
667         DWORD rsa_modlen;
668         BIGNUM *e = NULL, *n = NULL;
669         unsigned char *rsa_modulus;
670         rp = (RSAPUBKEY *) (bh + 1);
671         if (rp->magic != 0x31415352) {
672             char magstr[10];
673             BIO_snprintf(magstr, 10, "%lx", rp->magic);
674             CAPIerr(CAPI_F_CAPI_GET_PKEY,
675                     CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
676             ERR_add_error_data(2, "magic=0x", magstr);
677             goto err;
678         }
679         rsa_modulus = (unsigned char *)(rp + 1);
680         rkey = RSA_new_method(eng);
681         if (!rkey)
682             goto memerr;
683
684         e = BN_new();
685         n = BN_new();
686
687         if (e == NULL || n == NULL) {
688             BN_free(e);
689             BN_free(n);
690             goto memerr;
691         }
692
693         RSA_set0_key(rkey, n, e, NULL);
694
695         if (!BN_set_word(e, rp->pubexp))
696             goto memerr;
697
698         rsa_modlen = rp->bitlen / 8;
699         if (!lend_tobn(n, rsa_modulus, rsa_modlen))
700             goto memerr;
701
702         RSA_set_ex_data(rkey, rsa_capi_idx, key);
703
704         if ((ret = EVP_PKEY_new()) == NULL)
705             goto memerr;
706
707         EVP_PKEY_assign_RSA(ret, rkey);
708         rkey = NULL;
709
710 # ifndef OPENSSL_NO_DSA
711     } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
712         DSSPUBKEY *dp;
713         DWORD dsa_plen;
714         unsigned char *btmp;
715         BIGNUM *p, *q, *g, *pub_key;
716         dp = (DSSPUBKEY *) (bh + 1);
717         if (dp->magic != 0x31535344) {
718             char magstr[10];
719             BIO_snprintf(magstr, 10, "%lx", dp->magic);
720             CAPIerr(CAPI_F_CAPI_GET_PKEY,
721                     CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
722             ERR_add_error_data(2, "magic=0x", magstr);
723             goto err;
724         }
725         dsa_plen = dp->bitlen / 8;
726         btmp = (unsigned char *)(dp + 1);
727         dkey = DSA_new_method(eng);
728         if (!dkey)
729             goto memerr;
730         p = BN_new();
731         q = BN_new();
732         g = BN_new();
733         pub_key = BN_new();
734         if (p == NULL || q == NULL || g == NULL || pub_key == NULL) {
735             BN_free(p);
736             BN_free(q);
737             BN_free(g);
738             BN_free(pub_key);
739             goto memerr;
740         }
741         DSA_set0_pqg(dkey, p, q, g);
742         DSA_set0_key(dkey, pub_key, NULL);
743         if (!lend_tobn(p, btmp, dsa_plen))
744             goto memerr;
745         btmp += dsa_plen;
746         if (!lend_tobn(q, btmp, 20))
747             goto memerr;
748         btmp += 20;
749         if (!lend_tobn(g, btmp, dsa_plen))
750             goto memerr;
751         btmp += dsa_plen;
752         if (!lend_tobn(pub_key, btmp, dsa_plen))
753             goto memerr;
754         btmp += dsa_plen;
755
756         DSA_set_ex_data(dkey, dsa_capi_idx, key);
757
758         if ((ret = EVP_PKEY_new()) == NULL)
759             goto memerr;
760
761         EVP_PKEY_assign_DSA(ret, dkey);
762         dkey = NULL;
763 # endif
764     } else {
765         char algstr[10];
766         BIO_snprintf(algstr, 10, "%ux", bh->aiKeyAlg);
767         CAPIerr(CAPI_F_CAPI_GET_PKEY,
768                 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
769         ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
770         goto err;
771     }
772
773  err:
774     OPENSSL_free(pubkey);
775     if (!ret) {
776         RSA_free(rkey);
777 # ifndef OPENSSL_NO_DSA
778         DSA_free(dkey);
779 # endif
780     }
781
782     return ret;
783
784  memerr:
785     CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
786     goto err;
787
788 }
789
790 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
791                                    UI_METHOD *ui_method, void *callback_data)
792 {
793     CAPI_CTX *ctx;
794     CAPI_KEY *key;
795     EVP_PKEY *ret;
796     ctx = ENGINE_get_ex_data(eng, capi_idx);
797
798     if (!ctx) {
799         CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
800         return NULL;
801     }
802
803     key = capi_find_key(ctx, key_id);
804
805     if (!key)
806         return NULL;
807
808     ret = capi_get_pkey(eng, key);
809
810     if (!ret)
811         capi_free_key(key);
812     return ret;
813
814 }
815
816 /* CryptoAPI RSA operations */
817
818 int capi_rsa_priv_enc(int flen, const unsigned char *from,
819                       unsigned char *to, RSA *rsa, int padding)
820 {
821     CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
822     return -1;
823 }
824
825 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
826                   unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
827 {
828     ALG_ID alg;
829     HCRYPTHASH hash;
830     DWORD slen;
831     unsigned int i;
832     int ret = -1;
833     CAPI_KEY *capi_key;
834     CAPI_CTX *ctx;
835
836     ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
837
838     CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
839
840     capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
841     if (!capi_key) {
842         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
843         return -1;
844     }
845 /* Convert the signature type to a CryptoAPI algorithm ID */
846     switch (dtype) {
847     case NID_sha256:
848         alg = CALG_SHA_256;
849         break;
850
851     case NID_sha384:
852         alg = CALG_SHA_384;
853         break;
854
855     case NID_sha512:
856         alg = CALG_SHA_512;
857         break;
858
859     case NID_sha1:
860         alg = CALG_SHA1;
861         break;
862
863     case NID_md5:
864         alg = CALG_MD5;
865         break;
866
867     case NID_md5_sha1:
868         alg = CALG_SSL3_SHAMD5;
869         break;
870     default:
871         {
872             char algstr[10];
873             BIO_snprintf(algstr, 10, "%x", dtype);
874             CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
875             ERR_add_error_data(2, "NID=0x", algstr);
876             return -1;
877         }
878     }
879
880 /* Create the hash object */
881     if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
882         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
883         capi_addlasterror();
884         return -1;
885     }
886 /* Set the hash value to the value passed */
887
888     if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
889         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
890         capi_addlasterror();
891         goto err;
892     }
893
894 /* Finally sign it */
895     slen = RSA_size(rsa);
896     if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
897         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
898         capi_addlasterror();
899         goto err;
900     } else {
901         ret = 1;
902         /* Inplace byte reversal of signature */
903         for (i = 0; i < slen / 2; i++) {
904             unsigned char c;
905             c = sigret[i];
906             sigret[i] = sigret[slen - i - 1];
907             sigret[slen - i - 1] = c;
908         }
909         *siglen = slen;
910     }
911
912     /* Now cleanup */
913
914  err:
915     CryptDestroyHash(hash);
916
917     return ret;
918 }
919
920 int capi_rsa_priv_dec(int flen, const unsigned char *from,
921                       unsigned char *to, RSA *rsa, int padding)
922 {
923     int i;
924     unsigned char *tmpbuf;
925     CAPI_KEY *capi_key;
926     CAPI_CTX *ctx;
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     if (padding != RSA_PKCS1_PADDING) {
943         char errstr[10];
944         BIO_snprintf(errstr, 10, "%d", padding);
945         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
946         ERR_add_error_data(2, "padding=", errstr);
947         return -1;
948     }
949
950     /* Create temp reverse order version of input */
951     if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
952         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
953         return -1;
954     }
955     for (i = 0; i < flen; i++)
956         tmpbuf[flen - i - 1] = from[i];
957
958     /* Finally decrypt it */
959     dlen = flen;
960     if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &dlen)) {
961         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
962         capi_addlasterror();
963         OPENSSL_free(tmpbuf);
964         return -1;
965     } else
966         memcpy(to, tmpbuf, (flen = (int)dlen));
967
968     OPENSSL_free(tmpbuf);
969
970     return flen;
971 }
972
973 static int capi_rsa_free(RSA *rsa)
974 {
975     CAPI_KEY *capi_key;
976     capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
977     capi_free_key(capi_key);
978     RSA_set_ex_data(rsa, rsa_capi_idx, 0);
979     return 1;
980 }
981
982 # ifndef OPENSSL_NO_DSA
983 /* CryptoAPI DSA operations */
984
985 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
986                                  DSA *dsa)
987 {
988     HCRYPTHASH hash;
989     DWORD slen;
990     DSA_SIG *ret = NULL;
991     CAPI_KEY *capi_key;
992     CAPI_CTX *ctx;
993     unsigned char csigbuf[40];
994
995     ctx = ENGINE_get_ex_data(DSA_get0_engine(dsa), capi_idx);
996
997     CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
998
999     capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1000
1001     if (!capi_key) {
1002         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
1003         return NULL;
1004     }
1005
1006     if (dlen != 20) {
1007         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
1008         return NULL;
1009     }
1010
1011     /* Create the hash object */
1012     if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
1013         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
1014         capi_addlasterror();
1015         return NULL;
1016     }
1017
1018     /* Set the hash value to the value passed */
1019     if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
1020         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
1021         capi_addlasterror();
1022         goto err;
1023     }
1024
1025     /* Finally sign it */
1026     slen = sizeof(csigbuf);
1027     if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
1028         CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1029         capi_addlasterror();
1030         goto err;
1031     } else {
1032         BIGNUM *r = BN_new(), *s = BN_new();
1033
1034         if (r == NULL || s == NULL
1035             || !lend_tobn(r, csigbuf, 20)
1036             || !lend_tobn(s, csigbuf + 20, 20)
1037             || (ret = DSA_SIG_new()) == NULL) {
1038             BN_free(r); /* BN_free checks for BIGNUM * being NULL */
1039             BN_free(s);
1040             goto err;
1041         }
1042         DSA_SIG_set0(ret, r, s);
1043     }
1044
1045     /* Now cleanup */
1046
1047  err:
1048     OPENSSL_cleanse(csigbuf, 40);
1049     CryptDestroyHash(hash);
1050     return ret;
1051 }
1052
1053 static int capi_dsa_free(DSA *dsa)
1054 {
1055     CAPI_KEY *capi_key;
1056     capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1057     capi_free_key(capi_key);
1058     DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1059     return 1;
1060 }
1061 # endif
1062
1063 static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
1064                         va_list argptr)
1065 {
1066     BIO *out;
1067
1068     if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1069         return;
1070     out = BIO_new_file(ctx->debug_file, "a+");
1071     if (out == NULL) {
1072         CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
1073         return;
1074     }
1075     BIO_vprintf(out, format, argptr);
1076     BIO_free(out);
1077 }
1078
1079 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
1080 {
1081     va_list args;
1082     va_start(args, format);
1083     capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1084     va_end(args);
1085 }
1086
1087 static void capi_addlasterror(void)
1088 {
1089     capi_adderror(GetLastError());
1090 }
1091
1092 static void capi_adderror(DWORD err)
1093 {
1094     char errstr[10];
1095     BIO_snprintf(errstr, 10, "%lX", err);
1096     ERR_add_error_data(2, "Error code= 0x", errstr);
1097 }
1098
1099 static char *wide_to_asc(LPCWSTR wstr)
1100 {
1101     char *str;
1102     int len_0, sz;
1103
1104     if (!wstr)
1105         return NULL;
1106     len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1107     sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1108     if (!sz) {
1109         CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1110         return NULL;
1111     }
1112     str = OPENSSL_malloc(sz);
1113     if (str == NULL) {
1114         CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1115         return NULL;
1116     }
1117     if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1118         OPENSSL_free(str);
1119         CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1120         return NULL;
1121     }
1122     return str;
1123 }
1124
1125 static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
1126                              DWORD idx)
1127 {
1128     DWORD len, err;
1129     LPTSTR name;
1130     CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1131     if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1132         err = GetLastError();
1133         if (err == ERROR_NO_MORE_ITEMS)
1134             return 2;
1135         CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1136         capi_adderror(err);
1137         return 0;
1138     }
1139     name = OPENSSL_malloc(len);
1140     if (name == NULL) {
1141         CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1142         return 0;
1143     }
1144     if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1145         err = GetLastError();
1146         OPENSSL_free(name);
1147         if (err == ERROR_NO_MORE_ITEMS)
1148             return 2;
1149         CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1150         capi_adderror(err);
1151         return 0;
1152     }
1153     if (sizeof(TCHAR) != sizeof(char)) {
1154         *pname = wide_to_asc((WCHAR *)name);
1155         OPENSSL_free(name);
1156         if (*pname == NULL)
1157             return 0;
1158     } else
1159         *pname = (char *)name;
1160     CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1161                *ptype);
1162
1163     return 1;
1164 }
1165
1166 static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
1167 {
1168     DWORD idx, ptype;
1169     int ret;
1170     LPSTR provname = NULL;
1171     CAPI_trace(ctx, "capi_list_providers\n");
1172     BIO_printf(out, "Available CSPs:\n");
1173     for (idx = 0;; idx++) {
1174         ret = capi_get_provname(ctx, &provname, &ptype, idx);
1175         if (ret == 2)
1176             break;
1177         if (ret == 0)
1178             break;
1179         BIO_printf(out, "%lu. %s, type %lu\n", idx, provname, ptype);
1180         OPENSSL_free(provname);
1181     }
1182     return 1;
1183 }
1184
1185 static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
1186 {
1187     int ret = 1;
1188     HCRYPTPROV hprov;
1189     DWORD err, idx, flags, buflen = 0, clen;
1190     LPSTR cname;
1191     LPTSTR cspname = NULL;
1192
1193     CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1194                ctx->csptype);
1195     if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
1196         if ((clen =
1197              MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
1198             cspname = alloca(clen * sizeof(WCHAR));
1199             MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1200                                 clen);
1201         }
1202         if (!cspname) {
1203             CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1204             capi_addlasterror();
1205             return 0;
1206         }
1207     } else
1208         cspname = (TCHAR *)ctx->cspname;
1209     if (!CryptAcquireContext
1210         (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
1211         CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1212                 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1213         capi_addlasterror();
1214         return 0;
1215     }
1216     if (!CryptGetProvParam
1217         (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
1218         CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1219         capi_addlasterror();
1220         CryptReleaseContext(hprov, 0);
1221         return 0;
1222     }
1223     CAPI_trace(ctx, "Got max container len %d\n", buflen);
1224     if (buflen == 0)
1225         buflen = 1024;
1226     cname = OPENSSL_malloc(buflen);
1227     if (cname == NULL) {
1228         CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1229         goto err;
1230     }
1231
1232     for (idx = 0;; idx++) {
1233         clen = buflen;
1234         cname[0] = 0;
1235
1236         if (idx == 0)
1237             flags = CRYPT_FIRST;
1238         else
1239             flags = 0;
1240         if (!CryptGetProvParam
1241             (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
1242             err = GetLastError();
1243             if (err == ERROR_NO_MORE_ITEMS)
1244                 goto done;
1245             CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1246             capi_adderror(err);
1247             goto err;
1248         }
1249         CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1250                    cname, clen, idx, flags);
1251         if (!cname[0] && (clen == buflen)) {
1252             CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1253             goto done;
1254         }
1255         BIO_printf(out, "%lu. %s\n", idx, cname);
1256     }
1257  err:
1258
1259     ret = 0;
1260
1261  done:
1262     OPENSSL_free(cname);
1263     CryptReleaseContext(hprov, 0);
1264
1265     return ret;
1266 }
1267
1268 static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1269 {
1270     DWORD len;
1271     CRYPT_KEY_PROV_INFO *pinfo;
1272
1273     if (!CertGetCertificateContextProperty
1274         (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1275         return NULL;
1276     pinfo = OPENSSL_malloc(len);
1277     if (pinfo == NULL) {
1278         CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1279         return NULL;
1280     }
1281     if (!CertGetCertificateContextProperty
1282         (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
1283         CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1284                 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1285         capi_addlasterror();
1286         OPENSSL_free(pinfo);
1287         return NULL;
1288     }
1289     return pinfo;
1290 }
1291
1292 static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
1293                                 CRYPT_KEY_PROV_INFO * pinfo)
1294 {
1295     char *provname = NULL, *contname = NULL;
1296     if (!pinfo) {
1297         BIO_printf(out, "  No Private Key\n");
1298         return;
1299     }
1300     provname = wide_to_asc(pinfo->pwszProvName);
1301     contname = wide_to_asc(pinfo->pwszContainerName);
1302     if (!provname || !contname)
1303         goto err;
1304
1305     BIO_printf(out, "  Private Key Info:\n");
1306     BIO_printf(out, "    Provider Name:  %s, Provider Type %lu\n", provname,
1307                pinfo->dwProvType);
1308     BIO_printf(out, "    Container Name: %s, Key Type %lu\n", contname,
1309                pinfo->dwKeySpec);
1310  err:
1311     OPENSSL_free(provname);
1312     OPENSSL_free(contname);
1313 }
1314
1315 static char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1316 {
1317     LPWSTR wfname;
1318     DWORD dlen;
1319
1320     CAPI_trace(ctx, "capi_cert_get_fname\n");
1321     if (!CertGetCertificateContextProperty
1322         (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1323         return NULL;
1324     wfname = OPENSSL_malloc(dlen);
1325     if (wfname == NULL)
1326         return NULL;
1327     if (CertGetCertificateContextProperty
1328         (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
1329         char *fname = wide_to_asc(wfname);
1330         OPENSSL_free(wfname);
1331         return fname;
1332     }
1333     CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1334     capi_addlasterror();
1335
1336     OPENSSL_free(wfname);
1337     return NULL;
1338 }
1339
1340 static void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
1341 {
1342     X509 *x;
1343     const unsigned char *p;
1344     unsigned long flags = ctx->dump_flags;
1345     if (flags & CAPI_DMP_FNAME) {
1346         char *fname;
1347         fname = capi_cert_get_fname(ctx, cert);
1348         if (fname) {
1349             BIO_printf(out, "  Friendly Name \"%s\"\n", fname);
1350             OPENSSL_free(fname);
1351         } else
1352             BIO_printf(out, "  <No Friendly Name>\n");
1353     }
1354
1355     p = cert->pbCertEncoded;
1356     x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1357     if (!x)
1358         BIO_printf(out, "  <Can't parse certificate>\n");
1359     if (flags & CAPI_DMP_SUMMARY) {
1360         BIO_printf(out, "  Subject: ");
1361         X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1362         BIO_printf(out, "\n  Issuer: ");
1363         X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1364         BIO_printf(out, "\n");
1365     }
1366     if (flags & CAPI_DMP_FULL)
1367         X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
1368
1369     if (flags & CAPI_DMP_PKEYINFO) {
1370         CRYPT_KEY_PROV_INFO *pinfo;
1371         pinfo = capi_get_prov_info(ctx, cert);
1372         capi_dump_prov_info(ctx, out, pinfo);
1373         OPENSSL_free(pinfo);
1374     }
1375
1376     if (flags & CAPI_DMP_PEM)
1377         PEM_write_bio_X509(out, x);
1378     X509_free(x);
1379 }
1380
1381 static HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
1382 {
1383     HCERTSTORE hstore;
1384
1385     if (!storename)
1386         storename = ctx->storename;
1387     if (!storename)
1388         storename = "MY";
1389     CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1390
1391     hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1392                            ctx->store_flags, storename);
1393     if (!hstore) {
1394         CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1395         capi_addlasterror();
1396     }
1397     return hstore;
1398 }
1399
1400 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
1401 {
1402     char *storename;
1403     int idx;
1404     int ret = 1;
1405     HCERTSTORE hstore;
1406     PCCERT_CONTEXT cert = NULL;
1407
1408     storename = ctx->storename;
1409     if (!storename)
1410         storename = "MY";
1411     CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1412
1413     hstore = capi_open_store(ctx, storename);
1414     if (!hstore)
1415         return 0;
1416     if (id) {
1417         cert = capi_find_cert(ctx, id, hstore);
1418         if (!cert) {
1419             ret = 0;
1420             goto err;
1421         }
1422         capi_dump_cert(ctx, out, cert);
1423         CertFreeCertificateContext(cert);
1424     } else {
1425         for (idx = 0;; idx++) {
1426             cert = CertEnumCertificatesInStore(hstore, cert);
1427             if (!cert)
1428                 break;
1429             BIO_printf(out, "Certificate %d\n", idx);
1430             capi_dump_cert(ctx, out, cert);
1431         }
1432     }
1433  err:
1434     CertCloseStore(hstore, 0);
1435     return ret;
1436 }
1437
1438 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
1439                                      HCERTSTORE hstore)
1440 {
1441     PCCERT_CONTEXT cert = NULL;
1442     char *fname = NULL;
1443     int match;
1444     switch (ctx->lookup_method) {
1445     case CAPI_LU_SUBSTR:
1446         return CertFindCertificateInStore(hstore,
1447                                           X509_ASN_ENCODING, 0,
1448                                           CERT_FIND_SUBJECT_STR_A, id, NULL);
1449     case CAPI_LU_FNAME:
1450         for (;;) {
1451             cert = CertEnumCertificatesInStore(hstore, cert);
1452             if (!cert)
1453                 return NULL;
1454             fname = capi_cert_get_fname(ctx, cert);
1455             if (fname) {
1456                 if (strcmp(fname, id))
1457                     match = 0;
1458                 else
1459                     match = 1;
1460                 OPENSSL_free(fname);
1461                 if (match)
1462                     return cert;
1463             }
1464         }
1465     default:
1466         return NULL;
1467     }
1468 }
1469
1470 static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
1471                               TCHAR *provname, DWORD ptype, DWORD keyspec)
1472 {
1473     DWORD dwFlags = 0;
1474     CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
1475
1476     if (key == NULL)
1477         return NULL;
1478     /* If PROV_RSA_AES supported use it instead */
1479     if (ptype == PROV_RSA_FULL && use_aes_csp) {
1480         provname = NULL;
1481         ptype = PROV_RSA_AES;
1482         CAPI_trace(ctx, "capi_get_key, contname=%s, RSA_AES_CSP\n", contname);
1483     } else if (sizeof(TCHAR) == sizeof(char)) {
1484         CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1485                    contname, provname, ptype);
1486     } else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
1487         /* above 'if' is optimization to minimize malloc-ations */
1488         char *_contname = wide_to_asc((WCHAR *)contname);
1489         char *_provname = wide_to_asc((WCHAR *)provname);
1490
1491         CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1492                    _contname, _provname, ptype);
1493         OPENSSL_free(_provname);
1494         OPENSSL_free(_contname);
1495     }
1496     if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1497         dwFlags = CRYPT_MACHINE_KEYSET;
1498     if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
1499         CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1500         capi_addlasterror();
1501         goto err;
1502     }
1503     if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1504         CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1505         capi_addlasterror();
1506         CryptReleaseContext(key->hprov, 0);
1507         goto err;
1508     }
1509     key->keyspec = keyspec;
1510     key->pcert = NULL;
1511     return key;
1512
1513  err:
1514     OPENSSL_free(key);
1515     return NULL;
1516 }
1517
1518 static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1519 {
1520     CAPI_KEY *key = NULL;
1521     CRYPT_KEY_PROV_INFO *pinfo = NULL;
1522     char *provname = NULL, *contname = NULL;
1523     pinfo = capi_get_prov_info(ctx, cert);
1524     if (!pinfo)
1525         goto err;
1526     if (sizeof(TCHAR) != sizeof(char))
1527         key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1528                            (TCHAR *)pinfo->pwszProvName,
1529                            pinfo->dwProvType, pinfo->dwKeySpec);
1530     else {
1531         provname = wide_to_asc(pinfo->pwszProvName);
1532         contname = wide_to_asc(pinfo->pwszContainerName);
1533         if (!provname || !contname)
1534             goto err;
1535         key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1536                            pinfo->dwProvType, pinfo->dwKeySpec);
1537     }
1538
1539  err:
1540     OPENSSL_free(pinfo);
1541     OPENSSL_free(provname);
1542     OPENSSL_free(contname);
1543     return key;
1544 }
1545
1546 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
1547 {
1548     PCCERT_CONTEXT cert;
1549     HCERTSTORE hstore;
1550     CAPI_KEY *key = NULL;
1551     switch (ctx->lookup_method) {
1552     case CAPI_LU_SUBSTR:
1553     case CAPI_LU_FNAME:
1554         hstore = capi_open_store(ctx, NULL);
1555         if (!hstore)
1556             return NULL;
1557         cert = capi_find_cert(ctx, id, hstore);
1558         if (cert) {
1559             key = capi_get_cert_key(ctx, cert);
1560             CertFreeCertificateContext(cert);
1561         }
1562         CertCloseStore(hstore, 0);
1563         break;
1564
1565     case CAPI_LU_CONTNAME:
1566         if (sizeof(TCHAR) != sizeof(char)) {
1567             WCHAR *contname, *provname;
1568             DWORD len;
1569
1570             if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1571                 (contname = alloca(len * sizeof(WCHAR)),
1572                  MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1573                 (len =
1574                  MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
1575                 && (provname =
1576                     alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
1577                                                                      0,
1578                                                                      ctx->cspname,
1579                                                                      -1,
1580                                                                      provname,
1581                                                                      len)))
1582                 key =
1583                     capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1584                                  ctx->csptype, ctx->keytype);
1585         } else
1586             key = capi_get_key(ctx, (TCHAR *)id,
1587                                (TCHAR *)ctx->cspname,
1588                                ctx->csptype, ctx->keytype);
1589         break;
1590     }
1591
1592     return key;
1593 }
1594
1595 void capi_free_key(CAPI_KEY * key)
1596 {
1597     if (!key)
1598         return;
1599     CryptDestroyKey(key->key);
1600     CryptReleaseContext(key->hprov, 0);
1601     if (key->pcert)
1602         CertFreeCertificateContext(key->pcert);
1603     OPENSSL_free(key);
1604 }
1605
1606 /* Initialize a CAPI_CTX structure */
1607
1608 static CAPI_CTX *capi_ctx_new(void)
1609 {
1610     CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
1611
1612     if (ctx == NULL) {
1613         CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1614         return NULL;
1615     }
1616     ctx->csptype = PROV_RSA_FULL;
1617     ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1618     ctx->keytype = AT_KEYEXCHANGE;
1619     ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1620         CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1621     ctx->lookup_method = CAPI_LU_SUBSTR;
1622     ctx->client_cert_select = cert_select_simple;
1623     return ctx;
1624 }
1625
1626 static void capi_ctx_free(CAPI_CTX * ctx)
1627 {
1628     CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1629     if (!ctx)
1630         return;
1631     OPENSSL_free(ctx->cspname);
1632     OPENSSL_free(ctx->debug_file);
1633     OPENSSL_free(ctx->storename);
1634     OPENSSL_free(ctx->ssl_client_store);
1635     OPENSSL_free(ctx);
1636 }
1637
1638 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
1639                                  int check)
1640 {
1641     LPSTR tmpcspname;
1642
1643     CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1644     if (check) {
1645         HCRYPTPROV hprov;
1646         LPTSTR name = NULL;
1647
1648         if (sizeof(TCHAR) != sizeof(char)) {
1649             DWORD len;
1650             if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1651                 name = alloca(len * sizeof(WCHAR));
1652                 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1653             }
1654         } else
1655             name = (TCHAR *)pname;
1656
1657         if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1658                                           CRYPT_VERIFYCONTEXT)) {
1659             CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1660                     CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1661             capi_addlasterror();
1662             return 0;
1663         }
1664         CryptReleaseContext(hprov, 0);
1665     }
1666     tmpcspname = OPENSSL_strdup(pname);
1667     if (tmpcspname == NULL) {
1668         CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, ERR_R_MALLOC_FAILURE);
1669         return 0;
1670     }
1671     OPENSSL_free(ctx->cspname);
1672     ctx->cspname = tmpcspname;
1673     ctx->csptype = type;
1674     return 1;
1675 }
1676
1677 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
1678 {
1679     LPSTR pname;
1680     DWORD type;
1681     int res;
1682     if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1683         return 0;
1684     res = capi_ctx_set_provname(ctx, pname, type, 0);
1685     OPENSSL_free(pname);
1686     return res;
1687 }
1688
1689 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1690 {
1691     int i;
1692     X509_NAME *nm;
1693     /* Special case: empty list: match anything */
1694     if (sk_X509_NAME_num(ca_dn) <= 0)
1695         return 1;
1696     for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1697         nm = sk_X509_NAME_value(ca_dn, i);
1698         if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1699             return 1;
1700     }
1701     return 0;
1702 }
1703
1704 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1705                                      STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1706                                      EVP_PKEY **pkey, STACK_OF(X509) **pother,
1707                                      UI_METHOD *ui_method,
1708                                      void *callback_data)
1709 {
1710     STACK_OF(X509) *certs = NULL;
1711     X509 *x;
1712     char *storename;
1713     const unsigned char *p;
1714     int i, client_cert_idx;
1715     HCERTSTORE hstore;
1716     PCCERT_CONTEXT cert = NULL, excert = NULL;
1717     CAPI_CTX *ctx;
1718     CAPI_KEY *key;
1719     ctx = ENGINE_get_ex_data(e, capi_idx);
1720
1721     *pcert = NULL;
1722     *pkey = NULL;
1723
1724     storename = ctx->ssl_client_store;
1725     if (!storename)
1726         storename = "MY";
1727
1728     hstore = capi_open_store(ctx, storename);
1729     if (!hstore)
1730         return 0;
1731     /* Enumerate all certificates collect any matches */
1732     for (i = 0;; i++) {
1733         cert = CertEnumCertificatesInStore(hstore, cert);
1734         if (!cert)
1735             break;
1736         p = cert->pbCertEncoded;
1737         x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1738         if (!x) {
1739             CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1740             continue;
1741         }
1742         if (cert_issuer_match(ca_dn, x)
1743             && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1744             key = capi_get_cert_key(ctx, cert);
1745             if (!key) {
1746                 X509_free(x);
1747                 continue;
1748             }
1749             /*
1750              * Match found: attach extra data to it so we can retrieve the
1751              * key later.
1752              */
1753             excert = CertDuplicateCertificateContext(cert);
1754             key->pcert = excert;
1755             X509_set_ex_data(x, cert_capi_idx, key);
1756
1757             if (!certs)
1758                 certs = sk_X509_new_null();
1759
1760             sk_X509_push(certs, x);
1761         } else
1762             X509_free(x);
1763
1764     }
1765
1766     if (cert)
1767         CertFreeCertificateContext(cert);
1768     if (hstore)
1769         CertCloseStore(hstore, 0);
1770
1771     if (!certs)
1772         return 0;
1773
1774     /* Select the appropriate certificate */
1775
1776     client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1777
1778     /* Set the selected certificate and free the rest */
1779
1780     for (i = 0; i < sk_X509_num(certs); i++) {
1781         x = sk_X509_value(certs, i);
1782         if (i == client_cert_idx)
1783             *pcert = x;
1784         else {
1785             key = X509_get_ex_data(x, cert_capi_idx);
1786             capi_free_key(key);
1787             X509_free(x);
1788         }
1789     }
1790
1791     sk_X509_free(certs);
1792
1793     if (!*pcert)
1794         return 0;
1795
1796     /* Setup key for selected certificate */
1797
1798     key = X509_get_ex_data(*pcert, cert_capi_idx);
1799     *pkey = capi_get_pkey(e, key);
1800     X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1801
1802     return 1;
1803
1804 }
1805
1806 /* Simple client cert selection function: always select first */
1807
1808 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1809 {
1810     return 0;
1811 }
1812
1813 # ifdef OPENSSL_CAPIENG_DIALOG
1814
1815 /*
1816  * More complex cert selection function, using standard function
1817  * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1818  */
1819
1820 /*
1821  * Definitions which are in cryptuiapi.h but this is not present in older
1822  * versions of headers.
1823  */
1824
1825 #  ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1826 #   define CRYPTUI_SELECT_LOCATION_COLUMN                   0x000000010
1827 #   define CRYPTUI_SELECT_INTENDEDUSE_COLUMN                0x000000004
1828 #  endif
1829
1830 #  define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1831 #  define dlg_prompt L"Select a certificate to use for authentication"
1832 #  define dlg_columns      CRYPTUI_SELECT_LOCATION_COLUMN \
1833                         |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1834
1835 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1836 {
1837     X509 *x;
1838     HCERTSTORE dstore;
1839     PCCERT_CONTEXT cert;
1840     CAPI_CTX *ctx;
1841     CAPI_KEY *key;
1842     HWND hwnd;
1843     int i, idx = -1;
1844     if (sk_X509_num(certs) == 1)
1845         return 0;
1846     ctx = ENGINE_get_ex_data(e, capi_idx);
1847     /* Create an in memory store of certificates */
1848     dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1849                            CERT_STORE_CREATE_NEW_FLAG, NULL);
1850     if (!dstore) {
1851         CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1852         capi_addlasterror();
1853         goto err;
1854     }
1855     /* Add all certificates to store */
1856     for (i = 0; i < sk_X509_num(certs); i++) {
1857         x = sk_X509_value(certs, i);
1858         key = X509_get_ex_data(x, cert_capi_idx);
1859
1860         if (!CertAddCertificateContextToStore(dstore, key->pcert,
1861                                               CERT_STORE_ADD_NEW, NULL)) {
1862             CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1863             capi_addlasterror();
1864             goto err;
1865         }
1866
1867     }
1868     hwnd = GetForegroundWindow();
1869     if (!hwnd)
1870         hwnd = GetActiveWindow();
1871     if (!hwnd && ctx->getconswindow)
1872         hwnd = ctx->getconswindow();
1873     /* Call dialog to select one */
1874     cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1875                               dlg_columns, 0, NULL);
1876
1877     /* Find matching cert from list */
1878     if (cert) {
1879         for (i = 0; i < sk_X509_num(certs); i++) {
1880             x = sk_X509_value(certs, i);
1881             key = X509_get_ex_data(x, cert_capi_idx);
1882             if (CertCompareCertificate
1883                 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1884                  key->pcert->pCertInfo)) {
1885                 idx = i;
1886                 break;
1887             }
1888         }
1889     }
1890
1891  err:
1892     if (dstore)
1893         CertCloseStore(dstore, 0);
1894     return idx;
1895
1896 }
1897 # endif
1898
1899 #else                           /* !__COMPILE_CAPIENG */
1900 # include <openssl/engine.h>
1901 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1902 OPENSSL_EXPORT
1903     int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1904 OPENSSL_EXPORT
1905     int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1906 {
1907     return 0;
1908 }
1909
1910 IMPLEMENT_DYNAMIC_CHECK_FN()
1911 # else
1912 void engine_load_capi_int(void);
1913 void engine_load_capi_int(void)
1914 {
1915 }
1916 # endif
1917 #endif