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