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