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