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