2 * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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
14 #include <openssl/crypto.h>
16 #ifdef OPENSSL_SYS_WIN32
17 # ifndef OPENSSL_NO_CAPIENG
19 # include <openssl/buffer.h>
20 # include <openssl/bn.h>
21 # include <openssl/rsa.h>
22 # include <openssl/dsa.h>
25 # define _WIN32_WINNT 0x0400
29 # include <wincrypt.h>
32 # define alloca _alloca
36 * This module uses several "new" interfaces, among which is
37 * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is
38 * one of possible values you can pass to function in question. By
39 * checking if it's defined we can see if wincrypt.h and accompanying
40 * crypt32.lib are in shape. The native MingW32 headers up to and
41 * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the
42 * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG,
43 * so we check for these too and avoid compiling.
44 * Yes, it's rather "weak" test and if compilation fails,
45 * then re-configure with -DOPENSSL_NO_CAPIENG.
47 # if defined(CERT_KEY_PROV_INFO_PROP_ID) && \
48 defined(CERT_STORE_PROV_SYSTEM_A) && \
49 defined(CERT_STORE_READONLY_FLAG)
50 # define __COMPILE_CAPIENG
51 # endif /* CERT_KEY_PROV_INFO_PROP_ID */
52 # endif /* OPENSSL_NO_CAPIENG */
53 #endif /* OPENSSL_SYS_WIN32 */
55 #ifdef __COMPILE_CAPIENG
57 # undef X509_EXTENSIONS
59 /* Definitions which may be missing from earlier version of headers */
60 # ifndef CERT_STORE_OPEN_EXISTING_FLAG
61 # define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
64 # ifndef CERT_STORE_CREATE_NEW_FLAG
65 # define CERT_STORE_CREATE_NEW_FLAG 0x00002000
68 # ifndef CERT_SYSTEM_STORE_CURRENT_USER
69 # define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000
72 # ifndef ALG_SID_SHA_256
73 # define ALG_SID_SHA_256 12
75 # ifndef ALG_SID_SHA_384
76 # define ALG_SID_SHA_384 13
78 # ifndef ALG_SID_SHA_512
79 # define ALG_SID_SHA_512 14
83 # define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
86 # define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
89 # define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
93 # define PROV_RSA_AES 24
96 # include <openssl/engine.h>
97 # include <openssl/pem.h>
98 # include <openssl/x509v3.h>
100 # include "e_capi_err.h"
101 # include "e_capi_err.c"
103 static const char *engine_capi_id = "capi";
104 static const char *engine_capi_name = "CryptoAPI ENGINE";
106 typedef struct CAPI_CTX_st CAPI_CTX;
107 typedef struct CAPI_KEY_st CAPI_KEY;
109 static void capi_addlasterror(void);
110 static void capi_adderror(DWORD err);
112 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...);
114 static int capi_list_providers(CAPI_CTX * ctx, BIO *out);
115 static int capi_list_containers(CAPI_CTX * ctx, BIO *out);
116 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *storename);
117 void capi_free_key(CAPI_KEY * key);
119 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
122 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id);
124 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
125 UI_METHOD *ui_method, void *callback_data);
126 static int capi_rsa_sign(int dtype, const unsigned char *m,
127 unsigned int m_len, unsigned char *sigret,
128 unsigned int *siglen, const RSA *rsa);
129 static int capi_rsa_priv_enc(int flen, const unsigned char *from,
130 unsigned char *to, RSA *rsa, int padding);
131 static int capi_rsa_priv_dec(int flen, const unsigned char *from,
132 unsigned char *to, RSA *rsa, int padding);
133 static int capi_rsa_free(RSA *rsa);
135 # ifndef OPENSSL_NO_DSA
136 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
138 static int capi_dsa_free(DSA *dsa);
141 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
142 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
143 EVP_PKEY **pkey, STACK_OF(X509) **pother,
144 UI_METHOD *ui_method,
145 void *callback_data);
147 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
148 # ifdef OPENSSL_CAPIENG_DIALOG
149 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
152 void engine_load_capi_int(void);
154 typedef PCCERT_CONTEXT(WINAPI *CERTDLG) (HCERTSTORE, HWND, LPCWSTR,
155 LPCWSTR, DWORD, DWORD, void *);
156 typedef HWND(WINAPI *GETCONSWIN) (void);
159 * This structure contains CAPI ENGINE specific data: it contains various
160 * global options and affects how other functions behave.
163 # define CAPI_DBG_TRACE 2
164 # define CAPI_DBG_ERROR 1
169 /* Parameters to use for container lookup */
173 /* Certificate store name to use */
175 LPSTR ssl_client_store;
176 /* System store flags */
178 /* Lookup string meanings in load_private_key */
179 /* Substring of subject: uses "storename" */
180 # define CAPI_LU_SUBSTR 1
181 /* Friendly name: uses storename */
182 # define CAPI_LU_FNAME 2
183 /* Container name: uses cspname, keytype */
184 # define CAPI_LU_CONTNAME 3
186 /* Info to dump with dumpcerts option */
187 /* Issuer and serial name strings */
188 # define CAPI_DMP_SUMMARY 0x1
190 # define CAPI_DMP_FNAME 0x2
191 /* Full X509_print dump */
192 # define CAPI_DMP_FULL 0x4
193 /* Dump PEM format certificate */
194 # define CAPI_DMP_PEM 0x8
195 /* Dump pseudo key (if possible) */
196 # define CAPI_DMP_PSKEY 0x10
197 /* Dump key info (if possible) */
198 # define CAPI_DMP_PKEYINFO 0x20
200 int (*client_cert_select) (ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
201 CERTDLG certselectdlg;
202 GETCONSWIN getconswindow;
205 static CAPI_CTX *capi_ctx_new(void);
206 static void capi_ctx_free(CAPI_CTX * ctx);
207 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
209 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx);
211 # define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
212 # define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
213 # define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
214 # define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
215 # define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
216 # define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
217 # define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
218 # define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
219 # define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
220 # define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
221 # define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
222 # define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
223 # define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
224 # define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
226 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
227 {CAPI_CMD_LIST_CERTS,
229 "List all certificates in store",
230 ENGINE_CMD_FLAG_NO_INPUT},
231 {CAPI_CMD_LOOKUP_CERT,
233 "Lookup and output certificates",
234 ENGINE_CMD_FLAG_STRING},
235 {CAPI_CMD_DEBUG_LEVEL,
237 "debug level (1=errors, 2=trace)",
238 ENGINE_CMD_FLAG_NUMERIC},
239 {CAPI_CMD_DEBUG_FILE,
241 "debugging filename)",
242 ENGINE_CMD_FLAG_STRING},
245 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
246 ENGINE_CMD_FLAG_NUMERIC},
250 ENGINE_CMD_FLAG_NO_INPUT},
251 {CAPI_CMD_SET_CSP_IDX,
254 ENGINE_CMD_FLAG_NUMERIC},
255 {CAPI_CMD_SET_CSP_NAME,
257 "Set CSP name, (default CSP used if not specified)",
258 ENGINE_CMD_FLAG_STRING},
259 {CAPI_CMD_SET_CSP_TYPE,
261 "Set CSP type, (default RSA_PROV_FULL)",
262 ENGINE_CMD_FLAG_NUMERIC},
263 {CAPI_CMD_LIST_CONTAINERS,
265 "list container names",
266 ENGINE_CMD_FLAG_NO_INPUT},
267 {CAPI_CMD_LIST_OPTIONS,
269 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
270 "32=private key info)",
271 ENGINE_CMD_FLAG_NUMERIC},
272 {CAPI_CMD_LOOKUP_METHOD,
274 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
275 ENGINE_CMD_FLAG_NUMERIC},
276 {CAPI_CMD_STORE_NAME,
278 "certificate store name, default \"MY\"",
279 ENGINE_CMD_FLAG_STRING},
280 {CAPI_CMD_STORE_FLAGS,
282 "Certificate store flags: 1 = system store",
283 ENGINE_CMD_FLAG_NUMERIC},
288 static int capi_idx = -1;
289 static int rsa_capi_idx = -1;
290 static int dsa_capi_idx = -1;
291 static int cert_capi_idx = -1;
293 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
299 if (capi_idx == -1) {
300 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
303 ctx = ENGINE_get_ex_data(e, capi_idx);
304 out = BIO_new_fp(stdout, BIO_NOCLOSE);
306 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_FILE_OPEN_ERROR);
310 case CAPI_CMD_LIST_CSPS:
311 ret = capi_list_providers(ctx, out);
314 case CAPI_CMD_LIST_CERTS:
315 ret = capi_list_certs(ctx, out, NULL);
318 case CAPI_CMD_LOOKUP_CERT:
319 ret = capi_list_certs(ctx, out, p);
322 case CAPI_CMD_LIST_CONTAINERS:
323 ret = capi_list_containers(ctx, out);
326 case CAPI_CMD_STORE_NAME:
327 tmpstr = OPENSSL_strdup(p);
328 if (tmpstr != NULL) {
329 OPENSSL_free(ctx->storename);
330 ctx->storename = tmpstr;
331 CAPI_trace(ctx, "Setting store name to %s\n", p);
333 CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
338 case CAPI_CMD_STORE_FLAGS:
340 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
341 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
343 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
344 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
346 CAPI_trace(ctx, "Setting flags to %d\n", i);
349 case CAPI_CMD_DEBUG_LEVEL:
350 ctx->debug_level = (int)i;
351 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
354 case CAPI_CMD_DEBUG_FILE:
355 tmpstr = OPENSSL_strdup(p);
356 if (tmpstr != NULL) {
357 ctx->debug_file = tmpstr;
358 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
360 CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
365 case CAPI_CMD_KEYTYPE:
367 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
370 case CAPI_CMD_SET_CSP_IDX:
371 ret = capi_ctx_set_provname_idx(ctx, i);
374 case CAPI_CMD_LIST_OPTIONS:
378 case CAPI_CMD_LOOKUP_METHOD:
379 if (i < 1 || i > 3) {
380 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
384 ctx->lookup_method = i;
387 case CAPI_CMD_SET_CSP_NAME:
388 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
391 case CAPI_CMD_SET_CSP_TYPE:
396 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
405 static RSA_METHOD *capi_rsa_method = NULL;
406 # ifndef OPENSSL_NO_DSA
407 static DSA_METHOD *capi_dsa_method = NULL;
410 static int use_aes_csp = 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 we support AES CSP */
487 if (CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_AES,
488 CRYPT_VERIFYCONTEXT)) {
490 CryptReleaseContext(hprov, 0);
496 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
502 static int capi_destroy(ENGINE *e)
504 RSA_meth_free(capi_rsa_method);
505 capi_rsa_method = NULL;
506 # ifndef OPENSSL_NO_DSA
507 DSA_meth_free(capi_dsa_method);
508 capi_dsa_method = NULL;
510 ERR_unload_CAPI_strings();
514 static int capi_finish(ENGINE *e)
517 ctx = ENGINE_get_ex_data(e, capi_idx);
519 ENGINE_set_ex_data(e, capi_idx, NULL);
524 * CryptoAPI key application data. This contains a handle to the private key
525 * container (for sign operations) and a handle to the key (for decrypt
530 /* Associated certificate context (if any) */
531 PCCERT_CONTEXT pcert;
537 static int bind_capi(ENGINE *e)
539 capi_rsa_method = RSA_meth_new("CryptoAPI RSA method", 0);
540 if (capi_rsa_method == NULL)
542 # ifndef OPENSSL_NO_DSA
543 capi_dsa_method = DSA_meth_new("CryptoAPI DSA method", 0);
544 if (capi_dsa_method == NULL)
547 if (!ENGINE_set_id(e, engine_capi_id)
548 || !ENGINE_set_name(e, engine_capi_name)
549 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
550 || !ENGINE_set_init_function(e, capi_init)
551 || !ENGINE_set_finish_function(e, capi_finish)
552 || !ENGINE_set_destroy_function(e, capi_destroy)
553 || !ENGINE_set_RSA(e, capi_rsa_method)
554 # ifndef OPENSSL_NO_DSA
555 || !ENGINE_set_DSA(e, capi_dsa_method)
557 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
558 || !ENGINE_set_load_ssl_client_cert_function(e,
559 capi_load_ssl_client_cert)
560 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
561 || !ENGINE_set_ctrl_function(e, capi_ctrl))
563 ERR_load_CAPI_strings();
567 RSA_meth_free(capi_rsa_method);
568 capi_rsa_method = NULL;
569 # ifndef OPENSSL_NO_DSA
570 DSA_meth_free(capi_dsa_method);
571 capi_dsa_method = NULL;
576 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
577 static int bind_helper(ENGINE *e, const char *id)
579 if (id && (strcmp(id, engine_capi_id) != 0))
586 IMPLEMENT_DYNAMIC_CHECK_FN()
587 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
589 static ENGINE *engine_capi(void)
591 ENGINE *ret = ENGINE_new();
594 if (!bind_capi(ret)) {
601 void engine_load_capi_int(void)
603 /* Copied from eng_[openssl|dyn].c */
604 ENGINE *toadd = engine_capi();
613 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
617 * Reverse buffer in place: since this is a keyblob structure that will
618 * be freed up after conversion anyway it doesn't matter if we change
621 for (i = 0; i < binlen / 2; i++) {
624 bin[i] = bin[binlen - i - 1];
625 bin[binlen - i - 1] = c;
628 if (!BN_bin2bn(bin, binlen, bn))
633 /* Given a CAPI_KEY get an EVP_PKEY structure */
635 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
637 unsigned char *pubkey = NULL;
642 EVP_PKEY *ret = NULL;
643 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
644 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
649 pubkey = OPENSSL_malloc(len);
654 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
655 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
660 bh = (BLOBHEADER *) pubkey;
661 if (bh->bType != PUBLICKEYBLOB) {
662 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
665 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
668 BIGNUM *e = NULL, *n = NULL;
669 unsigned char *rsa_modulus;
670 rp = (RSAPUBKEY *) (bh + 1);
671 if (rp->magic != 0x31415352) {
673 BIO_snprintf(magstr, 10, "%lx", rp->magic);
674 CAPIerr(CAPI_F_CAPI_GET_PKEY,
675 CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
676 ERR_add_error_data(2, "magic=0x", magstr);
679 rsa_modulus = (unsigned char *)(rp + 1);
680 rkey = RSA_new_method(eng);
687 if (e == NULL || n == NULL) {
693 RSA_set0_key(rkey, n, e, NULL);
695 if (!BN_set_word(e, rp->pubexp))
698 rsa_modlen = rp->bitlen / 8;
699 if (!lend_tobn(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 # ifndef OPENSSL_NO_DSA
711 } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
715 BIGNUM *p, *q, *g, *pub_key;
716 dp = (DSSPUBKEY *) (bh + 1);
717 if (dp->magic != 0x31535344) {
719 BIO_snprintf(magstr, 10, "%lx", dp->magic);
720 CAPIerr(CAPI_F_CAPI_GET_PKEY,
721 CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
722 ERR_add_error_data(2, "magic=0x", magstr);
725 dsa_plen = dp->bitlen / 8;
726 btmp = (unsigned char *)(dp + 1);
727 dkey = DSA_new_method(eng);
734 if (p == NULL || q == NULL || g == NULL || pub_key == NULL) {
741 DSA_set0_pqg(dkey, p, q, g);
742 DSA_set0_key(dkey, pub_key, NULL);
743 if (!lend_tobn(p, btmp, dsa_plen))
746 if (!lend_tobn(q, btmp, 20))
749 if (!lend_tobn(g, btmp, dsa_plen))
752 if (!lend_tobn(pub_key, btmp, dsa_plen))
756 DSA_set_ex_data(dkey, dsa_capi_idx, key);
758 if ((ret = EVP_PKEY_new()) == NULL)
761 EVP_PKEY_assign_DSA(ret, dkey);
766 BIO_snprintf(algstr, 10, "%ux", bh->aiKeyAlg);
767 CAPIerr(CAPI_F_CAPI_GET_PKEY,
768 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
769 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
774 OPENSSL_free(pubkey);
777 # ifndef OPENSSL_NO_DSA
785 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
790 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
791 UI_METHOD *ui_method, void *callback_data)
796 ctx = ENGINE_get_ex_data(eng, capi_idx);
799 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
803 key = capi_find_key(ctx, key_id);
808 ret = capi_get_pkey(eng, key);
816 /* CryptoAPI RSA operations */
818 int capi_rsa_priv_enc(int flen, const unsigned char *from,
819 unsigned char *to, RSA *rsa, int padding)
821 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
825 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
826 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
836 ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
838 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
840 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
842 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
845 /* Convert the signature type to a CryptoAPI algorithm ID */
868 alg = CALG_SSL3_SHAMD5;
873 BIO_snprintf(algstr, 10, "%x", dtype);
874 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
875 ERR_add_error_data(2, "NID=0x", algstr);
880 /* Create the hash object */
881 if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
882 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
886 /* Set the hash value to the value passed */
888 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
889 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
894 /* Finally sign it */
895 slen = RSA_size(rsa);
896 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
897 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
902 /* Inplace byte reversal of signature */
903 for (i = 0; i < slen / 2; i++) {
906 sigret[i] = sigret[slen - i - 1];
907 sigret[slen - i - 1] = c;
915 CryptDestroyHash(hash);
920 int capi_rsa_priv_dec(int flen, const unsigned char *from,
921 unsigned char *to, RSA *rsa, int padding)
924 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);
942 if (padding != RSA_PKCS1_PADDING) {
944 BIO_snprintf(errstr, 10, "%d", padding);
945 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
946 ERR_add_error_data(2, "padding=", errstr);
950 /* Create temp reverse order version of input */
951 if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
952 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
955 for (i = 0; i < flen; i++)
956 tmpbuf[flen - i - 1] = from[i];
958 /* Finally decrypt it */
960 if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &dlen)) {
961 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
963 OPENSSL_free(tmpbuf);
966 memcpy(to, tmpbuf, (flen = (int)dlen));
968 OPENSSL_free(tmpbuf);
973 static int capi_rsa_free(RSA *rsa)
976 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
977 capi_free_key(capi_key);
978 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
982 # ifndef OPENSSL_NO_DSA
983 /* CryptoAPI DSA operations */
985 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
993 unsigned char csigbuf[40];
995 ctx = ENGINE_get_ex_data(DSA_get0_engine(dsa), capi_idx);
997 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
999 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1002 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
1007 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
1011 /* Create the hash object */
1012 if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
1013 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
1014 capi_addlasterror();
1018 /* Set the hash value to the value passed */
1019 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
1020 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
1021 capi_addlasterror();
1025 /* Finally sign it */
1026 slen = sizeof(csigbuf);
1027 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
1028 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1029 capi_addlasterror();
1032 BIGNUM *r = NULL, *s = NULL;
1033 ret = DSA_SIG_new();
1036 DSA_SIG_get0(&r, &s, ret);
1037 if (!lend_tobn(r, csigbuf, 20)
1038 || !lend_tobn(s, csigbuf + 20, 20)) {
1048 OPENSSL_cleanse(csigbuf, 40);
1049 CryptDestroyHash(hash);
1053 static int capi_dsa_free(DSA *dsa)
1056 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1057 capi_free_key(capi_key);
1058 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1063 static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
1068 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1070 out = BIO_new_file(ctx->debug_file, "a+");
1072 CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
1075 BIO_vprintf(out, format, argptr);
1079 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
1082 va_start(args, format);
1083 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1087 static void capi_addlasterror(void)
1089 capi_adderror(GetLastError());
1092 static void capi_adderror(DWORD err)
1095 BIO_snprintf(errstr, 10, "%lX", err);
1096 ERR_add_error_data(2, "Error code= 0x", errstr);
1099 static char *wide_to_asc(LPCWSTR wstr)
1106 len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1107 sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1109 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1112 str = OPENSSL_malloc(sz);
1114 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1117 if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1119 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1125 static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
1130 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1131 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1132 err = GetLastError();
1133 if (err == ERROR_NO_MORE_ITEMS)
1135 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1139 name = OPENSSL_malloc(len);
1141 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1144 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1145 err = GetLastError();
1147 if (err == ERROR_NO_MORE_ITEMS)
1149 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1153 if (sizeof(TCHAR) != sizeof(char)) {
1154 *pname = wide_to_asc((WCHAR *)name);
1159 *pname = (char *)name;
1160 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1166 static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
1170 LPSTR provname = NULL;
1171 CAPI_trace(ctx, "capi_list_providers\n");
1172 BIO_printf(out, "Available CSPs:\n");
1173 for (idx = 0;; idx++) {
1174 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1179 BIO_printf(out, "%lu. %s, type %lu\n", idx, provname, ptype);
1180 OPENSSL_free(provname);
1185 static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
1189 DWORD err, idx, flags, buflen = 0, clen;
1191 LPTSTR cspname = NULL;
1193 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1195 if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
1197 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
1198 cspname = alloca(clen * sizeof(WCHAR));
1199 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1203 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1204 capi_addlasterror();
1208 cspname = (TCHAR *)ctx->cspname;
1209 if (!CryptAcquireContext
1210 (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
1211 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1212 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1213 capi_addlasterror();
1216 if (!CryptGetProvParam
1217 (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
1218 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1219 capi_addlasterror();
1220 CryptReleaseContext(hprov, 0);
1223 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1226 cname = OPENSSL_malloc(buflen);
1227 if (cname == NULL) {
1228 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1232 for (idx = 0;; idx++) {
1237 flags = CRYPT_FIRST;
1240 if (!CryptGetProvParam
1241 (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
1242 err = GetLastError();
1243 if (err == ERROR_NO_MORE_ITEMS)
1245 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1249 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1250 cname, clen, idx, flags);
1251 if (!cname[0] && (clen == buflen)) {
1252 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1255 BIO_printf(out, "%lu. %s\n", idx, cname);
1262 OPENSSL_free(cname);
1263 CryptReleaseContext(hprov, 0);
1268 static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1271 CRYPT_KEY_PROV_INFO *pinfo;
1273 if (!CertGetCertificateContextProperty
1274 (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1276 pinfo = OPENSSL_malloc(len);
1277 if (pinfo == NULL) {
1278 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1281 if (!CertGetCertificateContextProperty
1282 (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
1283 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1284 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1285 capi_addlasterror();
1286 OPENSSL_free(pinfo);
1292 static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
1293 CRYPT_KEY_PROV_INFO * pinfo)
1295 char *provname = NULL, *contname = NULL;
1297 BIO_printf(out, " No Private Key\n");
1300 provname = wide_to_asc(pinfo->pwszProvName);
1301 contname = wide_to_asc(pinfo->pwszContainerName);
1302 if (!provname || !contname)
1305 BIO_printf(out, " Private Key Info:\n");
1306 BIO_printf(out, " Provider Name: %s, Provider Type %lu\n", provname,
1308 BIO_printf(out, " Container Name: %s, Key Type %lu\n", contname,
1311 OPENSSL_free(provname);
1312 OPENSSL_free(contname);
1315 static char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1320 CAPI_trace(ctx, "capi_cert_get_fname\n");
1321 if (!CertGetCertificateContextProperty
1322 (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1324 wfname = OPENSSL_malloc(dlen);
1327 if (CertGetCertificateContextProperty
1328 (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
1329 char *fname = wide_to_asc(wfname);
1330 OPENSSL_free(wfname);
1333 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1334 capi_addlasterror();
1336 OPENSSL_free(wfname);
1340 static void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
1343 const unsigned char *p;
1344 unsigned long flags = ctx->dump_flags;
1345 if (flags & CAPI_DMP_FNAME) {
1347 fname = capi_cert_get_fname(ctx, cert);
1349 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1350 OPENSSL_free(fname);
1352 BIO_printf(out, " <No Friendly Name>\n");
1355 p = cert->pbCertEncoded;
1356 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1358 BIO_printf(out, " <Can't parse certificate>\n");
1359 if (flags & CAPI_DMP_SUMMARY) {
1360 BIO_printf(out, " Subject: ");
1361 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1362 BIO_printf(out, "\n Issuer: ");
1363 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1364 BIO_printf(out, "\n");
1366 if (flags & CAPI_DMP_FULL)
1367 X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
1369 if (flags & CAPI_DMP_PKEYINFO) {
1370 CRYPT_KEY_PROV_INFO *pinfo;
1371 pinfo = capi_get_prov_info(ctx, cert);
1372 capi_dump_prov_info(ctx, out, pinfo);
1373 OPENSSL_free(pinfo);
1376 if (flags & CAPI_DMP_PEM)
1377 PEM_write_bio_X509(out, x);
1381 static HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
1386 storename = ctx->storename;
1389 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1391 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1392 ctx->store_flags, storename);
1394 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1395 capi_addlasterror();
1400 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
1406 PCCERT_CONTEXT cert = NULL;
1408 storename = ctx->storename;
1411 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1413 hstore = capi_open_store(ctx, storename);
1417 cert = capi_find_cert(ctx, id, hstore);
1422 capi_dump_cert(ctx, out, cert);
1423 CertFreeCertificateContext(cert);
1425 for (idx = 0;; idx++) {
1426 cert = CertEnumCertificatesInStore(hstore, cert);
1429 BIO_printf(out, "Certificate %d\n", idx);
1430 capi_dump_cert(ctx, out, cert);
1434 CertCloseStore(hstore, 0);
1438 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
1441 PCCERT_CONTEXT cert = NULL;
1444 switch (ctx->lookup_method) {
1445 case CAPI_LU_SUBSTR:
1446 return CertFindCertificateInStore(hstore,
1447 X509_ASN_ENCODING, 0,
1448 CERT_FIND_SUBJECT_STR_A, id, NULL);
1451 cert = CertEnumCertificatesInStore(hstore, cert);
1454 fname = capi_cert_get_fname(ctx, cert);
1456 if (strcmp(fname, id))
1460 OPENSSL_free(fname);
1470 static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
1471 TCHAR *provname, DWORD ptype, DWORD keyspec)
1474 CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
1478 /* If PROV_RSA_AES supported use it instead */
1479 if (ptype == PROV_RSA_FULL && use_aes_csp) {
1481 ptype = PROV_RSA_AES;
1482 CAPI_trace(ctx, "capi_get_key, contname=%s, RSA_AES_CSP\n", contname);
1483 } else if (sizeof(TCHAR) == sizeof(char)) {
1484 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1485 contname, provname, ptype);
1486 } else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
1487 /* above 'if' is optimization to minimize malloc-ations */
1488 char *_contname = wide_to_asc((WCHAR *)contname);
1489 char *_provname = wide_to_asc((WCHAR *)provname);
1491 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1492 _contname, _provname, ptype);
1493 OPENSSL_free(_provname);
1494 OPENSSL_free(_contname);
1496 if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1497 dwFlags = CRYPT_MACHINE_KEYSET;
1498 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
1499 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1500 capi_addlasterror();
1503 if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1504 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1505 capi_addlasterror();
1506 CryptReleaseContext(key->hprov, 0);
1509 key->keyspec = keyspec;
1518 static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1520 CAPI_KEY *key = NULL;
1521 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1522 char *provname = NULL, *contname = NULL;
1523 pinfo = capi_get_prov_info(ctx, cert);
1526 if (sizeof(TCHAR) != sizeof(char))
1527 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1528 (TCHAR *)pinfo->pwszProvName,
1529 pinfo->dwProvType, pinfo->dwKeySpec);
1531 provname = wide_to_asc(pinfo->pwszProvName);
1532 contname = wide_to_asc(pinfo->pwszContainerName);
1533 if (!provname || !contname)
1535 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1536 pinfo->dwProvType, pinfo->dwKeySpec);
1540 OPENSSL_free(pinfo);
1541 OPENSSL_free(provname);
1542 OPENSSL_free(contname);
1546 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
1548 PCCERT_CONTEXT cert;
1550 CAPI_KEY *key = NULL;
1551 switch (ctx->lookup_method) {
1552 case CAPI_LU_SUBSTR:
1554 hstore = capi_open_store(ctx, NULL);
1557 cert = capi_find_cert(ctx, id, hstore);
1559 key = capi_get_cert_key(ctx, cert);
1560 CertFreeCertificateContext(cert);
1562 CertCloseStore(hstore, 0);
1565 case CAPI_LU_CONTNAME:
1566 if (sizeof(TCHAR) != sizeof(char)) {
1567 WCHAR *contname, *provname;
1570 if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1571 (contname = alloca(len * sizeof(WCHAR)),
1572 MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1574 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
1576 alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
1583 capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1584 ctx->csptype, ctx->keytype);
1586 key = capi_get_key(ctx, (TCHAR *)id,
1587 (TCHAR *)ctx->cspname,
1588 ctx->csptype, ctx->keytype);
1595 void capi_free_key(CAPI_KEY * key)
1599 CryptDestroyKey(key->key);
1600 CryptReleaseContext(key->hprov, 0);
1602 CertFreeCertificateContext(key->pcert);
1606 /* Initialize a CAPI_CTX structure */
1608 static CAPI_CTX *capi_ctx_new(void)
1610 CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
1613 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1616 ctx->csptype = PROV_RSA_FULL;
1617 ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1618 ctx->keytype = AT_KEYEXCHANGE;
1619 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1620 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1621 ctx->lookup_method = CAPI_LU_SUBSTR;
1622 ctx->client_cert_select = cert_select_simple;
1626 static void capi_ctx_free(CAPI_CTX * ctx)
1628 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1631 OPENSSL_free(ctx->cspname);
1632 OPENSSL_free(ctx->debug_file);
1633 OPENSSL_free(ctx->storename);
1634 OPENSSL_free(ctx->ssl_client_store);
1638 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
1643 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1648 if (sizeof(TCHAR) != sizeof(char)) {
1650 if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1651 name = alloca(len * sizeof(WCHAR));
1652 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1655 name = (TCHAR *)pname;
1657 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1658 CRYPT_VERIFYCONTEXT)) {
1659 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1660 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1661 capi_addlasterror();
1664 CryptReleaseContext(hprov, 0);
1666 tmpcspname = OPENSSL_strdup(pname);
1667 if (tmpcspname == NULL) {
1668 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, ERR_R_MALLOC_FAILURE);
1671 OPENSSL_free(ctx->cspname);
1672 ctx->cspname = tmpcspname;
1673 ctx->csptype = type;
1677 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
1682 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1684 res = capi_ctx_set_provname(ctx, pname, type, 0);
1685 OPENSSL_free(pname);
1689 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1693 /* Special case: empty list: match anything */
1694 if (sk_X509_NAME_num(ca_dn) <= 0)
1696 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1697 nm = sk_X509_NAME_value(ca_dn, i);
1698 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1704 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1705 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1706 EVP_PKEY **pkey, STACK_OF(X509) **pother,
1707 UI_METHOD *ui_method,
1708 void *callback_data)
1710 STACK_OF(X509) *certs = NULL;
1713 const unsigned char *p;
1714 int i, client_cert_idx;
1716 PCCERT_CONTEXT cert = NULL, excert = NULL;
1719 ctx = ENGINE_get_ex_data(e, capi_idx);
1724 storename = ctx->ssl_client_store;
1728 hstore = capi_open_store(ctx, storename);
1731 /* Enumerate all certificates collect any matches */
1733 cert = CertEnumCertificatesInStore(hstore, cert);
1736 p = cert->pbCertEncoded;
1737 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1739 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1742 if (cert_issuer_match(ca_dn, x)
1743 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1744 key = capi_get_cert_key(ctx, cert);
1750 * Match found: attach extra data to it so we can retrieve the
1753 excert = CertDuplicateCertificateContext(cert);
1754 key->pcert = excert;
1755 X509_set_ex_data(x, cert_capi_idx, key);
1758 certs = sk_X509_new_null();
1760 sk_X509_push(certs, x);
1767 CertFreeCertificateContext(cert);
1769 CertCloseStore(hstore, 0);
1774 /* Select the appropriate certificate */
1776 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1778 /* Set the selected certificate and free the rest */
1780 for (i = 0; i < sk_X509_num(certs); i++) {
1781 x = sk_X509_value(certs, i);
1782 if (i == client_cert_idx)
1785 key = X509_get_ex_data(x, cert_capi_idx);
1791 sk_X509_free(certs);
1796 /* Setup key for selected certificate */
1798 key = X509_get_ex_data(*pcert, cert_capi_idx);
1799 *pkey = capi_get_pkey(e, key);
1800 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1806 /* Simple client cert selection function: always select first */
1808 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1813 # ifdef OPENSSL_CAPIENG_DIALOG
1816 * More complex cert selection function, using standard function
1817 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1821 * Definitions which are in cryptuiapi.h but this is not present in older
1822 * versions of headers.
1825 # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1826 # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1827 # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1830 # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1831 # define dlg_prompt L"Select a certificate to use for authentication"
1832 # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1833 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1835 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1839 PCCERT_CONTEXT cert;
1844 if (sk_X509_num(certs) == 1)
1846 ctx = ENGINE_get_ex_data(e, capi_idx);
1847 /* Create an in memory store of certificates */
1848 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1849 CERT_STORE_CREATE_NEW_FLAG, NULL);
1851 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1852 capi_addlasterror();
1855 /* Add all certificates to store */
1856 for (i = 0; i < sk_X509_num(certs); i++) {
1857 x = sk_X509_value(certs, i);
1858 key = X509_get_ex_data(x, cert_capi_idx);
1860 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1861 CERT_STORE_ADD_NEW, NULL)) {
1862 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1863 capi_addlasterror();
1868 hwnd = GetForegroundWindow();
1870 hwnd = GetActiveWindow();
1871 if (!hwnd && ctx->getconswindow)
1872 hwnd = ctx->getconswindow();
1873 /* Call dialog to select one */
1874 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1875 dlg_columns, 0, NULL);
1877 /* Find matching cert from list */
1879 for (i = 0; i < sk_X509_num(certs); i++) {
1880 x = sk_X509_value(certs, i);
1881 key = X509_get_ex_data(x, cert_capi_idx);
1882 if (CertCompareCertificate
1883 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1884 key->pcert->pCertInfo)) {
1893 CertCloseStore(dstore, 0);
1899 #else /* !__COMPILE_CAPIENG */
1900 # include <openssl/engine.h>
1901 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1903 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1905 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1910 IMPLEMENT_DYNAMIC_CHECK_FN()
1912 void engine_load_capi_int(void);
1913 void engine_load_capi_int(void)