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