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