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