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