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