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