3 * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
6 /* ====================================================================
7 * Copyright (c) 2008 The OpenSSL Project. All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the
21 * 3. All advertising materials mentioning features or use of this
22 * software must display the following acknowledgment:
23 * "This product includes software developed by the OpenSSL Project
24 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
26 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27 * endorse or promote products derived from this software without
28 * prior written permission. For written permission, please contact
29 * licensing@OpenSSL.org.
31 * 5. Products derived from this software may not be called "OpenSSL"
32 * nor may "OpenSSL" appear in their names without prior written
33 * permission of the OpenSSL Project.
35 * 6. Redistributions of any form whatsoever must retain the following
37 * "This product includes software developed by the OpenSSL Project
38 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
40 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
44 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51 * OF THE POSSIBILITY OF SUCH DAMAGE.
52 * ====================================================================
59 #include <openssl/crypto.h>
61 #ifdef OPENSSL_SYS_WIN32
62 # ifndef OPENSSL_NO_CAPIENG
64 # include <openssl/buffer.h>
65 # include <openssl/bn.h>
66 # include <openssl/rsa.h>
67 # include <openssl/dsa.h>
70 # define _WIN32_WINNT 0x0400
74 # include <wincrypt.h>
77 # define alloca _alloca
81 * This module uses several "new" interfaces, among which is
82 * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is
83 * one of possible values you can pass to function in question. By
84 * checking if it's defined we can see if wincrypt.h and accompanying
85 * crypt32.lib are in shape. The native MingW32 headers up to and
86 * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the
87 * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG,
88 * so we check for these too and avoid compiling.
89 * Yes, it's rather "weak" test and if compilation fails,
90 * then re-configure with -DOPENSSL_NO_CAPIENG.
92 # if defined(CERT_KEY_PROV_INFO_PROP_ID) && \
93 defined(CERT_STORE_PROV_SYSTEM_A) && \
94 defined(CERT_STORE_READONLY_FLAG)
95 # define __COMPILE_CAPIENG
96 # endif /* CERT_KEY_PROV_INFO_PROP_ID */
97 # endif /* OPENSSL_NO_CAPIENG */
98 #endif /* OPENSSL_SYS_WIN32 */
100 #ifdef __COMPILE_CAPIENG
102 # undef X509_EXTENSIONS
104 /* Definitions which may be missing from earlier version of headers */
105 # ifndef CERT_STORE_OPEN_EXISTING_FLAG
106 # define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
109 # ifndef CERT_STORE_CREATE_NEW_FLAG
110 # define CERT_STORE_CREATE_NEW_FLAG 0x00002000
113 # ifndef CERT_SYSTEM_STORE_CURRENT_USER
114 # define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000
117 # ifndef ALG_SID_SHA_256
118 # define ALG_SID_SHA_256 12
120 # ifndef ALG_SID_SHA_384
121 # define ALG_SID_SHA_384 13
123 # ifndef ALG_SID_SHA_512
124 # define ALG_SID_SHA_512 14
127 # ifndef CALG_SHA_256
128 # define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
130 # ifndef CALG_SHA_384
131 # define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
133 # ifndef CALG_SHA_512
134 # define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
137 # include <openssl/engine.h>
138 # include <openssl/pem.h>
139 # include <openssl/x509v3.h>
141 # include "e_capi_err.h"
142 # include "e_capi_err.c"
144 static const char *engine_capi_id = "capi";
145 static const char *engine_capi_name = "CryptoAPI ENGINE";
147 typedef struct CAPI_CTX_st CAPI_CTX;
148 typedef struct CAPI_KEY_st CAPI_KEY;
150 static void capi_addlasterror(void);
151 static void capi_adderror(DWORD err);
153 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...);
155 static int capi_list_providers(CAPI_CTX * ctx, BIO *out);
156 static int capi_list_containers(CAPI_CTX * ctx, BIO *out);
157 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *storename);
158 void capi_free_key(CAPI_KEY * key);
160 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
163 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id);
165 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
166 UI_METHOD *ui_method, void *callback_data);
167 static int capi_rsa_sign(int dtype, const unsigned char *m,
168 unsigned int m_len, unsigned char *sigret,
169 unsigned int *siglen, const RSA *rsa);
170 static int capi_rsa_priv_enc(int flen, const unsigned char *from,
171 unsigned char *to, RSA *rsa, int padding);
172 static int capi_rsa_priv_dec(int flen, const unsigned char *from,
173 unsigned char *to, RSA *rsa, int padding);
174 static int capi_rsa_free(RSA *rsa);
176 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
178 static int capi_dsa_free(DSA *dsa);
180 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
181 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
182 EVP_PKEY **pkey, STACK_OF(X509) **pother,
183 UI_METHOD *ui_method,
184 void *callback_data);
186 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
187 # ifdef OPENSSL_CAPIENG_DIALOG
188 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
191 typedef PCCERT_CONTEXT(WINAPI *CERTDLG) (HCERTSTORE, HWND, LPCWSTR,
192 LPCWSTR, DWORD, DWORD, void *);
193 typedef HWND(WINAPI *GETCONSWIN) (void);
196 * This structure contains CAPI ENGINE specific data: it contains various
197 * global options and affects how other functions behave.
200 # define CAPI_DBG_TRACE 2
201 # define CAPI_DBG_ERROR 1
206 /* Parameters to use for container lookup */
210 /* Certificate store name to use */
212 LPSTR ssl_client_store;
213 /* System store flags */
215 /* Lookup string meanings in load_private_key */
216 /* Substring of subject: uses "storename" */
217 # define CAPI_LU_SUBSTR 1
218 /* Friendly name: uses storename */
219 # define CAPI_LU_FNAME 2
220 /* Container name: uses cspname, keytype */
221 # define CAPI_LU_CONTNAME 3
223 /* Info to dump with dumpcerts option */
224 /* Issuer and serial name strings */
225 # define CAPI_DMP_SUMMARY 0x1
227 # define CAPI_DMP_FNAME 0x2
228 /* Full X509_print dump */
229 # define CAPI_DMP_FULL 0x4
230 /* Dump PEM format certificate */
231 # define CAPI_DMP_PEM 0x8
232 /* Dump pseudo key (if possible) */
233 # define CAPI_DMP_PSKEY 0x10
234 /* Dump key info (if possible) */
235 # define CAPI_DMP_PKEYINFO 0x20
237 int (*client_cert_select) (ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
238 CERTDLG certselectdlg;
239 GETCONSWIN getconswindow;
242 static CAPI_CTX *capi_ctx_new();
243 static void capi_ctx_free(CAPI_CTX * ctx);
244 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
246 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx);
248 # define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
249 # define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
250 # define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
251 # define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
252 # define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
253 # define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
254 # define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
255 # define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
256 # define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
257 # define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
258 # define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
259 # define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
260 # define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
261 # define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
263 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
264 {CAPI_CMD_LIST_CERTS,
266 "List all certificates in store",
267 ENGINE_CMD_FLAG_NO_INPUT},
268 {CAPI_CMD_LOOKUP_CERT,
270 "Lookup and output certificates",
271 ENGINE_CMD_FLAG_STRING},
272 {CAPI_CMD_DEBUG_LEVEL,
274 "debug level (1=errors, 2=trace)",
275 ENGINE_CMD_FLAG_NUMERIC},
276 {CAPI_CMD_DEBUG_FILE,
278 "debugging filename)",
279 ENGINE_CMD_FLAG_STRING},
282 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
283 ENGINE_CMD_FLAG_NUMERIC},
287 ENGINE_CMD_FLAG_NO_INPUT},
288 {CAPI_CMD_SET_CSP_IDX,
291 ENGINE_CMD_FLAG_NUMERIC},
292 {CAPI_CMD_SET_CSP_NAME,
294 "Set CSP name, (default CSP used if not specified)",
295 ENGINE_CMD_FLAG_STRING},
296 {CAPI_CMD_SET_CSP_TYPE,
298 "Set CSP type, (default RSA_PROV_FULL)",
299 ENGINE_CMD_FLAG_NUMERIC},
300 {CAPI_CMD_LIST_CONTAINERS,
302 "list container names",
303 ENGINE_CMD_FLAG_NO_INPUT},
304 {CAPI_CMD_LIST_OPTIONS,
306 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
307 "32=private key info)",
308 ENGINE_CMD_FLAG_NUMERIC},
309 {CAPI_CMD_LOOKUP_METHOD,
311 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
312 ENGINE_CMD_FLAG_NUMERIC},
313 {CAPI_CMD_STORE_NAME,
315 "certificate store name, default \"MY\"",
316 ENGINE_CMD_FLAG_STRING},
317 {CAPI_CMD_STORE_FLAGS,
319 "Certificate store flags: 1 = system store",
320 ENGINE_CMD_FLAG_NUMERIC},
325 static int capi_idx = -1;
326 static int rsa_capi_idx = -1;
327 static int dsa_capi_idx = -1;
328 static int cert_capi_idx = -1;
330 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
335 if (capi_idx == -1) {
336 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
339 ctx = ENGINE_get_ex_data(e, capi_idx);
340 out = BIO_new_fp(stdout, BIO_NOCLOSE);
342 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_FILE_OPEN_ERROR);
346 case CAPI_CMD_LIST_CSPS:
347 ret = capi_list_providers(ctx, out);
350 case CAPI_CMD_LIST_CERTS:
351 ret = capi_list_certs(ctx, out, NULL);
354 case CAPI_CMD_LOOKUP_CERT:
355 ret = capi_list_certs(ctx, out, p);
358 case CAPI_CMD_LIST_CONTAINERS:
359 ret = capi_list_containers(ctx, out);
362 case CAPI_CMD_STORE_NAME:
363 OPENSSL_free(ctx->storename);
364 ctx->storename = BUF_strdup(p);
365 CAPI_trace(ctx, "Setting store name to %s\n", p);
368 case CAPI_CMD_STORE_FLAGS:
370 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
371 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
373 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
374 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
376 CAPI_trace(ctx, "Setting flags to %d\n", i);
379 case CAPI_CMD_DEBUG_LEVEL:
380 ctx->debug_level = (int)i;
381 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
384 case CAPI_CMD_DEBUG_FILE:
385 ctx->debug_file = BUF_strdup(p);
386 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
389 case CAPI_CMD_KEYTYPE:
391 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
394 case CAPI_CMD_SET_CSP_IDX:
395 ret = capi_ctx_set_provname_idx(ctx, i);
398 case CAPI_CMD_LIST_OPTIONS:
402 case CAPI_CMD_LOOKUP_METHOD:
403 if (i < 1 || i > 3) {
404 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
408 ctx->lookup_method = i;
411 case CAPI_CMD_SET_CSP_NAME:
412 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
415 case CAPI_CMD_SET_CSP_TYPE:
420 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
429 static RSA_METHOD capi_rsa_method = {
430 "CryptoAPI RSA method",
433 capi_rsa_priv_enc, /* priv_enc */
434 capi_rsa_priv_dec, /* priv_dec */
438 capi_rsa_free, /* finish */
439 RSA_FLAG_SIGN_VER, /* flags */
441 capi_rsa_sign, /* rsa_sign */
445 static DSA_METHOD capi_dsa_method = {
446 "CryptoAPI DSA method",
447 capi_dsa_do_sign, /* dsa_do_sign */
448 0, /* dsa_sign_setup */
449 0, /* dsa_do_verify */
453 capi_dsa_free, /* finish */
456 0, /* dsa_paramgen */
460 static int capi_init(ENGINE *e)
463 const RSA_METHOD *ossl_rsa_meth;
464 const DSA_METHOD *ossl_dsa_meth;
467 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
471 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
473 /* Setup RSA_METHOD */
474 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
475 ossl_rsa_meth = RSA_PKCS1_SSLeay();
476 capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc;
477 capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec;
478 capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp;
479 capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp;
481 /* Setup DSA Method */
482 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
483 ossl_dsa_meth = DSA_OpenSSL();
484 capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify;
485 capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp;
486 capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp;
489 ctx = capi_ctx_new();
493 ENGINE_set_ex_data(e, capi_idx, ctx);
495 # ifdef OPENSSL_CAPIENG_DIALOG
497 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
498 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
501 (CERTDLG) GetProcAddress(cryptui,
502 "CryptUIDlgSelectCertificateFromStore");
505 (GETCONSWIN) GetProcAddress(kernel, "GetConsoleWindow");
506 if (cryptui && !OPENSSL_isservice())
507 ctx->client_cert_select = cert_select_dialog;
514 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
520 static int capi_destroy(ENGINE *e)
522 ERR_unload_CAPI_strings();
526 static int capi_finish(ENGINE *e)
529 ctx = ENGINE_get_ex_data(e, capi_idx);
531 ENGINE_set_ex_data(e, capi_idx, NULL);
536 * CryptoAPI key application data. This contains a handle to the private key
537 * container (for sign operations) and a handle to the key (for decrypt
542 /* Associated certificate context (if any) */
543 PCCERT_CONTEXT pcert;
549 static int bind_capi(ENGINE *e)
551 if (!ENGINE_set_id(e, engine_capi_id)
552 || !ENGINE_set_name(e, engine_capi_name)
553 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
554 || !ENGINE_set_init_function(e, capi_init)
555 || !ENGINE_set_finish_function(e, capi_finish)
556 || !ENGINE_set_destroy_function(e, capi_destroy)
557 || !ENGINE_set_RSA(e, &capi_rsa_method)
558 || !ENGINE_set_DSA(e, &capi_dsa_method)
559 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
560 || !ENGINE_set_load_ssl_client_cert_function(e,
561 capi_load_ssl_client_cert)
562 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
563 || !ENGINE_set_ctrl_function(e, capi_ctrl))
565 ERR_load_CAPI_strings();
571 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
572 static int bind_helper(ENGINE *e, const char *id)
574 if (id && (strcmp(id, engine_capi_id) != 0))
581 IMPLEMENT_DYNAMIC_CHECK_FN()
582 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
584 static ENGINE *engine_capi(void)
586 ENGINE *ret = ENGINE_new();
589 if (!bind_capi(ret)) {
596 void ENGINE_load_capi(void)
598 /* Copied from eng_[openssl|dyn].c */
599 ENGINE *toadd = engine_capi();
608 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
612 * Reverse buffer in place: since this is a keyblob structure that will
613 * be freed up after conversion anyway it doesn't matter if we change
616 for (i = 0; i < binlen / 2; i++) {
619 bin[i] = bin[binlen - i - 1];
620 bin[binlen - i - 1] = c;
623 if (!BN_bin2bn(bin, binlen, bn))
628 /* Given a CAPI_KEY get an EVP_PKEY structure */
630 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
632 unsigned char *pubkey = NULL;
637 EVP_PKEY *ret = NULL;
638 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
639 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
644 pubkey = OPENSSL_malloc(len);
649 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
650 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
655 bh = (BLOBHEADER *) pubkey;
656 if (bh->bType != PUBLICKEYBLOB) {
657 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
660 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
663 unsigned char *rsa_modulus;
664 rp = (RSAPUBKEY *) (bh + 1);
665 if (rp->magic != 0x31415352) {
667 BIO_snprintf(magstr, 10, "%lx", rp->magic);
668 CAPIerr(CAPI_F_CAPI_GET_PKEY,
669 CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
670 ERR_add_error_data(2, "magic=0x", magstr);
673 rsa_modulus = (unsigned char *)(rp + 1);
674 rkey = RSA_new_method(eng);
681 if (!rkey->e || !rkey->n)
684 if (!BN_set_word(rkey->e, rp->pubexp))
687 rsa_modlen = rp->bitlen / 8;
688 if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
691 RSA_set_ex_data(rkey, rsa_capi_idx, key);
693 if ((ret = EVP_PKEY_new()) == NULL)
696 EVP_PKEY_assign_RSA(ret, rkey);
699 } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
703 dp = (DSSPUBKEY *) (bh + 1);
704 if (dp->magic != 0x31535344) {
706 BIO_snprintf(magstr, 10, "%lx", dp->magic);
707 CAPIerr(CAPI_F_CAPI_GET_PKEY,
708 CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
709 ERR_add_error_data(2, "magic=0x", magstr);
712 dsa_plen = dp->bitlen / 8;
713 btmp = (unsigned char *)(dp + 1);
714 dkey = DSA_new_method(eng);
720 dkey->pub_key = BN_new();
721 if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key)
723 if (!lend_tobn(dkey->p, btmp, dsa_plen))
726 if (!lend_tobn(dkey->q, btmp, 20))
729 if (!lend_tobn(dkey->g, btmp, dsa_plen))
732 if (!lend_tobn(dkey->pub_key, btmp, dsa_plen))
736 DSA_set_ex_data(dkey, dsa_capi_idx, key);
738 if ((ret = EVP_PKEY_new()) == NULL)
741 EVP_PKEY_assign_DSA(ret, dkey);
745 BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg);
746 CAPIerr(CAPI_F_CAPI_GET_PKEY,
747 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
748 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
753 OPENSSL_free(pubkey);
762 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
767 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
768 UI_METHOD *ui_method, void *callback_data)
773 ctx = ENGINE_get_ex_data(eng, capi_idx);
776 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
780 key = capi_find_key(ctx, key_id);
785 ret = capi_get_pkey(eng, key);
793 /* CryptoAPI RSA operations */
795 int capi_rsa_priv_enc(int flen, const unsigned char *from,
796 unsigned char *to, RSA *rsa, int padding)
798 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
802 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
803 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
813 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
815 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
817 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
819 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
822 /* Convert the signature type to a CryptoAPI algorithm ID */
845 alg = CALG_SSL3_SHAMD5;
850 BIO_snprintf(algstr, 10, "%lx", dtype);
851 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
852 ERR_add_error_data(2, "NID=0x", algstr);
857 /* Create the hash object */
858 if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
859 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
863 /* Set the hash value to the value passed */
865 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
866 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
871 /* Finally sign it */
872 slen = RSA_size(rsa);
873 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
874 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
879 /* Inplace byte reversal of signature */
880 for (i = 0; i < slen / 2; i++) {
883 sigret[i] = sigret[slen - i - 1];
884 sigret[slen - i - 1] = c;
892 CryptDestroyHash(hash);
897 int capi_rsa_priv_dec(int flen, const unsigned char *from,
898 unsigned char *to, RSA *rsa, int padding)
901 unsigned char *tmpbuf;
904 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
906 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
908 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
910 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
914 if (padding != RSA_PKCS1_PADDING) {
916 BIO_snprintf(errstr, 10, "%d", padding);
917 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
918 ERR_add_error_data(2, "padding=", errstr);
922 /* Create temp reverse order version of input */
923 if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
924 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
927 for (i = 0; i < flen; i++)
928 tmpbuf[flen - i - 1] = from[i];
930 /* Finally decrypt it */
931 if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen)) {
932 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
934 OPENSSL_free(tmpbuf);
937 memcpy(to, tmpbuf, flen);
939 OPENSSL_free(tmpbuf);
944 static int capi_rsa_free(RSA *rsa)
947 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
948 capi_free_key(capi_key);
949 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
953 /* CryptoAPI DSA operations */
955 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
963 unsigned char csigbuf[40];
965 ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
967 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
969 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
972 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
977 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
981 /* Create the hash object */
982 if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
983 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
988 /* Set the hash value to the value passed */
989 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
990 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
995 /* Finally sign it */
996 slen = sizeof(csigbuf);
997 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
998 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1002 ret = DSA_SIG_new();
1007 if (!ret->r || !ret->s)
1009 if (!lend_tobn(ret->r, csigbuf, 20)
1010 || !lend_tobn(ret->s, csigbuf + 20, 20)) {
1020 OPENSSL_cleanse(csigbuf, 40);
1021 CryptDestroyHash(hash);
1025 static int capi_dsa_free(DSA *dsa)
1028 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1029 capi_free_key(capi_key);
1030 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1034 static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
1039 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1041 out = BIO_new_file(ctx->debug_file, "a+");
1043 CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
1046 BIO_vprintf(out, format, argptr);
1050 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
1053 va_start(args, format);
1054 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1058 static void capi_addlasterror(void)
1060 capi_adderror(GetLastError());
1063 static void capi_adderror(DWORD err)
1066 BIO_snprintf(errstr, 10, "%lX", err);
1067 ERR_add_error_data(2, "Error code= 0x", errstr);
1070 static char *wide_to_asc(LPCWSTR wstr)
1077 len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1078 sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1080 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1083 str = OPENSSL_malloc(sz);
1085 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1088 if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1090 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1096 static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
1101 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1102 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1103 err = GetLastError();
1104 if (err == ERROR_NO_MORE_ITEMS)
1106 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1110 name = OPENSSL_malloc(len);
1112 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1115 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1116 err = GetLastError();
1118 if (err == ERROR_NO_MORE_ITEMS)
1120 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1124 if (sizeof(TCHAR) != sizeof(char)) {
1125 *pname = wide_to_asc((WCHAR *)name);
1130 *pname = (char *)name;
1131 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1137 static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
1141 LPSTR provname = NULL;
1142 CAPI_trace(ctx, "capi_list_providers\n");
1143 BIO_printf(out, "Available CSPs:\n");
1144 for (idx = 0;; idx++) {
1145 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1150 BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
1151 OPENSSL_free(provname);
1156 static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
1160 DWORD err, idx, flags, buflen = 0, clen;
1162 LPTSTR cspname = NULL;
1164 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1166 if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
1168 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
1169 cspname = alloca(clen * sizeof(WCHAR));
1170 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1174 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1175 capi_addlasterror();
1179 cspname = (TCHAR *)ctx->cspname;
1180 if (!CryptAcquireContext
1181 (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
1182 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1183 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1184 capi_addlasterror();
1187 if (!CryptGetProvParam
1188 (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
1189 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1190 capi_addlasterror();
1191 CryptReleaseContext(hprov, 0);
1194 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1197 cname = OPENSSL_malloc(buflen);
1199 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1203 for (idx = 0;; idx++) {
1208 flags = CRYPT_FIRST;
1211 if (!CryptGetProvParam
1212 (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
1213 err = GetLastError();
1214 if (err == ERROR_NO_MORE_ITEMS)
1216 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1220 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1221 cname, clen, idx, flags);
1222 if (!cname[0] && (clen == buflen)) {
1223 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1226 BIO_printf(out, "%d. %s\n", idx, cname);
1233 OPENSSL_free(cname);
1234 CryptReleaseContext(hprov, 0);
1239 CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1242 CRYPT_KEY_PROV_INFO *pinfo;
1244 if (!CertGetCertificateContextProperty
1245 (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1247 pinfo = OPENSSL_malloc(len);
1249 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1252 if (!CertGetCertificateContextProperty
1253 (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
1254 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1255 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1256 capi_addlasterror();
1257 OPENSSL_free(pinfo);
1263 static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
1264 CRYPT_KEY_PROV_INFO * pinfo)
1266 char *provname = NULL, *contname = NULL;
1268 BIO_printf(out, " No Private Key\n");
1271 provname = wide_to_asc(pinfo->pwszProvName);
1272 contname = wide_to_asc(pinfo->pwszContainerName);
1273 if (!provname || !contname)
1276 BIO_printf(out, " Private Key Info:\n");
1277 BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname,
1279 BIO_printf(out, " Container Name: %s, Key Type %d\n", contname,
1282 OPENSSL_free(provname);
1283 OPENSSL_free(contname);
1286 char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1291 CAPI_trace(ctx, "capi_cert_get_fname\n");
1292 if (!CertGetCertificateContextProperty
1293 (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1295 wfname = OPENSSL_malloc(dlen);
1298 if (CertGetCertificateContextProperty
1299 (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
1300 char *fname = wide_to_asc(wfname);
1301 OPENSSL_free(wfname);
1304 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1305 capi_addlasterror();
1307 OPENSSL_free(wfname);
1311 void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
1315 unsigned long flags = ctx->dump_flags;
1316 if (flags & CAPI_DMP_FNAME) {
1318 fname = capi_cert_get_fname(ctx, cert);
1320 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1321 OPENSSL_free(fname);
1323 BIO_printf(out, " <No Friendly Name>\n");
1326 p = cert->pbCertEncoded;
1327 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1329 BIO_printf(out, " <Can't parse certificate>\n");
1330 if (flags & CAPI_DMP_SUMMARY) {
1331 BIO_printf(out, " Subject: ");
1332 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1333 BIO_printf(out, "\n Issuer: ");
1334 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1335 BIO_printf(out, "\n");
1337 if (flags & CAPI_DMP_FULL)
1338 X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
1340 if (flags & CAPI_DMP_PKEYINFO) {
1341 CRYPT_KEY_PROV_INFO *pinfo;
1342 pinfo = capi_get_prov_info(ctx, cert);
1343 capi_dump_prov_info(ctx, out, pinfo);
1344 OPENSSL_free(pinfo);
1347 if (flags & CAPI_DMP_PEM)
1348 PEM_write_bio_X509(out, x);
1352 HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
1357 storename = ctx->storename;
1360 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1362 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1363 ctx->store_flags, storename);
1365 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1366 capi_addlasterror();
1371 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
1377 PCCERT_CONTEXT cert = NULL;
1379 storename = ctx->storename;
1382 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1384 hstore = capi_open_store(ctx, storename);
1388 cert = capi_find_cert(ctx, id, hstore);
1393 capi_dump_cert(ctx, out, cert);
1394 CertFreeCertificateContext(cert);
1396 for (idx = 0;; idx++) {
1397 cert = CertEnumCertificatesInStore(hstore, cert);
1400 BIO_printf(out, "Certificate %d\n", idx);
1401 capi_dump_cert(ctx, out, cert);
1405 CertCloseStore(hstore, 0);
1409 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
1412 PCCERT_CONTEXT cert = NULL;
1415 switch (ctx->lookup_method) {
1416 case CAPI_LU_SUBSTR:
1417 return CertFindCertificateInStore(hstore,
1418 X509_ASN_ENCODING, 0,
1419 CERT_FIND_SUBJECT_STR_A, id, NULL);
1422 cert = CertEnumCertificatesInStore(hstore, cert);
1425 fname = capi_cert_get_fname(ctx, cert);
1427 if (strcmp(fname, id))
1431 OPENSSL_free(fname);
1441 static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
1442 TCHAR *provname, DWORD ptype, DWORD keyspec)
1445 CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
1449 if (sizeof(TCHAR) == sizeof(char))
1450 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1451 contname, provname, ptype);
1452 else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
1453 /* above 'if' is optimization to minimize malloc-ations */
1454 char *_contname = wide_to_asc((WCHAR *)contname);
1455 char *_provname = wide_to_asc((WCHAR *)provname);
1457 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1458 _contname, _provname, ptype);
1459 OPENSSL_free(_provname);
1460 OPENSSL_free(_contname);
1462 if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1463 dwFlags = CRYPT_MACHINE_KEYSET;
1464 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
1465 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1466 capi_addlasterror();
1469 if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1470 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1471 capi_addlasterror();
1472 CryptReleaseContext(key->hprov, 0);
1475 key->keyspec = keyspec;
1484 static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1486 CAPI_KEY *key = NULL;
1487 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1488 char *provname = NULL, *contname = NULL;
1489 pinfo = capi_get_prov_info(ctx, cert);
1492 if (sizeof(TCHAR) != sizeof(char))
1493 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1494 (TCHAR *)pinfo->pwszProvName,
1495 pinfo->dwProvType, pinfo->dwKeySpec);
1497 provname = wide_to_asc(pinfo->pwszProvName);
1498 contname = wide_to_asc(pinfo->pwszContainerName);
1499 if (!provname || !contname)
1501 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1502 pinfo->dwProvType, pinfo->dwKeySpec);
1506 OPENSSL_free(pinfo);
1507 OPENSSL_free(provname);
1508 OPENSSL_free(contname);
1512 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
1514 PCCERT_CONTEXT cert;
1516 CAPI_KEY *key = NULL;
1517 switch (ctx->lookup_method) {
1518 case CAPI_LU_SUBSTR:
1520 hstore = capi_open_store(ctx, NULL);
1523 cert = capi_find_cert(ctx, id, hstore);
1525 key = capi_get_cert_key(ctx, cert);
1526 CertFreeCertificateContext(cert);
1528 CertCloseStore(hstore, 0);
1531 case CAPI_LU_CONTNAME:
1532 if (sizeof(TCHAR) != sizeof(char)) {
1533 WCHAR *contname, *provname;
1536 if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1537 (contname = alloca(len * sizeof(WCHAR)),
1538 MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1540 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
1542 alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
1549 capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1550 ctx->csptype, ctx->keytype);
1552 key = capi_get_key(ctx, (TCHAR *)id,
1553 (TCHAR *)ctx->cspname,
1554 ctx->csptype, ctx->keytype);
1561 void capi_free_key(CAPI_KEY * key)
1565 CryptDestroyKey(key->key);
1566 CryptReleaseContext(key->hprov, 0);
1568 CertFreeCertificateContext(key->pcert);
1572 /* Initialize a CAPI_CTX structure */
1574 static CAPI_CTX *capi_ctx_new()
1576 CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
1579 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1582 ctx->csptype = PROV_RSA_FULL;
1583 ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1584 ctx->keytype = AT_KEYEXCHANGE;
1585 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1586 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1587 ctx->lookup_method = CAPI_LU_SUBSTR;
1588 ctx->client_cert_select = cert_select_simple;
1592 static void capi_ctx_free(CAPI_CTX * ctx)
1594 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1597 OPENSSL_free(ctx->cspname);
1598 OPENSSL_free(ctx->debug_file);
1599 OPENSSL_free(ctx->storename);
1600 OPENSSL_free(ctx->ssl_client_store);
1604 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
1607 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1612 if (sizeof(TCHAR) != sizeof(char)) {
1614 if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1615 name = alloca(len * sizeof(WCHAR));
1616 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1619 name = (TCHAR *)pname;
1621 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1622 CRYPT_VERIFYCONTEXT)) {
1623 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1624 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1625 capi_addlasterror();
1628 CryptReleaseContext(hprov, 0);
1630 OPENSSL_free(ctx->cspname);
1631 ctx->cspname = BUF_strdup(pname);
1632 ctx->csptype = type;
1636 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
1641 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1643 res = capi_ctx_set_provname(ctx, pname, type, 0);
1644 OPENSSL_free(pname);
1648 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1652 /* Special case: empty list: match anything */
1653 if (sk_X509_NAME_num(ca_dn) <= 0)
1655 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1656 nm = sk_X509_NAME_value(ca_dn, i);
1657 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1663 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1664 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1665 EVP_PKEY **pkey, STACK_OF(X509) **pother,
1666 UI_METHOD *ui_method,
1667 void *callback_data)
1669 STACK_OF(X509) *certs = NULL;
1673 int i, client_cert_idx;
1675 PCCERT_CONTEXT cert = NULL, excert = NULL;
1678 ctx = ENGINE_get_ex_data(e, capi_idx);
1683 storename = ctx->ssl_client_store;
1687 hstore = capi_open_store(ctx, storename);
1690 /* Enumerate all certificates collect any matches */
1692 cert = CertEnumCertificatesInStore(hstore, cert);
1695 p = cert->pbCertEncoded;
1696 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1698 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1701 if (cert_issuer_match(ca_dn, x)
1702 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1703 key = capi_get_cert_key(ctx, cert);
1709 * Match found: attach extra data to it so we can retrieve the
1712 excert = CertDuplicateCertificateContext(cert);
1713 key->pcert = excert;
1714 X509_set_ex_data(x, cert_capi_idx, key);
1717 certs = sk_X509_new_null();
1719 sk_X509_push(certs, x);
1726 CertFreeCertificateContext(cert);
1728 CertCloseStore(hstore, 0);
1733 /* Select the appropriate certificate */
1735 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1737 /* Set the selected certificate and free the rest */
1739 for (i = 0; i < sk_X509_num(certs); i++) {
1740 x = sk_X509_value(certs, i);
1741 if (i == client_cert_idx)
1744 key = X509_get_ex_data(x, cert_capi_idx);
1750 sk_X509_free(certs);
1755 /* Setup key for selected certificate */
1757 key = X509_get_ex_data(*pcert, cert_capi_idx);
1758 *pkey = capi_get_pkey(e, key);
1759 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1765 /* Simple client cert selection function: always select first */
1767 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1772 # ifdef OPENSSL_CAPIENG_DIALOG
1775 * More complex cert selection function, using standard function
1776 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1780 * Definitions which are in cryptuiapi.h but this is not present in older
1781 * versions of headers.
1784 # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1785 # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1786 # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1789 # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1790 # define dlg_prompt L"Select a certificate to use for authentication"
1791 # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1792 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1794 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1798 PCCERT_CONTEXT cert;
1803 if (sk_X509_num(certs) == 1)
1805 ctx = ENGINE_get_ex_data(e, capi_idx);
1806 /* Create an in memory store of certificates */
1807 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1808 CERT_STORE_CREATE_NEW_FLAG, NULL);
1810 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1811 capi_addlasterror();
1814 /* Add all certificates to store */
1815 for (i = 0; i < sk_X509_num(certs); i++) {
1816 x = sk_X509_value(certs, i);
1817 key = X509_get_ex_data(x, cert_capi_idx);
1819 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1820 CERT_STORE_ADD_NEW, NULL)) {
1821 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1822 capi_addlasterror();
1827 hwnd = GetForegroundWindow();
1829 hwnd = GetActiveWindow();
1830 if (!hwnd && ctx->getconswindow)
1831 hwnd = ctx->getconswindow();
1832 /* Call dialog to select one */
1833 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1834 dlg_columns, 0, NULL);
1836 /* Find matching cert from list */
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);
1841 if (CertCompareCertificate
1842 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1843 key->pcert->pCertInfo)) {
1852 CertCloseStore(dstore, 0);
1858 #else /* !__COMPILE_CAPIENG */
1859 # include <openssl/engine.h>
1860 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1862 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1864 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1869 IMPLEMENT_DYNAMIC_CHECK_FN()
1871 void ENGINE_load_capi(void)