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