2 * Copyright 2008-2020 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* We need to use some deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
15 # define _WIN32_WINNT 0x0400
18 # include <wincrypt.h>
25 # define alloca _alloca
28 # include <openssl/crypto.h>
30 # ifndef OPENSSL_NO_CAPIENG
32 # include <openssl/buffer.h>
33 # include <openssl/bn.h>
34 # include <openssl/rsa.h>
35 # include <openssl/dsa.h>
38 DEFINE_STACK_OF(X509_NAME)
41 * This module uses several "new" interfaces, among which is
42 * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is
43 * one of possible values you can pass to function in question. By
44 * checking if it's defined we can see if wincrypt.h and accompanying
45 * crypt32.lib are in shape. The native MingW32 headers up to and
46 * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the
47 * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG,
48 * so we check for these too and avoid compiling.
49 * Yes, it's rather "weak" test and if compilation fails,
50 * then re-configure with -DOPENSSL_NO_CAPIENG.
52 # if defined(CERT_KEY_PROV_INFO_PROP_ID) && \
53 defined(CERT_STORE_PROV_SYSTEM_A) && \
54 defined(CERT_STORE_READONLY_FLAG)
55 # define __COMPILE_CAPIENG
56 # endif /* CERT_KEY_PROV_INFO_PROP_ID */
57 # endif /* OPENSSL_NO_CAPIENG */
60 #ifdef __COMPILE_CAPIENG
62 # undef X509_EXTENSIONS
64 /* Definitions which may be missing from earlier version of headers */
65 # ifndef CERT_STORE_OPEN_EXISTING_FLAG
66 # define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
69 # ifndef CERT_STORE_CREATE_NEW_FLAG
70 # define CERT_STORE_CREATE_NEW_FLAG 0x00002000
73 # ifndef CERT_SYSTEM_STORE_CURRENT_USER
74 # define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000
77 # ifndef ALG_SID_SHA_256
78 # define ALG_SID_SHA_256 12
80 # ifndef ALG_SID_SHA_384
81 # define ALG_SID_SHA_384 13
83 # ifndef ALG_SID_SHA_512
84 # define ALG_SID_SHA_512 14
88 # define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
91 # define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
94 # define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
98 # define PROV_RSA_AES 24
101 # include <openssl/engine.h>
102 # include <openssl/pem.h>
103 # include <openssl/x509v3.h>
105 # include "e_capi_err.h"
106 # include "e_capi_err.c"
108 static const char *engine_capi_id = "capi";
109 static const char *engine_capi_name = "CryptoAPI ENGINE";
111 typedef struct CAPI_CTX_st CAPI_CTX;
112 typedef struct CAPI_KEY_st CAPI_KEY;
114 static void capi_addlasterror(void);
115 static void capi_adderror(DWORD err);
117 static void CAPI_trace(CAPI_CTX *ctx, char *format, ...);
119 static int capi_list_providers(CAPI_CTX *ctx, BIO *out);
120 static int capi_list_containers(CAPI_CTX *ctx, BIO *out);
121 int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *storename);
122 void capi_free_key(CAPI_KEY *key);
124 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id,
127 CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id);
129 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
130 UI_METHOD *ui_method, void *callback_data);
131 static int capi_rsa_sign(int dtype, const unsigned char *m,
132 unsigned int m_len, unsigned char *sigret,
133 unsigned int *siglen, const RSA *rsa);
134 static int capi_rsa_priv_enc(int flen, const unsigned char *from,
135 unsigned char *to, RSA *rsa, int padding);
136 static int capi_rsa_priv_dec(int flen, const unsigned char *from,
137 unsigned char *to, RSA *rsa, int padding);
138 static int capi_rsa_free(RSA *rsa);
140 # ifndef OPENSSL_NO_DSA
141 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
143 static int capi_dsa_free(DSA *dsa);
146 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
147 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
148 EVP_PKEY **pkey, STACK_OF(X509) **pother,
149 UI_METHOD *ui_method,
150 void *callback_data);
152 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
153 # ifdef OPENSSL_CAPIENG_DIALOG
154 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
157 void engine_load_capi_int(void);
159 typedef PCCERT_CONTEXT(WINAPI *CERTDLG)(HCERTSTORE, HWND, LPCWSTR,
160 LPCWSTR, DWORD, DWORD, void *);
161 typedef HWND(WINAPI *GETCONSWIN)(void);
164 * This structure contains CAPI ENGINE specific data: it contains various
165 * global options and affects how other functions behave.
168 # define CAPI_DBG_TRACE 2
169 # define CAPI_DBG_ERROR 1
174 /* Parameters to use for container lookup */
178 /* Certificate store name to use */
180 LPSTR ssl_client_store;
181 /* System store flags */
183 /* Lookup string meanings in load_private_key */
184 # define CAPI_LU_SUBSTR 1 /* Substring of subject: uses "storename" */
185 # define CAPI_LU_FNAME 2 /* Friendly name: uses storename */
186 # define CAPI_LU_CONTNAME 3 /* Container name: uses cspname, keytype */
188 /* Info to dump with dumpcerts option */
189 # define CAPI_DMP_SUMMARY 0x1 /* Issuer and serial name strings */
190 # define CAPI_DMP_FNAME 0x2 /* Friendly name */
191 # define CAPI_DMP_FULL 0x4 /* Full X509_print dump */
192 # define CAPI_DMP_PEM 0x8 /* Dump PEM format certificate */
193 # define CAPI_DMP_PSKEY 0x10 /* Dump pseudo key (if possible) */
194 # define CAPI_DMP_PKEYINFO 0x20 /* Dump key info (if possible) */
196 int (*client_cert_select) (ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
197 CERTDLG certselectdlg;
198 GETCONSWIN getconswindow;
201 static CAPI_CTX *capi_ctx_new(void);
202 static void capi_ctx_free(CAPI_CTX *ctx);
203 static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type,
205 static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx);
207 # define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
208 # define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
209 # define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
210 # define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
211 # define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
212 # define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
213 # define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
214 # define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
215 # define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
216 # define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
217 # define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
218 # define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
219 # define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
220 # define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
222 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
223 {CAPI_CMD_LIST_CERTS,
225 "List all certificates in store",
226 ENGINE_CMD_FLAG_NO_INPUT},
227 {CAPI_CMD_LOOKUP_CERT,
229 "Lookup and output certificates",
230 ENGINE_CMD_FLAG_STRING},
231 {CAPI_CMD_DEBUG_LEVEL,
233 "debug level (1=errors, 2=trace)",
234 ENGINE_CMD_FLAG_NUMERIC},
235 {CAPI_CMD_DEBUG_FILE,
237 "debugging filename)",
238 ENGINE_CMD_FLAG_STRING},
241 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
242 ENGINE_CMD_FLAG_NUMERIC},
246 ENGINE_CMD_FLAG_NO_INPUT},
247 {CAPI_CMD_SET_CSP_IDX,
250 ENGINE_CMD_FLAG_NUMERIC},
251 {CAPI_CMD_SET_CSP_NAME,
253 "Set CSP name, (default CSP used if not specified)",
254 ENGINE_CMD_FLAG_STRING},
255 {CAPI_CMD_SET_CSP_TYPE,
257 "Set CSP type, (default RSA_PROV_FULL)",
258 ENGINE_CMD_FLAG_NUMERIC},
259 {CAPI_CMD_LIST_CONTAINERS,
261 "list container names",
262 ENGINE_CMD_FLAG_NO_INPUT},
263 {CAPI_CMD_LIST_OPTIONS,
265 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
266 "32=private key info)",
267 ENGINE_CMD_FLAG_NUMERIC},
268 {CAPI_CMD_LOOKUP_METHOD,
270 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
271 ENGINE_CMD_FLAG_NUMERIC},
272 {CAPI_CMD_STORE_NAME,
274 "certificate store name, default \"MY\"",
275 ENGINE_CMD_FLAG_STRING},
276 {CAPI_CMD_STORE_FLAGS,
278 "Certificate store flags: 1 = system store",
279 ENGINE_CMD_FLAG_NUMERIC},
284 static int capi_idx = -1;
285 static int rsa_capi_idx = -1;
286 static int dsa_capi_idx = -1;
287 static int cert_capi_idx = -1;
289 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
295 if (capi_idx == -1) {
296 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
299 ctx = ENGINE_get_ex_data(e, capi_idx);
300 out = BIO_new_fp(stdout, BIO_NOCLOSE);
302 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_FILE_OPEN_ERROR);
306 case CAPI_CMD_LIST_CSPS:
307 ret = capi_list_providers(ctx, out);
310 case CAPI_CMD_LIST_CERTS:
311 ret = capi_list_certs(ctx, out, NULL);
314 case CAPI_CMD_LOOKUP_CERT:
315 ret = capi_list_certs(ctx, out, p);
318 case CAPI_CMD_LIST_CONTAINERS:
319 ret = capi_list_containers(ctx, out);
322 case CAPI_CMD_STORE_NAME:
323 tmpstr = OPENSSL_strdup(p);
324 if (tmpstr != NULL) {
325 OPENSSL_free(ctx->storename);
326 ctx->storename = tmpstr;
327 CAPI_trace(ctx, "Setting store name to %s\n", p);
329 CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
334 case CAPI_CMD_STORE_FLAGS:
336 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
337 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
339 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
340 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
342 CAPI_trace(ctx, "Setting flags to %d\n", i);
345 case CAPI_CMD_DEBUG_LEVEL:
346 ctx->debug_level = (int)i;
347 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
350 case CAPI_CMD_DEBUG_FILE:
351 tmpstr = OPENSSL_strdup(p);
352 if (tmpstr != NULL) {
353 ctx->debug_file = tmpstr;
354 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
356 CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
361 case CAPI_CMD_KEYTYPE:
363 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
366 case CAPI_CMD_SET_CSP_IDX:
367 ret = capi_ctx_set_provname_idx(ctx, i);
370 case CAPI_CMD_LIST_OPTIONS:
374 case CAPI_CMD_LOOKUP_METHOD:
375 if (i < 1 || i > 3) {
376 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
380 ctx->lookup_method = i;
383 case CAPI_CMD_SET_CSP_NAME:
384 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
387 case CAPI_CMD_SET_CSP_TYPE:
392 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
401 static RSA_METHOD *capi_rsa_method = NULL;
402 # ifndef OPENSSL_NO_DSA
403 static DSA_METHOD *capi_dsa_method = NULL;
406 static int use_aes_csp = 0;
407 static const WCHAR rsa_aes_cspname[] =
408 L"Microsoft Enhanced RSA and AES Cryptographic Provider";
409 static const WCHAR rsa_enh_cspname[] =
410 L"Microsoft Enhanced Cryptographic Provider v1.0";
412 static int capi_init(ENGINE *e)
415 const RSA_METHOD *ossl_rsa_meth;
416 # ifndef OPENSSL_NO_DSA
417 const DSA_METHOD *ossl_dsa_meth;
422 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
426 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
428 /* Setup RSA_METHOD */
429 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
430 ossl_rsa_meth = RSA_PKCS1_OpenSSL();
431 if ( !RSA_meth_set_pub_enc(capi_rsa_method,
432 RSA_meth_get_pub_enc(ossl_rsa_meth))
433 || !RSA_meth_set_pub_dec(capi_rsa_method,
434 RSA_meth_get_pub_dec(ossl_rsa_meth))
435 || !RSA_meth_set_priv_enc(capi_rsa_method, capi_rsa_priv_enc)
436 || !RSA_meth_set_priv_dec(capi_rsa_method, capi_rsa_priv_dec)
437 || !RSA_meth_set_mod_exp(capi_rsa_method,
438 RSA_meth_get_mod_exp(ossl_rsa_meth))
439 || !RSA_meth_set_bn_mod_exp(capi_rsa_method,
440 RSA_meth_get_bn_mod_exp(ossl_rsa_meth))
441 || !RSA_meth_set_finish(capi_rsa_method, capi_rsa_free)
442 || !RSA_meth_set_sign(capi_rsa_method, capi_rsa_sign)) {
446 # ifndef OPENSSL_NO_DSA
447 /* Setup DSA Method */
448 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
449 ossl_dsa_meth = DSA_OpenSSL();
450 if ( !DSA_meth_set_sign(capi_dsa_method, capi_dsa_do_sign)
451 || !DSA_meth_set_verify(capi_dsa_method,
452 DSA_meth_get_verify(ossl_dsa_meth))
453 || !DSA_meth_set_finish(capi_dsa_method, capi_dsa_free)
454 || !DSA_meth_set_mod_exp(capi_dsa_method,
455 DSA_meth_get_mod_exp(ossl_dsa_meth))
456 || !DSA_meth_set_bn_mod_exp(capi_dsa_method,
457 DSA_meth_get_bn_mod_exp(ossl_dsa_meth))) {
463 ctx = capi_ctx_new();
467 ENGINE_set_ex_data(e, capi_idx, ctx);
469 # ifdef OPENSSL_CAPIENG_DIALOG
471 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
472 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
475 (CERTDLG) GetProcAddress(cryptui,
476 "CryptUIDlgSelectCertificateFromStore");
479 (GETCONSWIN) GetProcAddress(kernel, "GetConsoleWindow");
480 if (cryptui && !OPENSSL_isservice())
481 ctx->client_cert_select = cert_select_dialog;
485 /* See if there is RSA+AES CSP */
486 if (CryptAcquireContextW(&hprov, NULL, rsa_aes_cspname, PROV_RSA_AES,
487 CRYPT_VERIFYCONTEXT)) {
489 CryptReleaseContext(hprov, 0);
495 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
501 static int capi_destroy(ENGINE *e)
503 RSA_meth_free(capi_rsa_method);
504 capi_rsa_method = NULL;
505 # ifndef OPENSSL_NO_DSA
506 DSA_meth_free(capi_dsa_method);
507 capi_dsa_method = NULL;
509 ERR_unload_CAPI_strings();
513 static int capi_finish(ENGINE *e)
516 ctx = ENGINE_get_ex_data(e, capi_idx);
518 ENGINE_set_ex_data(e, capi_idx, NULL);
523 * CryptoAPI key application data. This contains a handle to the private key
524 * container (for sign operations) and a handle to the key (for decrypt
529 /* Associated certificate context (if any) */
530 PCCERT_CONTEXT pcert;
536 static int bind_capi(ENGINE *e)
538 capi_rsa_method = RSA_meth_new("CryptoAPI RSA method", 0);
539 if (capi_rsa_method == NULL)
541 # ifndef OPENSSL_NO_DSA
542 capi_dsa_method = DSA_meth_new("CryptoAPI DSA method", 0);
543 if (capi_dsa_method == NULL)
546 if (!ENGINE_set_id(e, engine_capi_id)
547 || !ENGINE_set_name(e, engine_capi_name)
548 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
549 || !ENGINE_set_init_function(e, capi_init)
550 || !ENGINE_set_finish_function(e, capi_finish)
551 || !ENGINE_set_destroy_function(e, capi_destroy)
552 || !ENGINE_set_RSA(e, capi_rsa_method)
553 # ifndef OPENSSL_NO_DSA
554 || !ENGINE_set_DSA(e, capi_dsa_method)
556 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
557 || !ENGINE_set_load_ssl_client_cert_function(e,
558 capi_load_ssl_client_cert)
559 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
560 || !ENGINE_set_ctrl_function(e, capi_ctrl))
562 ERR_load_CAPI_strings();
566 RSA_meth_free(capi_rsa_method);
567 capi_rsa_method = NULL;
568 # ifndef OPENSSL_NO_DSA
569 DSA_meth_free(capi_dsa_method);
570 capi_dsa_method = NULL;
575 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
576 static int bind_helper(ENGINE *e, const char *id)
578 if (id && (strcmp(id, engine_capi_id) != 0))
585 IMPLEMENT_DYNAMIC_CHECK_FN()
586 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
588 static ENGINE *engine_capi(void)
590 ENGINE *ret = ENGINE_new();
593 if (!bind_capi(ret)) {
600 void engine_load_capi_int(void)
602 /* Copied from eng_[openssl|dyn].c */
603 ENGINE *toadd = engine_capi();
612 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
616 * Reverse buffer in place: since this is a keyblob structure that will
617 * be freed up after conversion anyway it doesn't matter if we change
620 for (i = 0; i < binlen / 2; i++) {
623 bin[i] = bin[binlen - i - 1];
624 bin[binlen - i - 1] = c;
627 if (!BN_bin2bn(bin, binlen, bn))
632 /* Given a CAPI_KEY get an EVP_PKEY structure */
634 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY *key)
636 unsigned char *pubkey = NULL;
641 EVP_PKEY *ret = NULL;
642 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
643 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
648 pubkey = OPENSSL_malloc(len);
653 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
654 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
659 bh = (BLOBHEADER *) pubkey;
660 if (bh->bType != PUBLICKEYBLOB) {
661 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
664 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
667 BIGNUM *e = NULL, *n = NULL;
668 unsigned char *rsa_modulus;
669 rp = (RSAPUBKEY *) (bh + 1);
670 if (rp->magic != 0x31415352) {
672 BIO_snprintf(magstr, 10, "%lx", rp->magic);
673 CAPIerr(CAPI_F_CAPI_GET_PKEY,
674 CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
675 ERR_add_error_data(2, "magic=0x", magstr);
678 rsa_modulus = (unsigned char *)(rp + 1);
679 rkey = RSA_new_method(eng);
686 if (e == NULL || n == NULL) {
692 RSA_set0_key(rkey, n, e, NULL);
694 if (!BN_set_word(e, rp->pubexp))
697 rsa_modlen = rp->bitlen / 8;
698 if (!lend_tobn(n, rsa_modulus, rsa_modlen))
701 RSA_set_ex_data(rkey, rsa_capi_idx, key);
703 if ((ret = EVP_PKEY_new()) == NULL)
706 EVP_PKEY_assign_RSA(ret, rkey);
709 # ifndef OPENSSL_NO_DSA
710 } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
714 BIGNUM *p, *q, *g, *pub_key;
715 dp = (DSSPUBKEY *) (bh + 1);
716 if (dp->magic != 0x31535344) {
718 BIO_snprintf(magstr, 10, "%lx", dp->magic);
719 CAPIerr(CAPI_F_CAPI_GET_PKEY,
720 CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
721 ERR_add_error_data(2, "magic=0x", magstr);
724 dsa_plen = dp->bitlen / 8;
725 btmp = (unsigned char *)(dp + 1);
726 dkey = DSA_new_method(eng);
733 if (p == NULL || q == NULL || g == NULL || pub_key == NULL) {
740 DSA_set0_pqg(dkey, p, q, g);
741 DSA_set0_key(dkey, pub_key, NULL);
742 if (!lend_tobn(p, btmp, dsa_plen))
745 if (!lend_tobn(q, btmp, 20))
748 if (!lend_tobn(g, btmp, dsa_plen))
751 if (!lend_tobn(pub_key, btmp, dsa_plen))
755 DSA_set_ex_data(dkey, dsa_capi_idx, key);
757 if ((ret = EVP_PKEY_new()) == NULL)
760 EVP_PKEY_assign_DSA(ret, dkey);
765 BIO_snprintf(algstr, 10, "%ux", bh->aiKeyAlg);
766 CAPIerr(CAPI_F_CAPI_GET_PKEY,
767 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
768 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
773 OPENSSL_free(pubkey);
776 # ifndef OPENSSL_NO_DSA
784 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
789 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
790 UI_METHOD *ui_method, void *callback_data)
795 ctx = ENGINE_get_ex_data(eng, capi_idx);
798 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
802 key = capi_find_key(ctx, key_id);
807 ret = capi_get_pkey(eng, key);
815 /* CryptoAPI RSA operations */
817 int capi_rsa_priv_enc(int flen, const unsigned char *from,
818 unsigned char *to, RSA *rsa, int padding)
820 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
824 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
825 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
835 ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
837 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
839 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
841 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
844 /* Convert the signature type to a CryptoAPI algorithm ID */
867 alg = CALG_SSL3_SHAMD5;
872 BIO_snprintf(algstr, 10, "%x", dtype);
873 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
874 ERR_add_error_data(2, "NID=0x", algstr);
879 /* Create the hash object */
880 if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
881 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
885 /* Set the hash value to the value passed */
887 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
888 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
893 /* Finally sign it */
894 slen = RSA_size(rsa);
895 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
896 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
901 /* Inplace byte reversal of signature */
902 for (i = 0; i < slen / 2; i++) {
905 sigret[i] = sigret[slen - i - 1];
906 sigret[slen - i - 1] = c;
914 CryptDestroyHash(hash);
919 int capi_rsa_priv_dec(int flen, const unsigned char *from,
920 unsigned char *to, RSA *rsa, int padding)
923 unsigned char *tmpbuf;
932 ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
934 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
936 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
938 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
943 case RSA_PKCS1_PADDING:
946 #ifdef CRYPT_DECRYPT_RSA_NO_PADDING_CHECK
948 flags = CRYPT_DECRYPT_RSA_NO_PADDING_CHECK;
954 BIO_snprintf(errstr, 10, "%d", padding);
955 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
956 ERR_add_error_data(2, "padding=", errstr);
961 /* Create temp reverse order version of input */
962 if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
963 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
966 for (i = 0; i < flen; i++)
967 tmpbuf[flen - i - 1] = from[i];
969 /* Finally decrypt it */
971 if (!CryptDecrypt(capi_key->key, 0, TRUE, flags, tmpbuf, &dlen)) {
972 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
974 OPENSSL_cleanse(tmpbuf, dlen);
975 OPENSSL_free(tmpbuf);
978 memcpy(to, tmpbuf, (flen = (int)dlen));
980 OPENSSL_cleanse(tmpbuf, flen);
981 OPENSSL_free(tmpbuf);
986 static int capi_rsa_free(RSA *rsa)
989 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
990 capi_free_key(capi_key);
991 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
995 # ifndef OPENSSL_NO_DSA
996 /* CryptoAPI DSA operations */
998 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
1003 DSA_SIG *ret = NULL;
1006 unsigned char csigbuf[40];
1008 ctx = ENGINE_get_ex_data(DSA_get0_engine(dsa), capi_idx);
1010 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
1012 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1015 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
1020 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
1024 /* Create the hash object */
1025 if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
1026 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
1027 capi_addlasterror();
1031 /* Set the hash value to the value passed */
1032 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
1033 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
1034 capi_addlasterror();
1038 /* Finally sign it */
1039 slen = sizeof(csigbuf);
1040 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
1041 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1042 capi_addlasterror();
1045 BIGNUM *r = BN_new(), *s = BN_new();
1047 if (r == NULL || s == NULL
1048 || !lend_tobn(r, csigbuf, 20)
1049 || !lend_tobn(s, csigbuf + 20, 20)
1050 || (ret = DSA_SIG_new()) == NULL) {
1051 BN_free(r); /* BN_free checks for BIGNUM * being NULL */
1055 DSA_SIG_set0(ret, r, s);
1061 OPENSSL_cleanse(csigbuf, 40);
1062 CryptDestroyHash(hash);
1066 static int capi_dsa_free(DSA *dsa)
1069 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1070 capi_free_key(capi_key);
1071 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1076 static void capi_vtrace(CAPI_CTX *ctx, int level, char *format,
1081 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1083 out = BIO_new_file(ctx->debug_file, "a+");
1085 CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
1088 BIO_vprintf(out, format, argptr);
1092 static void CAPI_trace(CAPI_CTX *ctx, char *format, ...)
1095 va_start(args, format);
1096 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1100 static void capi_addlasterror(void)
1102 capi_adderror(GetLastError());
1105 static void capi_adderror(DWORD err)
1108 BIO_snprintf(errstr, 10, "%lX", err);
1109 ERR_add_error_data(2, "Error code= 0x", errstr);
1112 static char *wide_to_asc(LPCWSTR wstr)
1119 len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1120 sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1122 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1125 str = OPENSSL_malloc(sz);
1127 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1130 if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1132 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1138 static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype,
1143 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1144 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1145 err = GetLastError();
1146 if (err == ERROR_NO_MORE_ITEMS)
1148 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1152 name = OPENSSL_malloc(len);
1154 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1157 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1158 err = GetLastError();
1160 if (err == ERROR_NO_MORE_ITEMS)
1162 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1166 if (sizeof(TCHAR) != sizeof(char)) {
1167 *pname = wide_to_asc((WCHAR *)name);
1172 *pname = (char *)name;
1174 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1180 static int capi_list_providers(CAPI_CTX *ctx, BIO *out)
1184 LPSTR provname = NULL;
1185 CAPI_trace(ctx, "capi_list_providers\n");
1186 BIO_printf(out, "Available CSPs:\n");
1187 for (idx = 0;; idx++) {
1188 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1193 BIO_printf(out, "%lu. %s, type %lu\n", idx, provname, ptype);
1194 OPENSSL_free(provname);
1199 static int capi_list_containers(CAPI_CTX *ctx, BIO *out)
1203 DWORD err, idx, flags, buflen = 0, clen;
1205 LPWSTR cspname = NULL;
1207 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1209 if (ctx->cspname != NULL) {
1210 if ((clen = MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
1212 cspname = alloca(clen * sizeof(WCHAR));
1213 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1216 if (cspname == NULL) {
1217 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1218 capi_addlasterror();
1222 if (!CryptAcquireContextW(&hprov, NULL, cspname, ctx->csptype,
1223 CRYPT_VERIFYCONTEXT)) {
1224 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1225 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1226 capi_addlasterror();
1229 if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen,
1231 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1232 capi_addlasterror();
1233 CryptReleaseContext(hprov, 0);
1236 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1239 cname = OPENSSL_malloc(buflen);
1240 if (cname == NULL) {
1241 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1245 for (idx = 0;; idx++) {
1250 flags = CRYPT_FIRST;
1253 if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, (BYTE *)cname,
1255 err = GetLastError();
1256 if (err == ERROR_NO_MORE_ITEMS)
1258 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1262 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1263 cname, clen, idx, flags);
1264 if (!cname[0] && (clen == buflen)) {
1265 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1268 BIO_printf(out, "%lu. %s\n", idx, cname);
1275 OPENSSL_free(cname);
1276 CryptReleaseContext(hprov, 0);
1281 static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx,
1282 PCCERT_CONTEXT cert)
1285 CRYPT_KEY_PROV_INFO *pinfo;
1287 if (!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
1290 pinfo = OPENSSL_malloc(len);
1291 if (pinfo == NULL) {
1292 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1295 if (!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
1297 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1298 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1299 capi_addlasterror();
1300 OPENSSL_free(pinfo);
1306 static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out,
1307 CRYPT_KEY_PROV_INFO *pinfo)
1309 char *provname = NULL, *contname = NULL;
1311 if (pinfo == NULL) {
1312 BIO_printf(out, " No Private Key\n");
1315 provname = wide_to_asc(pinfo->pwszProvName);
1316 contname = wide_to_asc(pinfo->pwszContainerName);
1317 if (provname == NULL || contname == NULL)
1320 BIO_printf(out, " Private Key Info:\n");
1321 BIO_printf(out, " Provider Name: %s, Provider Type %lu\n", provname,
1323 BIO_printf(out, " Container Name: %s, Key Type %lu\n", contname,
1326 OPENSSL_free(provname);
1327 OPENSSL_free(contname);
1330 static char *capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1335 CAPI_trace(ctx, "capi_cert_get_fname\n");
1336 if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
1339 wfname = OPENSSL_malloc(dlen);
1342 if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
1344 char *fname = wide_to_asc(wfname);
1345 OPENSSL_free(wfname);
1348 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1349 capi_addlasterror();
1351 OPENSSL_free(wfname);
1355 static void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert)
1358 const unsigned char *p;
1359 unsigned long flags = ctx->dump_flags;
1360 if (flags & CAPI_DMP_FNAME) {
1362 fname = capi_cert_get_fname(ctx, cert);
1364 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1365 OPENSSL_free(fname);
1367 BIO_printf(out, " <No Friendly Name>\n");
1371 p = cert->pbCertEncoded;
1372 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1374 BIO_printf(out, " <Can't parse certificate>\n");
1375 if (flags & CAPI_DMP_SUMMARY) {
1376 BIO_printf(out, " Subject: ");
1377 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1378 BIO_printf(out, "\n Issuer: ");
1379 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1380 BIO_printf(out, "\n");
1382 if (flags & CAPI_DMP_FULL)
1383 X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
1385 if (flags & CAPI_DMP_PKEYINFO) {
1386 CRYPT_KEY_PROV_INFO *pinfo;
1387 pinfo = capi_get_prov_info(ctx, cert);
1388 capi_dump_prov_info(ctx, out, pinfo);
1389 OPENSSL_free(pinfo);
1392 if (flags & CAPI_DMP_PEM)
1393 PEM_write_bio_X509(out, x);
1397 static HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename)
1402 storename = ctx->storename;
1405 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1407 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1408 ctx->store_flags, storename);
1410 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1411 capi_addlasterror();
1416 int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id)
1422 PCCERT_CONTEXT cert = NULL;
1424 storename = ctx->storename;
1427 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1429 hstore = capi_open_store(ctx, storename);
1433 cert = capi_find_cert(ctx, id, hstore);
1438 capi_dump_cert(ctx, out, cert);
1439 CertFreeCertificateContext(cert);
1441 for (idx = 0;; idx++) {
1442 cert = CertEnumCertificatesInStore(hstore, cert);
1445 BIO_printf(out, "Certificate %d\n", idx);
1446 capi_dump_cert(ctx, out, cert);
1450 CertCloseStore(hstore, 0);
1454 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id,
1457 PCCERT_CONTEXT cert = NULL;
1460 switch (ctx->lookup_method) {
1461 case CAPI_LU_SUBSTR:
1462 return CertFindCertificateInStore(hstore, X509_ASN_ENCODING, 0,
1463 CERT_FIND_SUBJECT_STR_A, id, NULL);
1466 cert = CertEnumCertificatesInStore(hstore, cert);
1469 fname = capi_cert_get_fname(ctx, cert);
1471 if (strcmp(fname, id))
1475 OPENSSL_free(fname);
1485 static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const WCHAR *contname,
1486 const WCHAR *provname, DWORD ptype,
1490 CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
1494 /* If PROV_RSA_AES supported use it instead */
1495 if (ptype == PROV_RSA_FULL && use_aes_csp &&
1496 wcscmp(provname, rsa_enh_cspname) == 0) {
1497 provname = rsa_aes_cspname;
1498 ptype = PROV_RSA_AES;
1500 if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
1502 * above 'if' is [complementary] copy from CAPI_trace and serves
1503 * as optimization to minimize [below] malloc-ations
1505 char *_contname = wide_to_asc(contname);
1506 char *_provname = wide_to_asc(provname);
1508 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1509 _contname, _provname, ptype);
1510 OPENSSL_free(_provname);
1511 OPENSSL_free(_contname);
1513 if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1514 dwFlags = CRYPT_MACHINE_KEYSET;
1515 if (!CryptAcquireContextW(&key->hprov, contname, provname, ptype,
1517 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1518 capi_addlasterror();
1521 if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1522 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1523 capi_addlasterror();
1524 CryptReleaseContext(key->hprov, 0);
1527 key->keyspec = keyspec;
1536 static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1538 CAPI_KEY *key = NULL;
1539 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1541 pinfo = capi_get_prov_info(ctx, cert);
1544 key = capi_get_key(ctx, pinfo->pwszContainerName, pinfo->pwszProvName,
1545 pinfo->dwProvType, pinfo->dwKeySpec);
1547 OPENSSL_free(pinfo);
1551 CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id)
1553 PCCERT_CONTEXT cert;
1555 CAPI_KEY *key = NULL;
1557 switch (ctx->lookup_method) {
1558 case CAPI_LU_SUBSTR:
1560 hstore = capi_open_store(ctx, NULL);
1563 cert = capi_find_cert(ctx, id, hstore);
1565 key = capi_get_cert_key(ctx, cert);
1566 CertFreeCertificateContext(cert);
1568 CertCloseStore(hstore, 0);
1571 case CAPI_LU_CONTNAME:
1573 WCHAR *contname, *provname;
1576 if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1577 (contname = alloca(len * sizeof(WCHAR)),
1578 MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1579 (len = MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
1581 (provname = alloca(len * sizeof(WCHAR)),
1582 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
1584 key = capi_get_key(ctx, contname, provname,
1585 ctx->csptype, ctx->keytype);
1593 void capi_free_key(CAPI_KEY *key)
1597 CryptDestroyKey(key->key);
1598 CryptReleaseContext(key->hprov, 0);
1600 CertFreeCertificateContext(key->pcert);
1604 /* Initialize a CAPI_CTX structure */
1606 static CAPI_CTX *capi_ctx_new(void)
1608 CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
1611 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1614 ctx->csptype = PROV_RSA_FULL;
1615 ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1616 ctx->keytype = AT_KEYEXCHANGE;
1617 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1618 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1619 ctx->lookup_method = CAPI_LU_SUBSTR;
1620 ctx->client_cert_select = cert_select_simple;
1624 static void capi_ctx_free(CAPI_CTX *ctx)
1626 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1629 OPENSSL_free(ctx->cspname);
1630 OPENSSL_free(ctx->debug_file);
1631 OPENSSL_free(ctx->storename);
1632 OPENSSL_free(ctx->ssl_client_store);
1636 static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type,
1641 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1647 if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1648 name = alloca(len * sizeof(WCHAR));
1649 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1651 if (name == NULL || !CryptAcquireContextW(&hprov, NULL, name, type,
1652 CRYPT_VERIFYCONTEXT)) {
1653 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1654 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1655 capi_addlasterror();
1658 CryptReleaseContext(hprov, 0);
1660 tmpcspname = OPENSSL_strdup(pname);
1661 if (tmpcspname == NULL) {
1662 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, ERR_R_MALLOC_FAILURE);
1665 OPENSSL_free(ctx->cspname);
1666 ctx->cspname = tmpcspname;
1667 ctx->csptype = type;
1671 static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx)
1676 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1678 res = capi_ctx_set_provname(ctx, pname, type, 0);
1679 OPENSSL_free(pname);
1683 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1687 /* Special case: empty list: match anything */
1688 if (sk_X509_NAME_num(ca_dn) <= 0)
1690 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1691 nm = sk_X509_NAME_value(ca_dn, i);
1692 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1698 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1699 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1700 EVP_PKEY **pkey, STACK_OF(X509) **pother,
1701 UI_METHOD *ui_method,
1702 void *callback_data)
1704 STACK_OF(X509) *certs = NULL;
1707 const unsigned char *p;
1708 int i, client_cert_idx;
1710 PCCERT_CONTEXT cert = NULL, excert = NULL;
1713 ctx = ENGINE_get_ex_data(e, capi_idx);
1718 storename = ctx->ssl_client_store;
1722 hstore = capi_open_store(ctx, storename);
1725 /* Enumerate all certificates collect any matches */
1727 cert = CertEnumCertificatesInStore(hstore, cert);
1730 p = cert->pbCertEncoded;
1731 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1733 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1736 if (cert_issuer_match(ca_dn, x)
1737 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1738 key = capi_get_cert_key(ctx, cert);
1744 * Match found: attach extra data to it so we can retrieve the
1747 excert = CertDuplicateCertificateContext(cert);
1748 key->pcert = excert;
1749 X509_set_ex_data(x, cert_capi_idx, key);
1752 certs = sk_X509_new_null();
1754 sk_X509_push(certs, x);
1761 CertFreeCertificateContext(cert);
1763 CertCloseStore(hstore, 0);
1768 /* Select the appropriate certificate */
1770 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1772 /* Set the selected certificate and free the rest */
1774 for (i = 0; i < sk_X509_num(certs); i++) {
1775 x = sk_X509_value(certs, i);
1776 if (i == client_cert_idx)
1779 key = X509_get_ex_data(x, cert_capi_idx);
1785 sk_X509_free(certs);
1790 /* Setup key for selected certificate */
1792 key = X509_get_ex_data(*pcert, cert_capi_idx);
1793 *pkey = capi_get_pkey(e, key);
1794 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1800 /* Simple client cert selection function: always select first */
1802 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1807 # ifdef OPENSSL_CAPIENG_DIALOG
1810 * More complex cert selection function, using standard function
1811 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1815 * Definitions which are in cryptuiapi.h but this is not present in older
1816 * versions of headers.
1819 # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1820 # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1821 # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1824 # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1825 # define dlg_prompt L"Select a certificate to use for authentication"
1826 # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1827 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1829 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1833 PCCERT_CONTEXT cert;
1838 if (sk_X509_num(certs) == 1)
1840 ctx = ENGINE_get_ex_data(e, capi_idx);
1841 /* Create an in memory store of certificates */
1842 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1843 CERT_STORE_CREATE_NEW_FLAG, NULL);
1845 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1846 capi_addlasterror();
1849 /* Add all certificates to store */
1850 for (i = 0; i < sk_X509_num(certs); i++) {
1851 x = sk_X509_value(certs, i);
1852 key = X509_get_ex_data(x, cert_capi_idx);
1854 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1855 CERT_STORE_ADD_NEW, NULL)) {
1856 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1857 capi_addlasterror();
1862 hwnd = GetForegroundWindow();
1864 hwnd = GetActiveWindow();
1865 if (!hwnd && ctx->getconswindow)
1866 hwnd = ctx->getconswindow();
1867 /* Call dialog to select one */
1868 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1869 dlg_columns, 0, NULL);
1871 /* Find matching cert from list */
1873 for (i = 0; i < sk_X509_num(certs); i++) {
1874 x = sk_X509_value(certs, i);
1875 key = X509_get_ex_data(x, cert_capi_idx);
1876 if (CertCompareCertificate
1877 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1878 key->pcert->pCertInfo)) {
1887 CertCloseStore(dstore, 0);
1893 #else /* !__COMPILE_CAPIENG */
1894 # include <openssl/engine.h>
1895 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1897 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1899 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1904 IMPLEMENT_DYNAMIC_CHECK_FN()
1906 void engine_load_capi_int(void);
1907 void engine_load_capi_int(void)