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