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 # ifndef OPENSSL_NO_DSA
180 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
182 static int capi_dsa_free(DSA *dsa);
185 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
186 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
187 EVP_PKEY **pkey, STACK_OF(X509) **pother,
188 UI_METHOD *ui_method,
189 void *callback_data);
191 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
192 # ifdef OPENSSL_CAPIENG_DIALOG
193 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
196 void engine_load_capi_int(void);
198 typedef PCCERT_CONTEXT(WINAPI *CERTDLG) (HCERTSTORE, HWND, LPCWSTR,
199 LPCWSTR, DWORD, DWORD, void *);
200 typedef HWND(WINAPI *GETCONSWIN) (void);
203 * This structure contains CAPI ENGINE specific data: it contains various
204 * global options and affects how other functions behave.
207 # define CAPI_DBG_TRACE 2
208 # define CAPI_DBG_ERROR 1
213 /* Parameters to use for container lookup */
217 /* Certificate store name to use */
219 LPSTR ssl_client_store;
220 /* System store flags */
222 /* Lookup string meanings in load_private_key */
223 /* Substring of subject: uses "storename" */
224 # define CAPI_LU_SUBSTR 1
225 /* Friendly name: uses storename */
226 # define CAPI_LU_FNAME 2
227 /* Container name: uses cspname, keytype */
228 # define CAPI_LU_CONTNAME 3
230 /* Info to dump with dumpcerts option */
231 /* Issuer and serial name strings */
232 # define CAPI_DMP_SUMMARY 0x1
234 # define CAPI_DMP_FNAME 0x2
235 /* Full X509_print dump */
236 # define CAPI_DMP_FULL 0x4
237 /* Dump PEM format certificate */
238 # define CAPI_DMP_PEM 0x8
239 /* Dump pseudo key (if possible) */
240 # define CAPI_DMP_PSKEY 0x10
241 /* Dump key info (if possible) */
242 # define CAPI_DMP_PKEYINFO 0x20
244 int (*client_cert_select) (ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
245 CERTDLG certselectdlg;
246 GETCONSWIN getconswindow;
249 static CAPI_CTX *capi_ctx_new(void);
250 static void capi_ctx_free(CAPI_CTX * ctx);
251 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
253 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx);
255 # define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
256 # define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
257 # define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
258 # define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
259 # define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
260 # define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
261 # define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
262 # define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
263 # define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
264 # define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
265 # define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
266 # define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
267 # define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
268 # define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
270 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
271 {CAPI_CMD_LIST_CERTS,
273 "List all certificates in store",
274 ENGINE_CMD_FLAG_NO_INPUT},
275 {CAPI_CMD_LOOKUP_CERT,
277 "Lookup and output certificates",
278 ENGINE_CMD_FLAG_STRING},
279 {CAPI_CMD_DEBUG_LEVEL,
281 "debug level (1=errors, 2=trace)",
282 ENGINE_CMD_FLAG_NUMERIC},
283 {CAPI_CMD_DEBUG_FILE,
285 "debugging filename)",
286 ENGINE_CMD_FLAG_STRING},
289 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
290 ENGINE_CMD_FLAG_NUMERIC},
294 ENGINE_CMD_FLAG_NO_INPUT},
295 {CAPI_CMD_SET_CSP_IDX,
298 ENGINE_CMD_FLAG_NUMERIC},
299 {CAPI_CMD_SET_CSP_NAME,
301 "Set CSP name, (default CSP used if not specified)",
302 ENGINE_CMD_FLAG_STRING},
303 {CAPI_CMD_SET_CSP_TYPE,
305 "Set CSP type, (default RSA_PROV_FULL)",
306 ENGINE_CMD_FLAG_NUMERIC},
307 {CAPI_CMD_LIST_CONTAINERS,
309 "list container names",
310 ENGINE_CMD_FLAG_NO_INPUT},
311 {CAPI_CMD_LIST_OPTIONS,
313 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
314 "32=private key info)",
315 ENGINE_CMD_FLAG_NUMERIC},
316 {CAPI_CMD_LOOKUP_METHOD,
318 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
319 ENGINE_CMD_FLAG_NUMERIC},
320 {CAPI_CMD_STORE_NAME,
322 "certificate store name, default \"MY\"",
323 ENGINE_CMD_FLAG_STRING},
324 {CAPI_CMD_STORE_FLAGS,
326 "Certificate store flags: 1 = system store",
327 ENGINE_CMD_FLAG_NUMERIC},
332 static int capi_idx = -1;
333 static int rsa_capi_idx = -1;
334 static int dsa_capi_idx = -1;
335 static int cert_capi_idx = -1;
337 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
342 if (capi_idx == -1) {
343 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
346 ctx = ENGINE_get_ex_data(e, capi_idx);
347 out = BIO_new_fp(stdout, BIO_NOCLOSE);
349 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_FILE_OPEN_ERROR);
353 case CAPI_CMD_LIST_CSPS:
354 ret = capi_list_providers(ctx, out);
357 case CAPI_CMD_LIST_CERTS:
358 ret = capi_list_certs(ctx, out, NULL);
361 case CAPI_CMD_LOOKUP_CERT:
362 ret = capi_list_certs(ctx, out, p);
365 case CAPI_CMD_LIST_CONTAINERS:
366 ret = capi_list_containers(ctx, out);
369 case CAPI_CMD_STORE_NAME:
370 OPENSSL_free(ctx->storename);
371 ctx->storename = OPENSSL_strdup(p);
372 CAPI_trace(ctx, "Setting store name to %s\n", p);
375 case CAPI_CMD_STORE_FLAGS:
377 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
378 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
380 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
381 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
383 CAPI_trace(ctx, "Setting flags to %d\n", i);
386 case CAPI_CMD_DEBUG_LEVEL:
387 ctx->debug_level = (int)i;
388 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
391 case CAPI_CMD_DEBUG_FILE:
392 ctx->debug_file = OPENSSL_strdup(p);
393 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
396 case CAPI_CMD_KEYTYPE:
398 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
401 case CAPI_CMD_SET_CSP_IDX:
402 ret = capi_ctx_set_provname_idx(ctx, i);
405 case CAPI_CMD_LIST_OPTIONS:
409 case CAPI_CMD_LOOKUP_METHOD:
410 if (i < 1 || i > 3) {
411 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
415 ctx->lookup_method = i;
418 case CAPI_CMD_SET_CSP_NAME:
419 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
422 case CAPI_CMD_SET_CSP_TYPE:
427 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
436 static RSA_METHOD *capi_rsa_method = NULL;
437 # ifndef OPENSSL_NO_DSA
438 static DSA_METHOD *capi_dsa_method = NULL;
441 static int use_aes_csp = 0;
443 static int capi_init(ENGINE *e)
446 const RSA_METHOD *ossl_rsa_meth;
447 # ifndef OPENSSL_NO_DSA
448 const DSA_METHOD *ossl_dsa_meth;
453 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
457 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
459 /* Setup RSA_METHOD */
460 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
461 ossl_rsa_meth = RSA_PKCS1_OpenSSL();
462 if ( !RSA_meth_set_pub_enc(capi_rsa_method,
463 RSA_meth_get_pub_enc(ossl_rsa_meth))
464 || !RSA_meth_set_pub_dec(capi_rsa_method,
465 RSA_meth_get_pub_dec(ossl_rsa_meth))
466 || !RSA_meth_set_priv_enc(capi_rsa_method, capi_rsa_priv_enc)
467 || !RSA_meth_set_priv_dec(capi_rsa_method, capi_rsa_priv_dec)
468 || !RSA_meth_set_mod_exp(capi_rsa_method,
469 RSA_meth_get_mod_exp(ossl_rsa_meth))
470 || !RSA_meth_set_bn_mod_exp(capi_rsa_method,
471 RSA_meth_get_bn_mod_exp(ossl_rsa_meth))
472 || !RSA_meth_set_finish(capi_rsa_method, capi_rsa_free)
473 || !RSA_meth_set_sign(capi_rsa_method, capi_rsa_sign)) {
477 # ifndef OPENSSL_NO_DSA
478 /* Setup DSA Method */
479 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
480 ossl_dsa_meth = DSA_OpenSSL();
481 if ( !DSA_meth_set_sign(capi_dsa_method, capi_dsa_do_sign)
482 || !DSA_meth_set_verify(capi_dsa_method,
483 DSA_meth_get_verify(ossl_dsa_meth))
484 || !DSA_meth_set_finish(capi_dsa_method, capi_dsa_free)
485 || !DSA_meth_set_mod_exp(capi_dsa_method,
486 DSA_meth_get_mod_exp(ossl_dsa_meth))
487 || !DSA_meth_set_bn_mod_exp(capi_dsa_method,
488 DSA_meth_get_bn_mod_exp(ossl_dsa_meth))) {
494 ctx = capi_ctx_new();
498 ENGINE_set_ex_data(e, capi_idx, ctx);
500 # ifdef OPENSSL_CAPIENG_DIALOG
502 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
503 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
506 (CERTDLG) GetProcAddress(cryptui,
507 "CryptUIDlgSelectCertificateFromStore");
510 (GETCONSWIN) GetProcAddress(kernel, "GetConsoleWindow");
511 if (cryptui && !OPENSSL_isservice())
512 ctx->client_cert_select = cert_select_dialog;
516 /* See if we support AES CSP */
518 if (CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_AES,
519 CRYPT_VERIFYCONTEXT)) {
521 CryptReleaseContext(hprov, 0);
527 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
533 static int capi_destroy(ENGINE *e)
535 RSA_meth_free(capi_rsa_method);
536 capi_rsa_method = NULL;
537 # ifndef OPENSSL_NO_DSA
538 DSA_meth_free(capi_dsa_method);
539 capi_dsa_method = NULL;
541 ERR_unload_CAPI_strings();
545 static int capi_finish(ENGINE *e)
548 ctx = ENGINE_get_ex_data(e, capi_idx);
550 ENGINE_set_ex_data(e, capi_idx, NULL);
555 * CryptoAPI key application data. This contains a handle to the private key
556 * container (for sign operations) and a handle to the key (for decrypt
561 /* Associated certificate context (if any) */
562 PCCERT_CONTEXT pcert;
568 static int bind_capi(ENGINE *e)
570 capi_rsa_method = RSA_meth_new("CryptoAPI RSA method", 0);
571 if (capi_rsa_method == NULL)
573 # ifndef OPENSSL_NO_DSA
574 capi_dsa_method = DSA_meth_new("CryptoAPI DSA method", 0);
575 if (capi_dsa_method == NULL)
578 if (!ENGINE_set_id(e, engine_capi_id)
579 || !ENGINE_set_name(e, engine_capi_name)
580 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
581 || !ENGINE_set_init_function(e, capi_init)
582 || !ENGINE_set_finish_function(e, capi_finish)
583 || !ENGINE_set_destroy_function(e, capi_destroy)
584 || !ENGINE_set_RSA(e, capi_rsa_method)
585 # ifndef OPENSSL_NO_DSA
586 || !ENGINE_set_DSA(e, capi_dsa_method)
588 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
589 || !ENGINE_set_load_ssl_client_cert_function(e,
590 capi_load_ssl_client_cert)
591 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
592 || !ENGINE_set_ctrl_function(e, capi_ctrl))
594 ERR_load_CAPI_strings();
598 RSA_meth_free(capi_rsa_method);
599 capi_rsa_method = NULL;
600 # ifndef OPENSSL_NO_DSA
601 DSA_meth_free(capi_dsa_method);
602 capi_dsa_method = NULL;
607 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
608 static int bind_helper(ENGINE *e, const char *id)
610 if (id && (strcmp(id, engine_capi_id) != 0))
617 IMPLEMENT_DYNAMIC_CHECK_FN()
618 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
620 static ENGINE *engine_capi(void)
622 ENGINE *ret = ENGINE_new();
625 if (!bind_capi(ret)) {
632 void engine_load_capi_int(void)
634 /* Copied from eng_[openssl|dyn].c */
635 ENGINE *toadd = engine_capi();
644 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
648 * Reverse buffer in place: since this is a keyblob structure that will
649 * be freed up after conversion anyway it doesn't matter if we change
652 for (i = 0; i < binlen / 2; i++) {
655 bin[i] = bin[binlen - i - 1];
656 bin[binlen - i - 1] = c;
659 if (!BN_bin2bn(bin, binlen, bn))
664 /* Given a CAPI_KEY get an EVP_PKEY structure */
666 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
668 unsigned char *pubkey = NULL;
673 EVP_PKEY *ret = NULL;
674 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
675 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
680 pubkey = OPENSSL_malloc(len);
685 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
686 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
691 bh = (BLOBHEADER *) pubkey;
692 if (bh->bType != PUBLICKEYBLOB) {
693 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
696 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
699 BIGNUM *e = NULL, *n = NULL;
700 unsigned char *rsa_modulus;
701 rp = (RSAPUBKEY *) (bh + 1);
702 if (rp->magic != 0x31415352) {
704 BIO_snprintf(magstr, 10, "%lx", rp->magic);
705 CAPIerr(CAPI_F_CAPI_GET_PKEY,
706 CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
707 ERR_add_error_data(2, "magic=0x", magstr);
710 rsa_modulus = (unsigned char *)(rp + 1);
711 rkey = RSA_new_method(eng);
718 if (e == NULL || n == NULL) {
724 RSA_set0_key(rkey, n, e, NULL);
726 if (!BN_set_word(e, rp->pubexp))
729 rsa_modlen = rp->bitlen / 8;
730 if (!lend_tobn(n, rsa_modulus, rsa_modlen))
733 RSA_set_ex_data(rkey, rsa_capi_idx, key);
735 if ((ret = EVP_PKEY_new()) == NULL)
738 EVP_PKEY_assign_RSA(ret, rkey);
741 # ifndef OPENSSL_NO_DSA
742 } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
746 BIGNUM *p, *q, *g, *pub_key;
747 dp = (DSSPUBKEY *) (bh + 1);
748 if (dp->magic != 0x31535344) {
750 BIO_snprintf(magstr, 10, "%lx", dp->magic);
751 CAPIerr(CAPI_F_CAPI_GET_PKEY,
752 CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
753 ERR_add_error_data(2, "magic=0x", magstr);
756 dsa_plen = dp->bitlen / 8;
757 btmp = (unsigned char *)(dp + 1);
758 dkey = DSA_new_method(eng);
765 if (p == NULL || q == NULL || g == NULL || pub_key == NULL) {
772 DSA_set0_pqg(dkey, p, q, g);
773 DSA_set0_key(dkey, pub_key, NULL);
774 if (!lend_tobn(p, btmp, dsa_plen))
777 if (!lend_tobn(q, btmp, 20))
780 if (!lend_tobn(g, btmp, dsa_plen))
783 if (!lend_tobn(pub_key, btmp, dsa_plen))
787 DSA_set_ex_data(dkey, dsa_capi_idx, key);
789 if ((ret = EVP_PKEY_new()) == NULL)
792 EVP_PKEY_assign_DSA(ret, dkey);
797 BIO_snprintf(algstr, 10, "%ux", bh->aiKeyAlg);
798 CAPIerr(CAPI_F_CAPI_GET_PKEY,
799 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
800 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
805 OPENSSL_free(pubkey);
808 # ifndef OPENSSL_NO_DSA
816 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
821 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
822 UI_METHOD *ui_method, void *callback_data)
827 ctx = ENGINE_get_ex_data(eng, capi_idx);
830 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
834 key = capi_find_key(ctx, key_id);
839 ret = capi_get_pkey(eng, key);
847 /* CryptoAPI RSA operations */
849 int capi_rsa_priv_enc(int flen, const unsigned char *from,
850 unsigned char *to, RSA *rsa, int padding)
852 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
856 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
857 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
867 ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
869 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
871 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
873 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
876 /* Convert the signature type to a CryptoAPI algorithm ID */
899 alg = CALG_SSL3_SHAMD5;
904 BIO_snprintf(algstr, 10, "%x", dtype);
905 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
906 ERR_add_error_data(2, "NID=0x", algstr);
911 /* Create the hash object */
912 if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
913 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
917 /* Set the hash value to the value passed */
919 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
920 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
925 /* Finally sign it */
926 slen = RSA_size(rsa);
927 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
928 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
933 /* Inplace byte reversal of signature */
934 for (i = 0; i < slen / 2; i++) {
937 sigret[i] = sigret[slen - i - 1];
938 sigret[slen - i - 1] = c;
946 CryptDestroyHash(hash);
951 int capi_rsa_priv_dec(int flen, const unsigned char *from,
952 unsigned char *to, RSA *rsa, int padding)
955 unsigned char *tmpbuf;
963 ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
965 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
967 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
969 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
973 if (padding != RSA_PKCS1_PADDING) {
975 BIO_snprintf(errstr, 10, "%d", padding);
976 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
977 ERR_add_error_data(2, "padding=", errstr);
981 /* Create temp reverse order version of input */
982 if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
983 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
986 for (i = 0; i < flen; i++)
987 tmpbuf[flen - i - 1] = from[i];
989 /* Finally decrypt it */
991 if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &dlen)) {
992 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
994 OPENSSL_free(tmpbuf);
997 memcpy(to, tmpbuf, (flen = (int)dlen));
999 OPENSSL_free(tmpbuf);
1004 static int capi_rsa_free(RSA *rsa)
1007 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
1008 capi_free_key(capi_key);
1009 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
1013 # ifndef OPENSSL_NO_DSA
1014 /* CryptoAPI DSA operations */
1016 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
1021 DSA_SIG *ret = NULL;
1024 unsigned char csigbuf[40];
1026 ctx = ENGINE_get_ex_data(DSA_get0_engine(dsa), capi_idx);
1028 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
1030 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1033 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
1038 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
1042 /* Create the hash object */
1043 if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
1044 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
1045 capi_addlasterror();
1049 /* Set the hash value to the value passed */
1050 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
1051 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
1052 capi_addlasterror();
1056 /* Finally sign it */
1057 slen = sizeof(csigbuf);
1058 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
1059 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1060 capi_addlasterror();
1063 BIGNUM *r = NULL, *s = NULL;
1064 ret = DSA_SIG_new();
1067 DSA_SIG_get0(&r, &s, ret);
1068 if (!lend_tobn(r, csigbuf, 20)
1069 || !lend_tobn(s, csigbuf + 20, 20)) {
1079 OPENSSL_cleanse(csigbuf, 40);
1080 CryptDestroyHash(hash);
1084 static int capi_dsa_free(DSA *dsa)
1087 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1088 capi_free_key(capi_key);
1089 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1094 static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
1099 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1101 out = BIO_new_file(ctx->debug_file, "a+");
1103 CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
1106 BIO_vprintf(out, format, argptr);
1110 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
1113 va_start(args, format);
1114 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1118 static void capi_addlasterror(void)
1120 capi_adderror(GetLastError());
1123 static void capi_adderror(DWORD err)
1126 BIO_snprintf(errstr, 10, "%lX", err);
1127 ERR_add_error_data(2, "Error code= 0x", errstr);
1130 static char *wide_to_asc(LPCWSTR wstr)
1137 len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1138 sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1140 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1143 str = OPENSSL_malloc(sz);
1145 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1148 if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1150 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1156 static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
1161 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1162 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1163 err = GetLastError();
1164 if (err == ERROR_NO_MORE_ITEMS)
1166 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1170 name = OPENSSL_malloc(len);
1172 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1175 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1176 err = GetLastError();
1178 if (err == ERROR_NO_MORE_ITEMS)
1180 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1184 if (sizeof(TCHAR) != sizeof(char)) {
1185 *pname = wide_to_asc((WCHAR *)name);
1190 *pname = (char *)name;
1191 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1197 static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
1201 LPSTR provname = NULL;
1202 CAPI_trace(ctx, "capi_list_providers\n");
1203 BIO_printf(out, "Available CSPs:\n");
1204 for (idx = 0;; idx++) {
1205 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1210 BIO_printf(out, "%lu. %s, type %lu\n", idx, provname, ptype);
1211 OPENSSL_free(provname);
1216 static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
1220 DWORD err, idx, flags, buflen = 0, clen;
1222 LPTSTR cspname = NULL;
1224 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1226 if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
1228 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
1229 cspname = alloca(clen * sizeof(WCHAR));
1230 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1234 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1235 capi_addlasterror();
1239 cspname = (TCHAR *)ctx->cspname;
1240 if (!CryptAcquireContext
1241 (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
1242 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1243 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1244 capi_addlasterror();
1247 if (!CryptGetProvParam
1248 (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
1249 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1250 capi_addlasterror();
1251 CryptReleaseContext(hprov, 0);
1254 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1257 cname = OPENSSL_malloc(buflen);
1258 if (cname == NULL) {
1259 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1263 for (idx = 0;; idx++) {
1268 flags = CRYPT_FIRST;
1271 if (!CryptGetProvParam
1272 (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
1273 err = GetLastError();
1274 if (err == ERROR_NO_MORE_ITEMS)
1276 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1280 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1281 cname, clen, idx, flags);
1282 if (!cname[0] && (clen == buflen)) {
1283 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1286 BIO_printf(out, "%lu. %s\n", idx, cname);
1293 OPENSSL_free(cname);
1294 CryptReleaseContext(hprov, 0);
1299 static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1302 CRYPT_KEY_PROV_INFO *pinfo;
1304 if (!CertGetCertificateContextProperty
1305 (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1307 pinfo = OPENSSL_malloc(len);
1308 if (pinfo == NULL) {
1309 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1312 if (!CertGetCertificateContextProperty
1313 (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
1314 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1315 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1316 capi_addlasterror();
1317 OPENSSL_free(pinfo);
1323 static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
1324 CRYPT_KEY_PROV_INFO * pinfo)
1326 char *provname = NULL, *contname = NULL;
1328 BIO_printf(out, " No Private Key\n");
1331 provname = wide_to_asc(pinfo->pwszProvName);
1332 contname = wide_to_asc(pinfo->pwszContainerName);
1333 if (!provname || !contname)
1336 BIO_printf(out, " Private Key Info:\n");
1337 BIO_printf(out, " Provider Name: %s, Provider Type %lu\n", provname,
1339 BIO_printf(out, " Container Name: %s, Key Type %lu\n", contname,
1342 OPENSSL_free(provname);
1343 OPENSSL_free(contname);
1346 static char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1351 CAPI_trace(ctx, "capi_cert_get_fname\n");
1352 if (!CertGetCertificateContextProperty
1353 (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1355 wfname = OPENSSL_malloc(dlen);
1358 if (CertGetCertificateContextProperty
1359 (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
1360 char *fname = wide_to_asc(wfname);
1361 OPENSSL_free(wfname);
1364 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1365 capi_addlasterror();
1367 OPENSSL_free(wfname);
1371 static void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
1374 const unsigned char *p;
1375 unsigned long flags = ctx->dump_flags;
1376 if (flags & CAPI_DMP_FNAME) {
1378 fname = capi_cert_get_fname(ctx, cert);
1380 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1381 OPENSSL_free(fname);
1383 BIO_printf(out, " <No Friendly Name>\n");
1386 p = cert->pbCertEncoded;
1387 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1389 BIO_printf(out, " <Can't parse certificate>\n");
1390 if (flags & CAPI_DMP_SUMMARY) {
1391 BIO_printf(out, " Subject: ");
1392 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1393 BIO_printf(out, "\n Issuer: ");
1394 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1395 BIO_printf(out, "\n");
1397 if (flags & CAPI_DMP_FULL)
1398 X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
1400 if (flags & CAPI_DMP_PKEYINFO) {
1401 CRYPT_KEY_PROV_INFO *pinfo;
1402 pinfo = capi_get_prov_info(ctx, cert);
1403 capi_dump_prov_info(ctx, out, pinfo);
1404 OPENSSL_free(pinfo);
1407 if (flags & CAPI_DMP_PEM)
1408 PEM_write_bio_X509(out, x);
1412 static HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
1417 storename = ctx->storename;
1420 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1422 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1423 ctx->store_flags, storename);
1425 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1426 capi_addlasterror();
1431 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
1437 PCCERT_CONTEXT cert = NULL;
1439 storename = ctx->storename;
1442 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1444 hstore = capi_open_store(ctx, storename);
1448 cert = capi_find_cert(ctx, id, hstore);
1453 capi_dump_cert(ctx, out, cert);
1454 CertFreeCertificateContext(cert);
1456 for (idx = 0;; idx++) {
1457 cert = CertEnumCertificatesInStore(hstore, cert);
1460 BIO_printf(out, "Certificate %d\n", idx);
1461 capi_dump_cert(ctx, out, cert);
1465 CertCloseStore(hstore, 0);
1469 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
1472 PCCERT_CONTEXT cert = NULL;
1475 switch (ctx->lookup_method) {
1476 case CAPI_LU_SUBSTR:
1477 return CertFindCertificateInStore(hstore,
1478 X509_ASN_ENCODING, 0,
1479 CERT_FIND_SUBJECT_STR_A, id, NULL);
1482 cert = CertEnumCertificatesInStore(hstore, cert);
1485 fname = capi_cert_get_fname(ctx, cert);
1487 if (strcmp(fname, id))
1491 OPENSSL_free(fname);
1501 static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
1502 TCHAR *provname, DWORD ptype, DWORD keyspec)
1505 CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
1509 /* If PROV_RSA_AES supported use it instead */
1510 if (ptype == PROV_RSA_FULL && use_aes_csp) {
1512 ptype = PROV_RSA_AES;
1513 CAPI_trace(ctx, "capi_get_key, contname=%s, RSA_AES_CSP\n", contname);
1514 } else if (sizeof(TCHAR) == sizeof(char)) {
1515 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1516 contname, provname, ptype);
1517 } else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
1518 /* above 'if' is optimization to minimize malloc-ations */
1519 char *_contname = wide_to_asc((WCHAR *)contname);
1520 char *_provname = wide_to_asc((WCHAR *)provname);
1522 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1523 _contname, _provname, ptype);
1524 OPENSSL_free(_provname);
1525 OPENSSL_free(_contname);
1527 if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1528 dwFlags = CRYPT_MACHINE_KEYSET;
1529 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
1530 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1531 capi_addlasterror();
1534 if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1535 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1536 capi_addlasterror();
1537 CryptReleaseContext(key->hprov, 0);
1540 key->keyspec = keyspec;
1549 static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1551 CAPI_KEY *key = NULL;
1552 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1553 char *provname = NULL, *contname = NULL;
1554 pinfo = capi_get_prov_info(ctx, cert);
1557 if (sizeof(TCHAR) != sizeof(char))
1558 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1559 (TCHAR *)pinfo->pwszProvName,
1560 pinfo->dwProvType, pinfo->dwKeySpec);
1562 provname = wide_to_asc(pinfo->pwszProvName);
1563 contname = wide_to_asc(pinfo->pwszContainerName);
1564 if (!provname || !contname)
1566 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1567 pinfo->dwProvType, pinfo->dwKeySpec);
1571 OPENSSL_free(pinfo);
1572 OPENSSL_free(provname);
1573 OPENSSL_free(contname);
1577 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
1579 PCCERT_CONTEXT cert;
1581 CAPI_KEY *key = NULL;
1582 switch (ctx->lookup_method) {
1583 case CAPI_LU_SUBSTR:
1585 hstore = capi_open_store(ctx, NULL);
1588 cert = capi_find_cert(ctx, id, hstore);
1590 key = capi_get_cert_key(ctx, cert);
1591 CertFreeCertificateContext(cert);
1593 CertCloseStore(hstore, 0);
1596 case CAPI_LU_CONTNAME:
1597 if (sizeof(TCHAR) != sizeof(char)) {
1598 WCHAR *contname, *provname;
1601 if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1602 (contname = alloca(len * sizeof(WCHAR)),
1603 MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1605 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
1607 alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
1614 capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1615 ctx->csptype, ctx->keytype);
1617 key = capi_get_key(ctx, (TCHAR *)id,
1618 (TCHAR *)ctx->cspname,
1619 ctx->csptype, ctx->keytype);
1626 void capi_free_key(CAPI_KEY * key)
1630 CryptDestroyKey(key->key);
1631 CryptReleaseContext(key->hprov, 0);
1633 CertFreeCertificateContext(key->pcert);
1637 /* Initialize a CAPI_CTX structure */
1639 static CAPI_CTX *capi_ctx_new(void)
1641 CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
1644 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1647 ctx->csptype = PROV_RSA_FULL;
1648 ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1649 ctx->keytype = AT_KEYEXCHANGE;
1650 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1651 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1652 ctx->lookup_method = CAPI_LU_SUBSTR;
1653 ctx->client_cert_select = cert_select_simple;
1657 static void capi_ctx_free(CAPI_CTX * ctx)
1659 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1662 OPENSSL_free(ctx->cspname);
1663 OPENSSL_free(ctx->debug_file);
1664 OPENSSL_free(ctx->storename);
1665 OPENSSL_free(ctx->ssl_client_store);
1669 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
1672 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1677 if (sizeof(TCHAR) != sizeof(char)) {
1679 if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1680 name = alloca(len * sizeof(WCHAR));
1681 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1684 name = (TCHAR *)pname;
1686 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1687 CRYPT_VERIFYCONTEXT)) {
1688 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1689 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1690 capi_addlasterror();
1693 CryptReleaseContext(hprov, 0);
1695 OPENSSL_free(ctx->cspname);
1696 ctx->cspname = OPENSSL_strdup(pname);
1697 ctx->csptype = type;
1701 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
1706 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1708 res = capi_ctx_set_provname(ctx, pname, type, 0);
1709 OPENSSL_free(pname);
1713 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1717 /* Special case: empty list: match anything */
1718 if (sk_X509_NAME_num(ca_dn) <= 0)
1720 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1721 nm = sk_X509_NAME_value(ca_dn, i);
1722 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1728 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1729 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1730 EVP_PKEY **pkey, STACK_OF(X509) **pother,
1731 UI_METHOD *ui_method,
1732 void *callback_data)
1734 STACK_OF(X509) *certs = NULL;
1737 const unsigned char *p;
1738 int i, client_cert_idx;
1740 PCCERT_CONTEXT cert = NULL, excert = NULL;
1743 ctx = ENGINE_get_ex_data(e, capi_idx);
1748 storename = ctx->ssl_client_store;
1752 hstore = capi_open_store(ctx, storename);
1755 /* Enumerate all certificates collect any matches */
1757 cert = CertEnumCertificatesInStore(hstore, cert);
1760 p = cert->pbCertEncoded;
1761 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1763 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1766 if (cert_issuer_match(ca_dn, x)
1767 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1768 key = capi_get_cert_key(ctx, cert);
1774 * Match found: attach extra data to it so we can retrieve the
1777 excert = CertDuplicateCertificateContext(cert);
1778 key->pcert = excert;
1779 X509_set_ex_data(x, cert_capi_idx, key);
1782 certs = sk_X509_new_null();
1784 sk_X509_push(certs, x);
1791 CertFreeCertificateContext(cert);
1793 CertCloseStore(hstore, 0);
1798 /* Select the appropriate certificate */
1800 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1802 /* Set the selected certificate and free the rest */
1804 for (i = 0; i < sk_X509_num(certs); i++) {
1805 x = sk_X509_value(certs, i);
1806 if (i == client_cert_idx)
1809 key = X509_get_ex_data(x, cert_capi_idx);
1815 sk_X509_free(certs);
1820 /* Setup key for selected certificate */
1822 key = X509_get_ex_data(*pcert, cert_capi_idx);
1823 *pkey = capi_get_pkey(e, key);
1824 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1830 /* Simple client cert selection function: always select first */
1832 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1837 # ifdef OPENSSL_CAPIENG_DIALOG
1840 * More complex cert selection function, using standard function
1841 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1845 * Definitions which are in cryptuiapi.h but this is not present in older
1846 * versions of headers.
1849 # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1850 # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1851 # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1854 # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1855 # define dlg_prompt L"Select a certificate to use for authentication"
1856 # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1857 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1859 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1863 PCCERT_CONTEXT cert;
1868 if (sk_X509_num(certs) == 1)
1870 ctx = ENGINE_get_ex_data(e, capi_idx);
1871 /* Create an in memory store of certificates */
1872 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1873 CERT_STORE_CREATE_NEW_FLAG, NULL);
1875 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1876 capi_addlasterror();
1879 /* Add all certificates to store */
1880 for (i = 0; i < sk_X509_num(certs); i++) {
1881 x = sk_X509_value(certs, i);
1882 key = X509_get_ex_data(x, cert_capi_idx);
1884 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1885 CERT_STORE_ADD_NEW, NULL)) {
1886 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1887 capi_addlasterror();
1892 hwnd = GetForegroundWindow();
1894 hwnd = GetActiveWindow();
1895 if (!hwnd && ctx->getconswindow)
1896 hwnd = ctx->getconswindow();
1897 /* Call dialog to select one */
1898 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1899 dlg_columns, 0, NULL);
1901 /* Find matching cert from list */
1903 for (i = 0; i < sk_X509_num(certs); i++) {
1904 x = sk_X509_value(certs, i);
1905 key = X509_get_ex_data(x, cert_capi_idx);
1906 if (CertCompareCertificate
1907 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1908 key->pcert->pCertInfo)) {
1917 CertCloseStore(dstore, 0);
1923 #else /* !__COMPILE_CAPIENG */
1924 # include <openssl/engine.h>
1925 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1927 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1929 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1934 IMPLEMENT_DYNAMIC_CHECK_FN()
1936 void engine_load_capi_int(void);
1937 void engine_load_capi_int(void)