2 * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
5 /* ====================================================================
6 * Copyright (c) 2008 The OpenSSL Project. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
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
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/)"
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.
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.
34 * 6. Redistributions of any form whatsoever must retain the following
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
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 * ====================================================================
58 #include <openssl/crypto.h>
60 #ifdef OPENSSL_SYS_WIN32
61 # ifndef OPENSSL_NO_CAPIENG
63 # include <openssl/buffer.h>
64 # include <openssl/bn.h>
65 # include <openssl/rsa.h>
66 # include <openssl/dsa.h>
69 # define _WIN32_WINNT 0x0400
73 # include <wincrypt.h>
76 # define alloca _alloca
80 * This module uses several "new" interfaces, among which is
81 * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is
82 * one of possible values you can pass to function in question. By
83 * checking if it's defined we can see if wincrypt.h and accompanying
84 * crypt32.lib are in shape. The native MingW32 headers up to and
85 * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the
86 * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG,
87 * so we check for these too and avoid compiling.
88 * Yes, it's rather "weak" test and if compilation fails,
89 * then re-configure with -DOPENSSL_NO_CAPIENG.
91 # if defined(CERT_KEY_PROV_INFO_PROP_ID) && \
92 defined(CERT_STORE_PROV_SYSTEM_A) && \
93 defined(CERT_STORE_READONLY_FLAG)
94 # define __COMPILE_CAPIENG
95 # endif /* CERT_KEY_PROV_INFO_PROP_ID */
96 # endif /* OPENSSL_NO_CAPIENG */
97 #endif /* OPENSSL_SYS_WIN32 */
99 #ifdef __COMPILE_CAPIENG
101 # undef X509_EXTENSIONS
103 /* Definitions which may be missing from earlier version of headers */
104 # ifndef CERT_STORE_OPEN_EXISTING_FLAG
105 # define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
108 # ifndef CERT_STORE_CREATE_NEW_FLAG
109 # define CERT_STORE_CREATE_NEW_FLAG 0x00002000
112 # ifndef CERT_SYSTEM_STORE_CURRENT_USER
113 # define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000
116 # ifndef ALG_SID_SHA_256
117 # define ALG_SID_SHA_256 12
119 # ifndef ALG_SID_SHA_384
120 # define ALG_SID_SHA_384 13
122 # ifndef ALG_SID_SHA_512
123 # define ALG_SID_SHA_512 14
126 # ifndef CALG_SHA_256
127 # define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
129 # ifndef CALG_SHA_384
130 # define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
132 # ifndef CALG_SHA_512
133 # define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
136 # ifndef PROV_RSA_AES
137 # define PROV_RSA_AES 24
140 # include <openssl/engine.h>
141 # include <openssl/pem.h>
142 # include <openssl/x509v3.h>
144 # include "e_capi_err.h"
145 # include "e_capi_err.c"
147 static const char *engine_capi_id = "capi";
148 static const char *engine_capi_name = "CryptoAPI ENGINE";
150 typedef struct CAPI_CTX_st CAPI_CTX;
151 typedef struct CAPI_KEY_st CAPI_KEY;
153 static void capi_addlasterror(void);
154 static void capi_adderror(DWORD err);
156 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...);
158 static int capi_list_providers(CAPI_CTX * ctx, BIO *out);
159 static int capi_list_containers(CAPI_CTX * ctx, BIO *out);
160 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *storename);
161 void capi_free_key(CAPI_KEY * key);
163 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
166 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id);
168 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
169 UI_METHOD *ui_method, void *callback_data);
170 static int capi_rsa_sign(int dtype, const unsigned char *m,
171 unsigned int m_len, unsigned char *sigret,
172 unsigned int *siglen, const RSA *rsa);
173 static int capi_rsa_priv_enc(int flen, const unsigned char *from,
174 unsigned char *to, RSA *rsa, int padding);
175 static int capi_rsa_priv_dec(int flen, const unsigned char *from,
176 unsigned char *to, RSA *rsa, int padding);
177 static int capi_rsa_free(RSA *rsa);
179 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
181 static int capi_dsa_free(DSA *dsa);
183 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
184 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
185 EVP_PKEY **pkey, STACK_OF(X509) **pother,
186 UI_METHOD *ui_method,
187 void *callback_data);
189 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
190 # ifdef OPENSSL_CAPIENG_DIALOG
191 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
194 void engine_load_capi_internal(void);
196 typedef PCCERT_CONTEXT(WINAPI *CERTDLG) (HCERTSTORE, HWND, LPCWSTR,
197 LPCWSTR, DWORD, DWORD, void *);
198 typedef HWND(WINAPI *GETCONSWIN) (void);
201 * This structure contains CAPI ENGINE specific data: it contains various
202 * global options and affects how other functions behave.
205 # define CAPI_DBG_TRACE 2
206 # define CAPI_DBG_ERROR 1
211 /* Parameters to use for container lookup */
215 /* Certificate store name to use */
217 LPSTR ssl_client_store;
218 /* System store flags */
220 /* Lookup string meanings in load_private_key */
221 /* Substring of subject: uses "storename" */
222 # define CAPI_LU_SUBSTR 1
223 /* Friendly name: uses storename */
224 # define CAPI_LU_FNAME 2
225 /* Container name: uses cspname, keytype */
226 # define CAPI_LU_CONTNAME 3
228 /* Info to dump with dumpcerts option */
229 /* Issuer and serial name strings */
230 # define CAPI_DMP_SUMMARY 0x1
232 # define CAPI_DMP_FNAME 0x2
233 /* Full X509_print dump */
234 # define CAPI_DMP_FULL 0x4
235 /* Dump PEM format certificate */
236 # define CAPI_DMP_PEM 0x8
237 /* Dump pseudo key (if possible) */
238 # define CAPI_DMP_PSKEY 0x10
239 /* Dump key info (if possible) */
240 # define CAPI_DMP_PKEYINFO 0x20
242 int (*client_cert_select) (ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
243 CERTDLG certselectdlg;
244 GETCONSWIN getconswindow;
247 static CAPI_CTX *capi_ctx_new(void);
248 static void capi_ctx_free(CAPI_CTX * ctx);
249 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
251 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx);
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)
268 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
269 {CAPI_CMD_LIST_CERTS,
271 "List all certificates in store",
272 ENGINE_CMD_FLAG_NO_INPUT},
273 {CAPI_CMD_LOOKUP_CERT,
275 "Lookup and output certificates",
276 ENGINE_CMD_FLAG_STRING},
277 {CAPI_CMD_DEBUG_LEVEL,
279 "debug level (1=errors, 2=trace)",
280 ENGINE_CMD_FLAG_NUMERIC},
281 {CAPI_CMD_DEBUG_FILE,
283 "debugging filename)",
284 ENGINE_CMD_FLAG_STRING},
287 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
288 ENGINE_CMD_FLAG_NUMERIC},
292 ENGINE_CMD_FLAG_NO_INPUT},
293 {CAPI_CMD_SET_CSP_IDX,
296 ENGINE_CMD_FLAG_NUMERIC},
297 {CAPI_CMD_SET_CSP_NAME,
299 "Set CSP name, (default CSP used if not specified)",
300 ENGINE_CMD_FLAG_STRING},
301 {CAPI_CMD_SET_CSP_TYPE,
303 "Set CSP type, (default RSA_PROV_FULL)",
304 ENGINE_CMD_FLAG_NUMERIC},
305 {CAPI_CMD_LIST_CONTAINERS,
307 "list container names",
308 ENGINE_CMD_FLAG_NO_INPUT},
309 {CAPI_CMD_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,
316 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
317 ENGINE_CMD_FLAG_NUMERIC},
318 {CAPI_CMD_STORE_NAME,
320 "certificate store name, default \"MY\"",
321 ENGINE_CMD_FLAG_STRING},
322 {CAPI_CMD_STORE_FLAGS,
324 "Certificate store flags: 1 = system store",
325 ENGINE_CMD_FLAG_NUMERIC},
330 static int capi_idx = -1;
331 static int rsa_capi_idx = -1;
332 static int dsa_capi_idx = -1;
333 static int cert_capi_idx = -1;
335 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
340 if (capi_idx == -1) {
341 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
344 ctx = ENGINE_get_ex_data(e, capi_idx);
345 out = BIO_new_fp(stdout, BIO_NOCLOSE);
347 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_FILE_OPEN_ERROR);
351 case CAPI_CMD_LIST_CSPS:
352 ret = capi_list_providers(ctx, out);
355 case CAPI_CMD_LIST_CERTS:
356 ret = capi_list_certs(ctx, out, NULL);
359 case CAPI_CMD_LOOKUP_CERT:
360 ret = capi_list_certs(ctx, out, p);
363 case CAPI_CMD_LIST_CONTAINERS:
364 ret = capi_list_containers(ctx, out);
367 case CAPI_CMD_STORE_NAME:
368 OPENSSL_free(ctx->storename);
369 ctx->storename = OPENSSL_strdup(p);
370 CAPI_trace(ctx, "Setting store name to %s\n", p);
373 case CAPI_CMD_STORE_FLAGS:
375 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
376 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
378 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
379 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
381 CAPI_trace(ctx, "Setting flags to %d\n", i);
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);
389 case CAPI_CMD_DEBUG_FILE:
390 ctx->debug_file = OPENSSL_strdup(p);
391 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
394 case CAPI_CMD_KEYTYPE:
396 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
399 case CAPI_CMD_SET_CSP_IDX:
400 ret = capi_ctx_set_provname_idx(ctx, i);
403 case CAPI_CMD_LIST_OPTIONS:
407 case CAPI_CMD_LOOKUP_METHOD:
408 if (i < 1 || i > 3) {
409 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
413 ctx->lookup_method = i;
416 case CAPI_CMD_SET_CSP_NAME:
417 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
420 case CAPI_CMD_SET_CSP_TYPE:
425 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
434 static RSA_METHOD capi_rsa_method = {
435 "CryptoAPI RSA method",
438 capi_rsa_priv_enc, /* priv_enc */
439 capi_rsa_priv_dec, /* priv_dec */
443 capi_rsa_free, /* finish */
446 capi_rsa_sign, /* rsa_sign */
450 static DSA_METHOD *capi_dsa_method = NULL;
452 static int use_aes_csp = 0;
454 static int capi_init(ENGINE *e)
457 const RSA_METHOD *ossl_rsa_meth;
458 const DSA_METHOD *ossl_dsa_meth;
462 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
466 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
468 /* Setup RSA_METHOD */
469 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
470 ossl_rsa_meth = RSA_PKCS1_OpenSSL();
471 capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc;
472 capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec;
473 capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp;
474 capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp;
476 /* Setup DSA Method */
477 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
478 ossl_dsa_meth = DSA_OpenSSL();
479 DSA_meth_set_sign(capi_dsa_method, capi_dsa_do_sign);
480 DSA_meth_set_verify(capi_dsa_method, DSA_meth_get_verify(ossl_dsa_meth));
481 DSA_meth_set_finish(capi_dsa_method, capi_dsa_free);
482 DSA_meth_set_mod_exp(capi_dsa_method, DSA_meth_get_mod_exp(ossl_dsa_meth));
483 DSA_meth_set_bn_mod_exp(capi_dsa_method,
484 DSA_meth_get_bn_mod_exp(ossl_dsa_meth));
487 ctx = capi_ctx_new();
491 ENGINE_set_ex_data(e, capi_idx, ctx);
493 # ifdef OPENSSL_CAPIENG_DIALOG
495 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
496 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
499 (CERTDLG) GetProcAddress(cryptui,
500 "CryptUIDlgSelectCertificateFromStore");
503 (GETCONSWIN) GetProcAddress(kernel, "GetConsoleWindow");
504 if (cryptui && !OPENSSL_isservice())
505 ctx->client_cert_select = cert_select_dialog;
509 /* See if we support AES CSP */
511 if (CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_AES,
512 CRYPT_VERIFYCONTEXT)) {
514 CryptReleaseContext(hprov, 0);
520 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
526 static int capi_destroy(ENGINE *e)
528 DSA_meth_free(capi_dsa_method);
529 capi_dsa_method = NULL;
530 ERR_unload_CAPI_strings();
534 static int capi_finish(ENGINE *e)
537 ctx = ENGINE_get_ex_data(e, capi_idx);
539 ENGINE_set_ex_data(e, capi_idx, NULL);
544 * CryptoAPI key application data. This contains a handle to the private key
545 * container (for sign operations) and a handle to the key (for decrypt
550 /* Associated certificate context (if any) */
551 PCCERT_CONTEXT pcert;
557 static int bind_capi(ENGINE *e)
559 capi_dsa_method = DSA_meth_new("CryptoAPI DSA method", 0);
560 if (capi_dsa_method == NULL)
562 if (!ENGINE_set_id(e, engine_capi_id)
563 || !ENGINE_set_name(e, engine_capi_name)
564 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
565 || !ENGINE_set_init_function(e, capi_init)
566 || !ENGINE_set_finish_function(e, capi_finish)
567 || !ENGINE_set_destroy_function(e, capi_destroy)
568 || !ENGINE_set_RSA(e, &capi_rsa_method)
569 || !ENGINE_set_DSA(e, capi_dsa_method)
570 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
571 || !ENGINE_set_load_ssl_client_cert_function(e,
572 capi_load_ssl_client_cert)
573 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
574 || !ENGINE_set_ctrl_function(e, capi_ctrl))
576 ERR_load_CAPI_strings();
582 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
583 static int bind_helper(ENGINE *e, const char *id)
585 if (id && (strcmp(id, engine_capi_id) != 0))
592 IMPLEMENT_DYNAMIC_CHECK_FN()
593 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
595 static ENGINE *engine_capi(void)
597 ENGINE *ret = ENGINE_new();
600 if (!bind_capi(ret)) {
607 void engine_load_capi_internal(void)
609 /* Copied from eng_[openssl|dyn].c */
610 ENGINE *toadd = engine_capi();
619 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
623 * Reverse buffer in place: since this is a keyblob structure that will
624 * be freed up after conversion anyway it doesn't matter if we change
627 for (i = 0; i < binlen / 2; i++) {
630 bin[i] = bin[binlen - i - 1];
631 bin[binlen - i - 1] = c;
634 if (!BN_bin2bn(bin, binlen, bn))
639 /* Given a CAPI_KEY get an EVP_PKEY structure */
641 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
643 unsigned char *pubkey = NULL;
648 EVP_PKEY *ret = NULL;
649 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
650 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
655 pubkey = OPENSSL_malloc(len);
660 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
661 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
666 bh = (BLOBHEADER *) pubkey;
667 if (bh->bType != PUBLICKEYBLOB) {
668 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
671 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
674 unsigned char *rsa_modulus;
675 rp = (RSAPUBKEY *) (bh + 1);
676 if (rp->magic != 0x31415352) {
678 BIO_snprintf(magstr, 10, "%lx", rp->magic);
679 CAPIerr(CAPI_F_CAPI_GET_PKEY,
680 CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
681 ERR_add_error_data(2, "magic=0x", magstr);
684 rsa_modulus = (unsigned char *)(rp + 1);
685 rkey = RSA_new_method(eng);
692 if (rkey->e == NULL || rkey->n == NULL)
695 if (!BN_set_word(rkey->e, rp->pubexp))
698 rsa_modlen = rp->bitlen / 8;
699 if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
702 RSA_set_ex_data(rkey, rsa_capi_idx, key);
704 if ((ret = EVP_PKEY_new()) == NULL)
707 EVP_PKEY_assign_RSA(ret, rkey);
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)
735 DSA_set0_pqg(dkey, p, q, g);
736 DSA_set0_key(dkey, pub_key, NULL);
737 if (!lend_tobn(p, btmp, dsa_plen))
740 if (!lend_tobn(q, btmp, 20))
743 if (!lend_tobn(g, btmp, dsa_plen))
746 if (!lend_tobn(pub_key, btmp, dsa_plen))
750 DSA_set_ex_data(dkey, dsa_capi_idx, key);
752 if ((ret = EVP_PKEY_new()) == NULL)
755 EVP_PKEY_assign_DSA(ret, dkey);
759 BIO_snprintf(algstr, 10, "%ux", bh->aiKeyAlg);
760 CAPIerr(CAPI_F_CAPI_GET_PKEY,
761 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
762 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
767 OPENSSL_free(pubkey);
776 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
781 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
782 UI_METHOD *ui_method, void *callback_data)
787 ctx = ENGINE_get_ex_data(eng, capi_idx);
790 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
794 key = capi_find_key(ctx, key_id);
799 ret = capi_get_pkey(eng, key);
807 /* CryptoAPI RSA operations */
809 int capi_rsa_priv_enc(int flen, const unsigned char *from,
810 unsigned char *to, RSA *rsa, int padding)
812 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
816 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
817 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
827 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
829 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
831 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
833 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
836 /* Convert the signature type to a CryptoAPI algorithm ID */
859 alg = CALG_SSL3_SHAMD5;
864 BIO_snprintf(algstr, 10, "%x", dtype);
865 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
866 ERR_add_error_data(2, "NID=0x", algstr);
871 /* Create the hash object */
872 if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
873 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
877 /* Set the hash value to the value passed */
879 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
880 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
885 /* Finally sign it */
886 slen = RSA_size(rsa);
887 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
888 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
893 /* Inplace byte reversal of signature */
894 for (i = 0; i < slen / 2; i++) {
897 sigret[i] = sigret[slen - i - 1];
898 sigret[slen - i - 1] = c;
906 CryptDestroyHash(hash);
911 int capi_rsa_priv_dec(int flen, const unsigned char *from,
912 unsigned char *to, RSA *rsa, int padding)
915 unsigned char *tmpbuf;
923 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
925 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
927 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
929 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
933 if (padding != RSA_PKCS1_PADDING) {
935 BIO_snprintf(errstr, 10, "%d", padding);
936 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
937 ERR_add_error_data(2, "padding=", errstr);
941 /* Create temp reverse order version of input */
942 if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
943 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
946 for (i = 0; i < flen; i++)
947 tmpbuf[flen - i - 1] = from[i];
949 /* Finally decrypt it */
951 if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &dlen)) {
952 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
954 OPENSSL_free(tmpbuf);
957 memcpy(to, tmpbuf, (flen = (int)dlen));
959 OPENSSL_free(tmpbuf);
964 static int capi_rsa_free(RSA *rsa)
967 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
968 capi_free_key(capi_key);
969 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
973 /* CryptoAPI DSA operations */
975 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
983 unsigned char csigbuf[40];
985 ctx = ENGINE_get_ex_data(DSA_get0_engine(dsa), capi_idx);
987 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
989 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
992 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
997 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
1001 /* Create the hash object */
1002 if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
1003 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
1004 capi_addlasterror();
1008 /* Set the hash value to the value passed */
1009 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
1010 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
1011 capi_addlasterror();
1015 /* Finally sign it */
1016 slen = sizeof(csigbuf);
1017 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
1018 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1019 capi_addlasterror();
1022 BIGNUM *r = NULL, *s = NULL;
1023 ret = DSA_SIG_new();
1026 DSA_SIG_get0(&r, &s, ret);
1027 if (!lend_tobn(r, csigbuf, 20)
1028 || !lend_tobn(s, csigbuf + 20, 20)) {
1038 OPENSSL_cleanse(csigbuf, 40);
1039 CryptDestroyHash(hash);
1043 static int capi_dsa_free(DSA *dsa)
1046 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1047 capi_free_key(capi_key);
1048 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1052 static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
1057 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1059 out = BIO_new_file(ctx->debug_file, "a+");
1061 CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
1064 BIO_vprintf(out, format, argptr);
1068 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
1071 va_start(args, format);
1072 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1076 static void capi_addlasterror(void)
1078 capi_adderror(GetLastError());
1081 static void capi_adderror(DWORD err)
1084 BIO_snprintf(errstr, 10, "%lX", err);
1085 ERR_add_error_data(2, "Error code= 0x", errstr);
1088 static char *wide_to_asc(LPCWSTR wstr)
1095 len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1096 sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1098 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1101 str = OPENSSL_malloc(sz);
1103 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1106 if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1108 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1114 static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
1119 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1120 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1121 err = GetLastError();
1122 if (err == ERROR_NO_MORE_ITEMS)
1124 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1128 name = OPENSSL_malloc(len);
1130 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1133 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1134 err = GetLastError();
1136 if (err == ERROR_NO_MORE_ITEMS)
1138 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1142 if (sizeof(TCHAR) != sizeof(char)) {
1143 *pname = wide_to_asc((WCHAR *)name);
1148 *pname = (char *)name;
1149 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1155 static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
1159 LPSTR provname = NULL;
1160 CAPI_trace(ctx, "capi_list_providers\n");
1161 BIO_printf(out, "Available CSPs:\n");
1162 for (idx = 0;; idx++) {
1163 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1168 BIO_printf(out, "%lu. %s, type %lu\n", idx, provname, ptype);
1169 OPENSSL_free(provname);
1174 static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
1178 DWORD err, idx, flags, buflen = 0, clen;
1180 LPTSTR cspname = NULL;
1182 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1184 if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
1186 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
1187 cspname = alloca(clen * sizeof(WCHAR));
1188 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1192 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1193 capi_addlasterror();
1197 cspname = (TCHAR *)ctx->cspname;
1198 if (!CryptAcquireContext
1199 (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
1200 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1201 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1202 capi_addlasterror();
1205 if (!CryptGetProvParam
1206 (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
1207 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1208 capi_addlasterror();
1209 CryptReleaseContext(hprov, 0);
1212 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1215 cname = OPENSSL_malloc(buflen);
1216 if (cname == NULL) {
1217 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1221 for (idx = 0;; idx++) {
1226 flags = CRYPT_FIRST;
1229 if (!CryptGetProvParam
1230 (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
1231 err = GetLastError();
1232 if (err == ERROR_NO_MORE_ITEMS)
1234 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1238 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1239 cname, clen, idx, flags);
1240 if (!cname[0] && (clen == buflen)) {
1241 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1244 BIO_printf(out, "%lu. %s\n", idx, cname);
1251 OPENSSL_free(cname);
1252 CryptReleaseContext(hprov, 0);
1257 static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1260 CRYPT_KEY_PROV_INFO *pinfo;
1262 if (!CertGetCertificateContextProperty
1263 (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1265 pinfo = OPENSSL_malloc(len);
1266 if (pinfo == NULL) {
1267 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1270 if (!CertGetCertificateContextProperty
1271 (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
1272 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1273 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1274 capi_addlasterror();
1275 OPENSSL_free(pinfo);
1281 static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
1282 CRYPT_KEY_PROV_INFO * pinfo)
1284 char *provname = NULL, *contname = NULL;
1286 BIO_printf(out, " No Private Key\n");
1289 provname = wide_to_asc(pinfo->pwszProvName);
1290 contname = wide_to_asc(pinfo->pwszContainerName);
1291 if (!provname || !contname)
1294 BIO_printf(out, " Private Key Info:\n");
1295 BIO_printf(out, " Provider Name: %s, Provider Type %lu\n", provname,
1297 BIO_printf(out, " Container Name: %s, Key Type %lu\n", contname,
1300 OPENSSL_free(provname);
1301 OPENSSL_free(contname);
1304 static char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1309 CAPI_trace(ctx, "capi_cert_get_fname\n");
1310 if (!CertGetCertificateContextProperty
1311 (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1313 wfname = OPENSSL_malloc(dlen);
1316 if (CertGetCertificateContextProperty
1317 (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
1318 char *fname = wide_to_asc(wfname);
1319 OPENSSL_free(wfname);
1322 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1323 capi_addlasterror();
1325 OPENSSL_free(wfname);
1329 static void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
1332 const unsigned char *p;
1333 unsigned long flags = ctx->dump_flags;
1334 if (flags & CAPI_DMP_FNAME) {
1336 fname = capi_cert_get_fname(ctx, cert);
1338 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1339 OPENSSL_free(fname);
1341 BIO_printf(out, " <No Friendly Name>\n");
1344 p = cert->pbCertEncoded;
1345 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1347 BIO_printf(out, " <Can't parse certificate>\n");
1348 if (flags & CAPI_DMP_SUMMARY) {
1349 BIO_printf(out, " Subject: ");
1350 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1351 BIO_printf(out, "\n Issuer: ");
1352 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1353 BIO_printf(out, "\n");
1355 if (flags & CAPI_DMP_FULL)
1356 X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
1358 if (flags & CAPI_DMP_PKEYINFO) {
1359 CRYPT_KEY_PROV_INFO *pinfo;
1360 pinfo = capi_get_prov_info(ctx, cert);
1361 capi_dump_prov_info(ctx, out, pinfo);
1362 OPENSSL_free(pinfo);
1365 if (flags & CAPI_DMP_PEM)
1366 PEM_write_bio_X509(out, x);
1370 static HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
1375 storename = ctx->storename;
1378 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1380 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1381 ctx->store_flags, storename);
1383 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1384 capi_addlasterror();
1389 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
1395 PCCERT_CONTEXT cert = NULL;
1397 storename = ctx->storename;
1400 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1402 hstore = capi_open_store(ctx, storename);
1406 cert = capi_find_cert(ctx, id, hstore);
1411 capi_dump_cert(ctx, out, cert);
1412 CertFreeCertificateContext(cert);
1414 for (idx = 0;; idx++) {
1415 cert = CertEnumCertificatesInStore(hstore, cert);
1418 BIO_printf(out, "Certificate %d\n", idx);
1419 capi_dump_cert(ctx, out, cert);
1423 CertCloseStore(hstore, 0);
1427 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
1430 PCCERT_CONTEXT cert = NULL;
1433 switch (ctx->lookup_method) {
1434 case CAPI_LU_SUBSTR:
1435 return CertFindCertificateInStore(hstore,
1436 X509_ASN_ENCODING, 0,
1437 CERT_FIND_SUBJECT_STR_A, id, NULL);
1440 cert = CertEnumCertificatesInStore(hstore, cert);
1443 fname = capi_cert_get_fname(ctx, cert);
1445 if (strcmp(fname, id))
1449 OPENSSL_free(fname);
1459 static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
1460 TCHAR *provname, DWORD ptype, DWORD keyspec)
1463 CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
1467 /* If PROV_RSA_AES supported use it instead */
1468 if (ptype == PROV_RSA_FULL && use_aes_csp) {
1470 ptype = PROV_RSA_AES;
1471 CAPI_trace(ctx, "capi_get_key, contname=%s, RSA_AES_CSP\n", contname);
1472 } else if (sizeof(TCHAR) == sizeof(char)) {
1473 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1474 contname, provname, ptype);
1475 } else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
1476 /* above 'if' is optimization to minimize malloc-ations */
1477 char *_contname = wide_to_asc((WCHAR *)contname);
1478 char *_provname = wide_to_asc((WCHAR *)provname);
1480 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1481 _contname, _provname, ptype);
1482 OPENSSL_free(_provname);
1483 OPENSSL_free(_contname);
1485 if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1486 dwFlags = CRYPT_MACHINE_KEYSET;
1487 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
1488 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1489 capi_addlasterror();
1492 if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1493 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1494 capi_addlasterror();
1495 CryptReleaseContext(key->hprov, 0);
1498 key->keyspec = keyspec;
1507 static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1509 CAPI_KEY *key = NULL;
1510 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1511 char *provname = NULL, *contname = NULL;
1512 pinfo = capi_get_prov_info(ctx, cert);
1515 if (sizeof(TCHAR) != sizeof(char))
1516 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1517 (TCHAR *)pinfo->pwszProvName,
1518 pinfo->dwProvType, pinfo->dwKeySpec);
1520 provname = wide_to_asc(pinfo->pwszProvName);
1521 contname = wide_to_asc(pinfo->pwszContainerName);
1522 if (!provname || !contname)
1524 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1525 pinfo->dwProvType, pinfo->dwKeySpec);
1529 OPENSSL_free(pinfo);
1530 OPENSSL_free(provname);
1531 OPENSSL_free(contname);
1535 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
1537 PCCERT_CONTEXT cert;
1539 CAPI_KEY *key = NULL;
1540 switch (ctx->lookup_method) {
1541 case CAPI_LU_SUBSTR:
1543 hstore = capi_open_store(ctx, NULL);
1546 cert = capi_find_cert(ctx, id, hstore);
1548 key = capi_get_cert_key(ctx, cert);
1549 CertFreeCertificateContext(cert);
1551 CertCloseStore(hstore, 0);
1554 case CAPI_LU_CONTNAME:
1555 if (sizeof(TCHAR) != sizeof(char)) {
1556 WCHAR *contname, *provname;
1559 if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1560 (contname = alloca(len * sizeof(WCHAR)),
1561 MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1563 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
1565 alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
1572 capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1573 ctx->csptype, ctx->keytype);
1575 key = capi_get_key(ctx, (TCHAR *)id,
1576 (TCHAR *)ctx->cspname,
1577 ctx->csptype, ctx->keytype);
1584 void capi_free_key(CAPI_KEY * key)
1588 CryptDestroyKey(key->key);
1589 CryptReleaseContext(key->hprov, 0);
1591 CertFreeCertificateContext(key->pcert);
1595 /* Initialize a CAPI_CTX structure */
1597 static CAPI_CTX *capi_ctx_new(void)
1599 CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
1602 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1605 ctx->csptype = PROV_RSA_FULL;
1606 ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1607 ctx->keytype = AT_KEYEXCHANGE;
1608 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1609 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1610 ctx->lookup_method = CAPI_LU_SUBSTR;
1611 ctx->client_cert_select = cert_select_simple;
1615 static void capi_ctx_free(CAPI_CTX * ctx)
1617 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1620 OPENSSL_free(ctx->cspname);
1621 OPENSSL_free(ctx->debug_file);
1622 OPENSSL_free(ctx->storename);
1623 OPENSSL_free(ctx->ssl_client_store);
1627 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
1630 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1635 if (sizeof(TCHAR) != sizeof(char)) {
1637 if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1638 name = alloca(len * sizeof(WCHAR));
1639 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1642 name = (TCHAR *)pname;
1644 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1645 CRYPT_VERIFYCONTEXT)) {
1646 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1647 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1648 capi_addlasterror();
1651 CryptReleaseContext(hprov, 0);
1653 OPENSSL_free(ctx->cspname);
1654 ctx->cspname = OPENSSL_strdup(pname);
1655 ctx->csptype = type;
1659 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
1664 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1666 res = capi_ctx_set_provname(ctx, pname, type, 0);
1667 OPENSSL_free(pname);
1671 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1675 /* Special case: empty list: match anything */
1676 if (sk_X509_NAME_num(ca_dn) <= 0)
1678 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1679 nm = sk_X509_NAME_value(ca_dn, i);
1680 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1686 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1687 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1688 EVP_PKEY **pkey, STACK_OF(X509) **pother,
1689 UI_METHOD *ui_method,
1690 void *callback_data)
1692 STACK_OF(X509) *certs = NULL;
1695 const unsigned char *p;
1696 int i, client_cert_idx;
1698 PCCERT_CONTEXT cert = NULL, excert = NULL;
1701 ctx = ENGINE_get_ex_data(e, capi_idx);
1706 storename = ctx->ssl_client_store;
1710 hstore = capi_open_store(ctx, storename);
1713 /* Enumerate all certificates collect any matches */
1715 cert = CertEnumCertificatesInStore(hstore, cert);
1718 p = cert->pbCertEncoded;
1719 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1721 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1724 if (cert_issuer_match(ca_dn, x)
1725 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1726 key = capi_get_cert_key(ctx, cert);
1732 * Match found: attach extra data to it so we can retrieve the
1735 excert = CertDuplicateCertificateContext(cert);
1736 key->pcert = excert;
1737 X509_set_ex_data(x, cert_capi_idx, key);
1740 certs = sk_X509_new_null();
1742 sk_X509_push(certs, x);
1749 CertFreeCertificateContext(cert);
1751 CertCloseStore(hstore, 0);
1756 /* Select the appropriate certificate */
1758 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1760 /* Set the selected certificate and free the rest */
1762 for (i = 0; i < sk_X509_num(certs); i++) {
1763 x = sk_X509_value(certs, i);
1764 if (i == client_cert_idx)
1767 key = X509_get_ex_data(x, cert_capi_idx);
1773 sk_X509_free(certs);
1778 /* Setup key for selected certificate */
1780 key = X509_get_ex_data(*pcert, cert_capi_idx);
1781 *pkey = capi_get_pkey(e, key);
1782 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1788 /* Simple client cert selection function: always select first */
1790 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1795 # ifdef OPENSSL_CAPIENG_DIALOG
1798 * More complex cert selection function, using standard function
1799 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1803 * Definitions which are in cryptuiapi.h but this is not present in older
1804 * versions of headers.
1807 # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1808 # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1809 # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1812 # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1813 # define dlg_prompt L"Select a certificate to use for authentication"
1814 # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1815 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1817 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1821 PCCERT_CONTEXT cert;
1826 if (sk_X509_num(certs) == 1)
1828 ctx = ENGINE_get_ex_data(e, capi_idx);
1829 /* Create an in memory store of certificates */
1830 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1831 CERT_STORE_CREATE_NEW_FLAG, NULL);
1833 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1834 capi_addlasterror();
1837 /* Add all certificates to store */
1838 for (i = 0; i < sk_X509_num(certs); i++) {
1839 x = sk_X509_value(certs, i);
1840 key = X509_get_ex_data(x, cert_capi_idx);
1842 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1843 CERT_STORE_ADD_NEW, NULL)) {
1844 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1845 capi_addlasterror();
1850 hwnd = GetForegroundWindow();
1852 hwnd = GetActiveWindow();
1853 if (!hwnd && ctx->getconswindow)
1854 hwnd = ctx->getconswindow();
1855 /* Call dialog to select one */
1856 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1857 dlg_columns, 0, NULL);
1859 /* Find matching cert from list */
1861 for (i = 0; i < sk_X509_num(certs); i++) {
1862 x = sk_X509_value(certs, i);
1863 key = X509_get_ex_data(x, cert_capi_idx);
1864 if (CertCompareCertificate
1865 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1866 key->pcert->pCertInfo)) {
1875 CertCloseStore(dstore, 0);
1881 #else /* !__COMPILE_CAPIENG */
1882 # include <openssl/engine.h>
1883 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1885 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1887 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1892 IMPLEMENT_DYNAMIC_CHECK_FN()
1894 void engine_load_capi_internal(void);
1895 void engine_load_capi_internal(void)