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>
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
102 # undef X509_CERT_PAIR
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 case CAPI_CMD_LIST_CSPS:
343 ret = capi_list_providers(ctx, out);
346 case CAPI_CMD_LIST_CERTS:
347 ret = capi_list_certs(ctx, out, NULL);
350 case CAPI_CMD_LOOKUP_CERT:
351 ret = capi_list_certs(ctx, out, p);
354 case CAPI_CMD_LIST_CONTAINERS:
355 ret = capi_list_containers(ctx, out);
358 case CAPI_CMD_STORE_NAME:
360 OPENSSL_free(ctx->storename);
361 ctx->storename = BUF_strdup(p);
362 CAPI_trace(ctx, "Setting store name to %s\n", p);
365 case CAPI_CMD_STORE_FLAGS:
367 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
368 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
370 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
371 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
373 CAPI_trace(ctx, "Setting flags to %d\n", i);
376 case CAPI_CMD_DEBUG_LEVEL:
377 ctx->debug_level = (int)i;
378 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
381 case CAPI_CMD_DEBUG_FILE:
382 ctx->debug_file = BUF_strdup(p);
383 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
386 case CAPI_CMD_KEYTYPE:
388 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
391 case CAPI_CMD_SET_CSP_IDX:
392 ret = capi_ctx_set_provname_idx(ctx, i);
395 case CAPI_CMD_LIST_OPTIONS:
399 case CAPI_CMD_LOOKUP_METHOD:
400 if (i < 1 || i > 3) {
401 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
404 ctx->lookup_method = i;
407 case CAPI_CMD_SET_CSP_NAME:
408 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
411 case CAPI_CMD_SET_CSP_TYPE:
416 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
425 static RSA_METHOD capi_rsa_method = {
426 "CryptoAPI RSA method",
429 capi_rsa_priv_enc, /* priv_enc */
430 capi_rsa_priv_dec, /* priv_dec */
434 capi_rsa_free, /* finish */
435 RSA_FLAG_SIGN_VER, /* flags */
437 capi_rsa_sign, /* rsa_sign */
441 static DSA_METHOD capi_dsa_method = {
442 "CryptoAPI DSA method",
443 capi_dsa_do_sign, /* dsa_do_sign */
444 0, /* dsa_sign_setup */
445 0, /* dsa_do_verify */
449 capi_dsa_free, /* finish */
452 0, /* dsa_paramgen */
456 static int capi_init(ENGINE *e)
459 const RSA_METHOD *ossl_rsa_meth;
460 const DSA_METHOD *ossl_dsa_meth;
463 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
467 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
469 /* Setup RSA_METHOD */
470 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
471 ossl_rsa_meth = RSA_PKCS1_SSLeay();
472 capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc;
473 capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec;
474 capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp;
475 capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp;
477 /* Setup DSA Method */
478 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
479 ossl_dsa_meth = DSA_OpenSSL();
480 capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify;
481 capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp;
482 capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp;
485 ctx = capi_ctx_new();
489 ENGINE_set_ex_data(e, capi_idx, ctx);
491 # ifdef OPENSSL_CAPIENG_DIALOG
493 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
494 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
497 (CERTDLG) GetProcAddress(cryptui,
498 "CryptUIDlgSelectCertificateFromStore");
501 (GETCONSWIN) GetProcAddress(kernel, "GetConsoleWindow");
502 if (cryptui && !OPENSSL_isservice())
503 ctx->client_cert_select = cert_select_dialog;
510 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
516 static int capi_destroy(ENGINE *e)
518 ERR_unload_CAPI_strings();
522 static int capi_finish(ENGINE *e)
525 ctx = ENGINE_get_ex_data(e, capi_idx);
527 ENGINE_set_ex_data(e, capi_idx, NULL);
532 * CryptoAPI key application data. This contains a handle to the private key
533 * container (for sign operations) and a handle to the key (for decrypt
538 /* Associated certificate context (if any) */
539 PCCERT_CONTEXT pcert;
545 static int bind_capi(ENGINE *e)
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 || !ENGINE_set_DSA(e, &capi_dsa_method)
555 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
556 || !ENGINE_set_load_ssl_client_cert_function(e,
557 capi_load_ssl_client_cert)
558 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
559 || !ENGINE_set_ctrl_function(e, capi_ctrl))
561 ERR_load_CAPI_strings();
567 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
568 static int bind_helper(ENGINE *e, const char *id)
570 if (id && (strcmp(id, engine_capi_id) != 0))
577 IMPLEMENT_DYNAMIC_CHECK_FN()
578 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
580 static ENGINE *engine_capi(void)
582 ENGINE *ret = ENGINE_new();
585 if (!bind_capi(ret)) {
592 void ENGINE_load_capi(void)
594 /* Copied from eng_[openssl|dyn].c */
595 ENGINE *toadd = engine_capi();
604 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
608 * Reverse buffer in place: since this is a keyblob structure that will
609 * be freed up after conversion anyway it doesn't matter if we change
612 for (i = 0; i < binlen / 2; i++) {
615 bin[i] = bin[binlen - i - 1];
616 bin[binlen - i - 1] = c;
619 if (!BN_bin2bn(bin, binlen, bn))
624 /* Given a CAPI_KEY get an EVP_PKEY structure */
626 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
628 unsigned char *pubkey = NULL;
633 EVP_PKEY *ret = NULL;
634 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
635 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
640 pubkey = OPENSSL_malloc(len);
645 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
646 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
651 bh = (BLOBHEADER *) pubkey;
652 if (bh->bType != PUBLICKEYBLOB) {
653 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
656 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
659 unsigned char *rsa_modulus;
660 rp = (RSAPUBKEY *) (bh + 1);
661 if (rp->magic != 0x31415352) {
663 BIO_snprintf(magstr, 10, "%lx", rp->magic);
664 CAPIerr(CAPI_F_CAPI_GET_PKEY,
665 CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
666 ERR_add_error_data(2, "magic=0x", magstr);
669 rsa_modulus = (unsigned char *)(rp + 1);
670 rkey = RSA_new_method(eng);
677 if (!rkey->e || !rkey->n)
680 if (!BN_set_word(rkey->e, rp->pubexp))
683 rsa_modlen = rp->bitlen / 8;
684 if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
687 RSA_set_ex_data(rkey, rsa_capi_idx, key);
689 if (!(ret = EVP_PKEY_new()))
692 EVP_PKEY_assign_RSA(ret, rkey);
695 } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
699 dp = (DSSPUBKEY *) (bh + 1);
700 if (dp->magic != 0x31535344) {
702 BIO_snprintf(magstr, 10, "%lx", dp->magic);
703 CAPIerr(CAPI_F_CAPI_GET_PKEY,
704 CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
705 ERR_add_error_data(2, "magic=0x", magstr);
708 dsa_plen = dp->bitlen / 8;
709 btmp = (unsigned char *)(dp + 1);
710 dkey = DSA_new_method(eng);
716 dkey->pub_key = BN_new();
717 if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key)
719 if (!lend_tobn(dkey->p, btmp, dsa_plen))
722 if (!lend_tobn(dkey->q, btmp, 20))
725 if (!lend_tobn(dkey->g, btmp, dsa_plen))
728 if (!lend_tobn(dkey->pub_key, btmp, dsa_plen))
732 DSA_set_ex_data(dkey, dsa_capi_idx, key);
734 if (!(ret = EVP_PKEY_new()))
737 EVP_PKEY_assign_DSA(ret, dkey);
741 BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg);
742 CAPIerr(CAPI_F_CAPI_GET_PKEY,
743 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
744 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
750 OPENSSL_free(pubkey);
761 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
766 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
767 UI_METHOD *ui_method, void *callback_data)
772 ctx = ENGINE_get_ex_data(eng, capi_idx);
775 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
779 key = capi_find_key(ctx, key_id);
784 ret = capi_get_pkey(eng, key);
792 /* CryptoAPI RSA operations */
794 int capi_rsa_priv_enc(int flen, const unsigned char *from,
795 unsigned char *to, RSA *rsa, int padding)
797 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
801 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
802 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
812 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
814 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
816 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
818 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
821 /* Convert the signature type to a CryptoAPI algorithm ID */
844 alg = CALG_SSL3_SHAMD5;
849 BIO_snprintf(algstr, 10, "%lx", dtype);
850 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
851 ERR_add_error_data(2, "NID=0x", algstr);
856 /* Create the hash object */
857 if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
858 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
862 /* Set the hash value to the value passed */
864 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
865 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
870 /* Finally sign it */
871 slen = RSA_size(rsa);
872 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
873 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
878 /* Inplace byte reversal of signature */
879 for (i = 0; i < slen / 2; i++) {
882 sigret[i] = sigret[slen - i - 1];
883 sigret[slen - i - 1] = c;
891 CryptDestroyHash(hash);
896 int capi_rsa_priv_dec(int flen, const unsigned char *from,
897 unsigned char *to, RSA *rsa, int padding)
900 unsigned char *tmpbuf;
905 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
907 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
909 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
911 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
916 case RSA_PKCS1_PADDING:
919 #ifdef CRYPT_DECRYPT_RSA_NO_PADDING_CHECK
921 flags = CRYPT_DECRYPT_RSA_NO_PADDING_CHECK;
927 BIO_snprintf(errstr, 10, "%d", padding);
928 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
929 ERR_add_error_data(2, "padding=", errstr);
934 /* Create temp reverse order version of input */
935 if (!(tmpbuf = OPENSSL_malloc(flen))) {
936 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
939 for (i = 0; i < flen; i++)
940 tmpbuf[flen - i - 1] = from[i];
942 /* Finally decrypt it */
943 if (!CryptDecrypt(capi_key->key, 0, TRUE, flags, tmpbuf, &flen)) {
944 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
946 OPENSSL_cleanse(tmpbuf, flen);
947 OPENSSL_free(tmpbuf);
950 memcpy(to, tmpbuf, flen);
953 OPENSSL_cleanse(tmpbuf, flen);
954 OPENSSL_free(tmpbuf);
959 static int capi_rsa_free(RSA *rsa)
962 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
963 capi_free_key(capi_key);
964 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
968 /* CryptoAPI DSA operations */
970 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
978 unsigned char csigbuf[40];
980 ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
982 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
984 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
987 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
992 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
996 /* Create the hash object */
997 if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
998 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
1003 /* Set the hash value to the value passed */
1004 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
1005 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
1006 capi_addlasterror();
1010 /* Finally sign it */
1011 slen = sizeof(csigbuf);
1012 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
1013 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1014 capi_addlasterror();
1017 ret = DSA_SIG_new();
1022 if (!ret->r || !ret->s)
1024 if (!lend_tobn(ret->r, csigbuf, 20)
1025 || !lend_tobn(ret->s, csigbuf + 20, 20)) {
1035 OPENSSL_cleanse(csigbuf, 40);
1036 CryptDestroyHash(hash);
1040 static int capi_dsa_free(DSA *dsa)
1043 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1044 capi_free_key(capi_key);
1045 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1049 static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
1054 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1056 out = BIO_new_file(ctx->debug_file, "a+");
1057 BIO_vprintf(out, format, argptr);
1061 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
1064 va_start(args, format);
1065 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1069 static void capi_addlasterror(void)
1071 capi_adderror(GetLastError());
1074 static void capi_adderror(DWORD err)
1077 BIO_snprintf(errstr, 10, "%lX", err);
1078 ERR_add_error_data(2, "Error code= 0x", errstr);
1081 static char *wide_to_asc(LPCWSTR wstr)
1088 len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1089 sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1091 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1094 str = OPENSSL_malloc(sz);
1096 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1099 if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1101 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1107 static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
1112 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1113 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1114 err = GetLastError();
1115 if (err == ERROR_NO_MORE_ITEMS)
1117 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1121 if (sizeof(TCHAR) != sizeof(char))
1124 name = OPENSSL_malloc(len);
1126 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1129 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1130 err = GetLastError();
1131 if (err == ERROR_NO_MORE_ITEMS)
1133 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1137 if (sizeof(TCHAR) != sizeof(char))
1138 *pname = wide_to_asc((WCHAR *)name);
1140 *pname = (char *)name;
1141 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1147 static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
1151 LPSTR provname = NULL;
1152 CAPI_trace(ctx, "capi_list_providers\n");
1153 BIO_printf(out, "Available CSPs:\n");
1154 for (idx = 0;; idx++) {
1155 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1160 BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
1161 OPENSSL_free(provname);
1166 static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
1170 DWORD err, idx, flags, buflen = 0, clen;
1172 LPTSTR cspname = NULL;
1174 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1176 if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
1178 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
1179 cspname = alloca(clen * sizeof(WCHAR));
1180 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1184 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1185 capi_addlasterror();
1189 cspname = (TCHAR *)ctx->cspname;
1190 if (!CryptAcquireContext
1191 (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
1192 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1193 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1194 capi_addlasterror();
1197 if (!CryptGetProvParam
1198 (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
1199 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1200 capi_addlasterror();
1201 CryptReleaseContext(hprov, 0);
1204 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1207 cname = OPENSSL_malloc(buflen);
1209 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1213 for (idx = 0;; idx++) {
1218 flags = CRYPT_FIRST;
1221 if (!CryptGetProvParam
1222 (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
1223 err = GetLastError();
1224 if (err == ERROR_NO_MORE_ITEMS)
1226 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1230 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1231 cname, clen, idx, flags);
1232 if (!cname[0] && (clen == buflen)) {
1233 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1236 BIO_printf(out, "%d. %s\n", idx, cname);
1244 OPENSSL_free(cname);
1245 CryptReleaseContext(hprov, 0);
1250 CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1253 CRYPT_KEY_PROV_INFO *pinfo;
1255 if (!CertGetCertificateContextProperty
1256 (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1258 pinfo = OPENSSL_malloc(len);
1260 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1263 if (!CertGetCertificateContextProperty
1264 (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
1265 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1266 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1267 capi_addlasterror();
1268 OPENSSL_free(pinfo);
1274 static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
1275 CRYPT_KEY_PROV_INFO * pinfo)
1277 char *provname = NULL, *contname = NULL;
1279 BIO_printf(out, " No Private Key\n");
1282 provname = wide_to_asc(pinfo->pwszProvName);
1283 contname = wide_to_asc(pinfo->pwszContainerName);
1284 if (!provname || !contname)
1287 BIO_printf(out, " Private Key Info:\n");
1288 BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname,
1290 BIO_printf(out, " Container Name: %s, Key Type %d\n", contname,
1294 OPENSSL_free(provname);
1296 OPENSSL_free(contname);
1299 char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1304 CAPI_trace(ctx, "capi_cert_get_fname\n");
1305 if (!CertGetCertificateContextProperty
1306 (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1308 wfname = OPENSSL_malloc(dlen);
1309 if (wfname == NULL) {
1310 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, ERR_R_MALLOC_FAILURE);
1313 if (CertGetCertificateContextProperty
1314 (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
1315 char *fname = wide_to_asc(wfname);
1316 OPENSSL_free(wfname);
1319 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1320 capi_addlasterror();
1322 OPENSSL_free(wfname);
1326 void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
1330 unsigned long flags = ctx->dump_flags;
1331 if (flags & CAPI_DMP_FNAME) {
1333 fname = capi_cert_get_fname(ctx, cert);
1335 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1336 OPENSSL_free(fname);
1338 BIO_printf(out, " <No Friendly Name>\n");
1341 p = cert->pbCertEncoded;
1342 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1344 BIO_printf(out, " <Can't parse certificate>\n");
1345 if (flags & CAPI_DMP_SUMMARY) {
1346 BIO_printf(out, " Subject: ");
1347 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1348 BIO_printf(out, "\n Issuer: ");
1349 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1350 BIO_printf(out, "\n");
1352 if (flags & CAPI_DMP_FULL)
1353 X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
1355 if (flags & CAPI_DMP_PKEYINFO) {
1356 CRYPT_KEY_PROV_INFO *pinfo;
1357 pinfo = capi_get_prov_info(ctx, cert);
1358 capi_dump_prov_info(ctx, out, pinfo);
1360 OPENSSL_free(pinfo);
1363 if (flags & CAPI_DMP_PEM)
1364 PEM_write_bio_X509(out, x);
1368 HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
1373 storename = ctx->storename;
1376 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1378 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1379 ctx->store_flags, storename);
1381 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1382 capi_addlasterror();
1387 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
1393 PCCERT_CONTEXT cert = NULL;
1395 storename = ctx->storename;
1398 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1400 hstore = capi_open_store(ctx, storename);
1404 cert = capi_find_cert(ctx, id, hstore);
1409 capi_dump_cert(ctx, out, cert);
1410 CertFreeCertificateContext(cert);
1412 for (idx = 0;; idx++) {
1413 cert = CertEnumCertificatesInStore(hstore, cert);
1416 BIO_printf(out, "Certificate %d\n", idx);
1417 capi_dump_cert(ctx, out, cert);
1421 CertCloseStore(hstore, 0);
1425 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
1428 PCCERT_CONTEXT cert = NULL;
1431 switch (ctx->lookup_method) {
1432 case CAPI_LU_SUBSTR:
1433 return CertFindCertificateInStore(hstore,
1434 X509_ASN_ENCODING, 0,
1435 CERT_FIND_SUBJECT_STR_A, id, NULL);
1438 cert = CertEnumCertificatesInStore(hstore, cert);
1441 fname = capi_cert_get_fname(ctx, cert);
1443 if (strcmp(fname, id))
1447 OPENSSL_free(fname);
1457 static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
1458 TCHAR *provname, DWORD ptype, DWORD keyspec)
1462 key = OPENSSL_malloc(sizeof(CAPI_KEY));
1464 CAPIerr(CAPI_F_CAPI_GET_KEY, ERR_R_MALLOC_FAILURE);
1465 capi_addlasterror();
1468 if (sizeof(TCHAR) == sizeof(char))
1469 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1470 contname, provname, ptype);
1471 else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
1472 /* above 'if' is optimization to minimize malloc-ations */
1473 char *_contname = wide_to_asc((WCHAR *)contname);
1474 char *_provname = wide_to_asc((WCHAR *)provname);
1476 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1477 _contname, _provname, ptype);
1479 OPENSSL_free(_provname);
1481 OPENSSL_free(_contname);
1483 if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1484 dwFlags = CRYPT_MACHINE_KEYSET;
1485 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
1486 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1487 capi_addlasterror();
1490 if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1491 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1492 capi_addlasterror();
1493 CryptReleaseContext(key->hprov, 0);
1496 key->keyspec = keyspec;
1505 static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1507 CAPI_KEY *key = NULL;
1508 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1509 char *provname = NULL, *contname = NULL;
1510 pinfo = capi_get_prov_info(ctx, cert);
1513 if (sizeof(TCHAR) != sizeof(char))
1514 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1515 (TCHAR *)pinfo->pwszProvName,
1516 pinfo->dwProvType, pinfo->dwKeySpec);
1518 provname = wide_to_asc(pinfo->pwszProvName);
1519 contname = wide_to_asc(pinfo->pwszContainerName);
1520 if (!provname || !contname)
1522 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1523 pinfo->dwProvType, pinfo->dwKeySpec);
1528 OPENSSL_free(pinfo);
1530 OPENSSL_free(provname);
1532 OPENSSL_free(contname);
1536 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
1538 PCCERT_CONTEXT cert;
1540 CAPI_KEY *key = NULL;
1541 switch (ctx->lookup_method) {
1542 case CAPI_LU_SUBSTR:
1544 hstore = capi_open_store(ctx, NULL);
1547 cert = capi_find_cert(ctx, id, hstore);
1549 key = capi_get_cert_key(ctx, cert);
1550 CertFreeCertificateContext(cert);
1552 CertCloseStore(hstore, 0);
1555 case CAPI_LU_CONTNAME:
1556 if (sizeof(TCHAR) != sizeof(char)) {
1557 WCHAR *contname, *provname;
1560 if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1561 (contname = alloca(len * sizeof(WCHAR)),
1562 MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1564 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
1566 alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
1573 capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1574 ctx->csptype, ctx->keytype);
1576 key = capi_get_key(ctx, (TCHAR *)id,
1577 (TCHAR *)ctx->cspname,
1578 ctx->csptype, ctx->keytype);
1585 void capi_free_key(CAPI_KEY * key)
1589 CryptDestroyKey(key->key);
1590 CryptReleaseContext(key->hprov, 0);
1592 CertFreeCertificateContext(key->pcert);
1596 /* Initialize a CAPI_CTX structure */
1598 static CAPI_CTX *capi_ctx_new()
1601 ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
1603 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1606 ctx->cspname = NULL;
1607 ctx->csptype = PROV_RSA_FULL;
1608 ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1609 ctx->keytype = AT_KEYEXCHANGE;
1610 ctx->storename = NULL;
1611 ctx->ssl_client_store = NULL;
1612 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1613 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1614 ctx->lookup_method = CAPI_LU_SUBSTR;
1615 ctx->debug_level = 0;
1616 ctx->debug_file = NULL;
1617 ctx->client_cert_select = cert_select_simple;
1621 static void capi_ctx_free(CAPI_CTX * ctx)
1623 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1627 OPENSSL_free(ctx->cspname);
1628 if (ctx->debug_file)
1629 OPENSSL_free(ctx->debug_file);
1631 OPENSSL_free(ctx->storename);
1632 if (ctx->ssl_client_store)
1633 OPENSSL_free(ctx->ssl_client_store);
1637 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
1640 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1645 if (sizeof(TCHAR) != sizeof(char)) {
1647 if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1648 name = alloca(len * sizeof(WCHAR));
1649 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1652 name = (TCHAR *)pname;
1654 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1655 CRYPT_VERIFYCONTEXT)) {
1656 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1657 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1658 capi_addlasterror();
1661 CryptReleaseContext(hprov, 0);
1664 OPENSSL_free(ctx->cspname);
1665 ctx->cspname = BUF_strdup(pname);
1666 ctx->csptype = type;
1670 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
1675 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1677 res = capi_ctx_set_provname(ctx, pname, type, 0);
1678 OPENSSL_free(pname);
1682 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1686 /* Special case: empty list: match anything */
1687 if (sk_X509_NAME_num(ca_dn) <= 0)
1689 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1690 nm = sk_X509_NAME_value(ca_dn, i);
1691 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1697 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1698 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1699 EVP_PKEY **pkey, STACK_OF(X509) **pother,
1700 UI_METHOD *ui_method,
1701 void *callback_data)
1703 STACK_OF(X509) *certs = NULL;
1707 int i, client_cert_idx;
1709 PCCERT_CONTEXT cert = NULL, excert = NULL;
1712 ctx = ENGINE_get_ex_data(e, capi_idx);
1717 storename = ctx->ssl_client_store;
1721 hstore = capi_open_store(ctx, storename);
1724 /* Enumerate all certificates collect any matches */
1726 cert = CertEnumCertificatesInStore(hstore, cert);
1729 p = cert->pbCertEncoded;
1730 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1732 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1735 if (cert_issuer_match(ca_dn, x)
1736 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1737 key = capi_get_cert_key(ctx, cert);
1743 * Match found: attach extra data to it so we can retrieve the
1746 excert = CertDuplicateCertificateContext(cert);
1747 key->pcert = excert;
1748 X509_set_ex_data(x, cert_capi_idx, key);
1751 certs = sk_X509_new_null();
1753 sk_X509_push(certs, x);
1760 CertFreeCertificateContext(cert);
1762 CertCloseStore(hstore, 0);
1767 /* Select the appropriate certificate */
1769 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1771 /* Set the selected certificate and free the rest */
1773 for (i = 0; i < sk_X509_num(certs); i++) {
1774 x = sk_X509_value(certs, i);
1775 if (i == client_cert_idx)
1778 key = X509_get_ex_data(x, cert_capi_idx);
1784 sk_X509_free(certs);
1789 /* Setup key for selected certificate */
1791 key = X509_get_ex_data(*pcert, cert_capi_idx);
1792 *pkey = capi_get_pkey(e, key);
1793 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1799 /* Simple client cert selection function: always select first */
1801 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1806 # ifdef OPENSSL_CAPIENG_DIALOG
1809 * More complex cert selection function, using standard function
1810 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1814 * Definitions which are in cryptuiapi.h but this is not present in older
1815 * versions of headers.
1818 # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1819 # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1820 # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1823 # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1824 # define dlg_prompt L"Select a certificate to use for authentication"
1825 # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1826 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1828 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1832 PCCERT_CONTEXT cert;
1837 if (sk_X509_num(certs) == 1)
1839 ctx = ENGINE_get_ex_data(e, capi_idx);
1840 /* Create an in memory store of certificates */
1841 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1842 CERT_STORE_CREATE_NEW_FLAG, NULL);
1844 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1845 capi_addlasterror();
1848 /* Add all certificates to store */
1849 for (i = 0; i < sk_X509_num(certs); i++) {
1850 x = sk_X509_value(certs, i);
1851 key = X509_get_ex_data(x, cert_capi_idx);
1853 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1854 CERT_STORE_ADD_NEW, NULL)) {
1855 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1856 capi_addlasterror();
1861 hwnd = GetForegroundWindow();
1863 hwnd = GetActiveWindow();
1864 if (!hwnd && ctx->getconswindow)
1865 hwnd = ctx->getconswindow();
1866 /* Call dialog to select one */
1867 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1868 dlg_columns, 0, NULL);
1870 /* Find matching cert from list */
1872 for (i = 0; i < sk_X509_num(certs); i++) {
1873 x = sk_X509_value(certs, i);
1874 key = X509_get_ex_data(x, cert_capi_idx);
1875 if (CertCompareCertificate
1876 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1877 key->pcert->pCertInfo)) {
1886 CertCloseStore(dstore, 0);
1892 #else /* !__COMPILE_CAPIENG */
1893 # include <openssl/engine.h>
1894 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1896 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1898 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1903 IMPLEMENT_DYNAMIC_CHECK_FN()
1905 void ENGINE_load_capi(void)