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 # include <openssl/engine.h>
118 # include <openssl/pem.h>
119 # include <openssl/x509v3.h>
121 # include "e_capi_err.h"
122 # include "e_capi_err.c"
124 static const char *engine_capi_id = "capi";
125 static const char *engine_capi_name = "CryptoAPI ENGINE";
127 typedef struct CAPI_CTX_st CAPI_CTX;
128 typedef struct CAPI_KEY_st CAPI_KEY;
130 static void capi_addlasterror(void);
131 static void capi_adderror(DWORD err);
133 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...);
135 static int capi_list_providers(CAPI_CTX * ctx, BIO *out);
136 static int capi_list_containers(CAPI_CTX * ctx, BIO *out);
137 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *storename);
138 void capi_free_key(CAPI_KEY * key);
140 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
143 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id);
145 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
146 UI_METHOD *ui_method, void *callback_data);
147 static int capi_rsa_sign(int dtype, const unsigned char *m,
148 unsigned int m_len, unsigned char *sigret,
149 unsigned int *siglen, const RSA *rsa);
150 static int capi_rsa_priv_enc(int flen, const unsigned char *from,
151 unsigned char *to, RSA *rsa, int padding);
152 static int capi_rsa_priv_dec(int flen, const unsigned char *from,
153 unsigned char *to, RSA *rsa, int padding);
154 static int capi_rsa_free(RSA *rsa);
156 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
158 static int capi_dsa_free(DSA *dsa);
160 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
161 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
162 EVP_PKEY **pkey, STACK_OF(X509) **pother,
163 UI_METHOD *ui_method,
164 void *callback_data);
166 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
167 # ifdef OPENSSL_CAPIENG_DIALOG
168 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
171 typedef PCCERT_CONTEXT(WINAPI *CERTDLG) (HCERTSTORE, HWND, LPCWSTR,
172 LPCWSTR, DWORD, DWORD, void *);
173 typedef HWND(WINAPI *GETCONSWIN) (void);
176 * This structure contains CAPI ENGINE specific data: it contains various
177 * global options and affects how other functions behave.
180 # define CAPI_DBG_TRACE 2
181 # define CAPI_DBG_ERROR 1
186 /* Parameters to use for container lookup */
190 /* Certificate store name to use */
192 LPSTR ssl_client_store;
193 /* System store flags */
195 /* Lookup string meanings in load_private_key */
196 /* Substring of subject: uses "storename" */
197 # define CAPI_LU_SUBSTR 1
198 /* Friendly name: uses storename */
199 # define CAPI_LU_FNAME 2
200 /* Container name: uses cspname, keytype */
201 # define CAPI_LU_CONTNAME 3
203 /* Info to dump with dumpcerts option */
204 /* Issuer and serial name strings */
205 # define CAPI_DMP_SUMMARY 0x1
207 # define CAPI_DMP_FNAME 0x2
208 /* Full X509_print dump */
209 # define CAPI_DMP_FULL 0x4
210 /* Dump PEM format certificate */
211 # define CAPI_DMP_PEM 0x8
212 /* Dump pseudo key (if possible) */
213 # define CAPI_DMP_PSKEY 0x10
214 /* Dump key info (if possible) */
215 # define CAPI_DMP_PKEYINFO 0x20
217 int (*client_cert_select) (ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
218 CERTDLG certselectdlg;
219 GETCONSWIN getconswindow;
222 static CAPI_CTX *capi_ctx_new();
223 static void capi_ctx_free(CAPI_CTX * ctx);
224 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
226 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx);
228 # define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
229 # define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
230 # define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
231 # define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
232 # define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
233 # define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
234 # define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
235 # define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
236 # define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
237 # define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
238 # define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
239 # define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
240 # define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
241 # define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
243 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
244 {CAPI_CMD_LIST_CERTS,
246 "List all certificates in store",
247 ENGINE_CMD_FLAG_NO_INPUT},
248 {CAPI_CMD_LOOKUP_CERT,
250 "Lookup and output certificates",
251 ENGINE_CMD_FLAG_STRING},
252 {CAPI_CMD_DEBUG_LEVEL,
254 "debug level (1=errors, 2=trace)",
255 ENGINE_CMD_FLAG_NUMERIC},
256 {CAPI_CMD_DEBUG_FILE,
258 "debugging filename)",
259 ENGINE_CMD_FLAG_STRING},
262 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
263 ENGINE_CMD_FLAG_NUMERIC},
267 ENGINE_CMD_FLAG_NO_INPUT},
268 {CAPI_CMD_SET_CSP_IDX,
271 ENGINE_CMD_FLAG_NUMERIC},
272 {CAPI_CMD_SET_CSP_NAME,
274 "Set CSP name, (default CSP used if not specified)",
275 ENGINE_CMD_FLAG_STRING},
276 {CAPI_CMD_SET_CSP_TYPE,
278 "Set CSP type, (default RSA_PROV_FULL)",
279 ENGINE_CMD_FLAG_NUMERIC},
280 {CAPI_CMD_LIST_CONTAINERS,
282 "list container names",
283 ENGINE_CMD_FLAG_NO_INPUT},
284 {CAPI_CMD_LIST_OPTIONS,
286 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
287 "32=private key info)",
288 ENGINE_CMD_FLAG_NUMERIC},
289 {CAPI_CMD_LOOKUP_METHOD,
291 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
292 ENGINE_CMD_FLAG_NUMERIC},
293 {CAPI_CMD_STORE_NAME,
295 "certificate store name, default \"MY\"",
296 ENGINE_CMD_FLAG_STRING},
297 {CAPI_CMD_STORE_FLAGS,
299 "Certificate store flags: 1 = system store",
300 ENGINE_CMD_FLAG_NUMERIC},
305 static int capi_idx = -1;
306 static int rsa_capi_idx = -1;
307 static int dsa_capi_idx = -1;
308 static int cert_capi_idx = -1;
310 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
315 if (capi_idx == -1) {
316 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
319 ctx = ENGINE_get_ex_data(e, capi_idx);
320 out = BIO_new_fp(stdout, BIO_NOCLOSE);
322 case CAPI_CMD_LIST_CSPS:
323 ret = capi_list_providers(ctx, out);
326 case CAPI_CMD_LIST_CERTS:
327 ret = capi_list_certs(ctx, out, NULL);
330 case CAPI_CMD_LOOKUP_CERT:
331 ret = capi_list_certs(ctx, out, p);
334 case CAPI_CMD_LIST_CONTAINERS:
335 ret = capi_list_containers(ctx, out);
338 case CAPI_CMD_STORE_NAME:
340 OPENSSL_free(ctx->storename);
341 ctx->storename = BUF_strdup(p);
342 CAPI_trace(ctx, "Setting store name to %s\n", p);
345 case CAPI_CMD_STORE_FLAGS:
347 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
348 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
350 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
351 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
353 CAPI_trace(ctx, "Setting flags to %d\n", i);
356 case CAPI_CMD_DEBUG_LEVEL:
357 ctx->debug_level = (int)i;
358 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
361 case CAPI_CMD_DEBUG_FILE:
362 ctx->debug_file = BUF_strdup(p);
363 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
366 case CAPI_CMD_KEYTYPE:
368 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
371 case CAPI_CMD_SET_CSP_IDX:
372 ret = capi_ctx_set_provname_idx(ctx, i);
375 case CAPI_CMD_LIST_OPTIONS:
379 case CAPI_CMD_LOOKUP_METHOD:
380 if (i < 1 || i > 3) {
381 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
384 ctx->lookup_method = i;
387 case CAPI_CMD_SET_CSP_NAME:
388 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
391 case CAPI_CMD_SET_CSP_TYPE:
396 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
405 static RSA_METHOD capi_rsa_method = {
406 "CryptoAPI RSA method",
409 capi_rsa_priv_enc, /* priv_enc */
410 capi_rsa_priv_dec, /* priv_dec */
414 capi_rsa_free, /* finish */
415 RSA_FLAG_SIGN_VER, /* flags */
417 capi_rsa_sign, /* rsa_sign */
421 static DSA_METHOD capi_dsa_method = {
422 "CryptoAPI DSA method",
423 capi_dsa_do_sign, /* dsa_do_sign */
424 0, /* dsa_sign_setup */
425 0, /* dsa_do_verify */
429 capi_dsa_free, /* finish */
432 0, /* dsa_paramgen */
436 static int capi_init(ENGINE *e)
439 const RSA_METHOD *ossl_rsa_meth;
440 const DSA_METHOD *ossl_dsa_meth;
443 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
447 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
449 /* Setup RSA_METHOD */
450 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
451 ossl_rsa_meth = RSA_PKCS1_SSLeay();
452 capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc;
453 capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec;
454 capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp;
455 capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp;
457 /* Setup DSA Method */
458 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
459 ossl_dsa_meth = DSA_OpenSSL();
460 capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify;
461 capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp;
462 capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp;
465 ctx = capi_ctx_new();
469 ENGINE_set_ex_data(e, capi_idx, ctx);
471 # ifdef OPENSSL_CAPIENG_DIALOG
473 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
474 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
477 (CERTDLG) GetProcAddress(cryptui,
478 "CryptUIDlgSelectCertificateFromStore");
481 (GETCONSWIN) GetProcAddress(kernel, "GetConsoleWindow");
482 if (cryptui && !OPENSSL_isservice())
483 ctx->client_cert_select = cert_select_dialog;
490 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
496 static int capi_destroy(ENGINE *e)
498 ERR_unload_CAPI_strings();
502 static int capi_finish(ENGINE *e)
505 ctx = ENGINE_get_ex_data(e, capi_idx);
507 ENGINE_set_ex_data(e, capi_idx, NULL);
512 * CryptoAPI key application data. This contains a handle to the private key
513 * container (for sign operations) and a handle to the key (for decrypt
518 /* Associated certificate context (if any) */
519 PCCERT_CONTEXT pcert;
525 static int bind_capi(ENGINE *e)
527 if (!ENGINE_set_id(e, engine_capi_id)
528 || !ENGINE_set_name(e, engine_capi_name)
529 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
530 || !ENGINE_set_init_function(e, capi_init)
531 || !ENGINE_set_finish_function(e, capi_finish)
532 || !ENGINE_set_destroy_function(e, capi_destroy)
533 || !ENGINE_set_RSA(e, &capi_rsa_method)
534 || !ENGINE_set_DSA(e, &capi_dsa_method)
535 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
536 || !ENGINE_set_load_ssl_client_cert_function(e,
537 capi_load_ssl_client_cert)
538 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
539 || !ENGINE_set_ctrl_function(e, capi_ctrl))
541 ERR_load_CAPI_strings();
547 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
548 static int bind_helper(ENGINE *e, const char *id)
550 if (id && (strcmp(id, engine_capi_id) != 0))
557 IMPLEMENT_DYNAMIC_CHECK_FN()
558 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
560 static ENGINE *engine_capi(void)
562 ENGINE *ret = ENGINE_new();
565 if (!bind_capi(ret)) {
572 void ENGINE_load_capi(void)
574 /* Copied from eng_[openssl|dyn].c */
575 ENGINE *toadd = engine_capi();
584 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
588 * Reverse buffer in place: since this is a keyblob structure that will
589 * be freed up after conversion anyway it doesn't matter if we change
592 for (i = 0; i < binlen / 2; i++) {
595 bin[i] = bin[binlen - i - 1];
596 bin[binlen - i - 1] = c;
599 if (!BN_bin2bn(bin, binlen, bn))
604 /* Given a CAPI_KEY get an EVP_PKEY structure */
606 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
608 unsigned char *pubkey = NULL;
613 EVP_PKEY *ret = NULL;
614 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
615 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
620 pubkey = OPENSSL_malloc(len);
625 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
626 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
631 bh = (BLOBHEADER *) pubkey;
632 if (bh->bType != PUBLICKEYBLOB) {
633 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
636 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
639 unsigned char *rsa_modulus;
640 rp = (RSAPUBKEY *) (bh + 1);
641 if (rp->magic != 0x31415352) {
643 BIO_snprintf(magstr, 10, "%lx", rp->magic);
644 CAPIerr(CAPI_F_CAPI_GET_PKEY,
645 CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
646 ERR_add_error_data(2, "magic=0x", magstr);
649 rsa_modulus = (unsigned char *)(rp + 1);
650 rkey = RSA_new_method(eng);
657 if (!rkey->e || !rkey->n)
660 if (!BN_set_word(rkey->e, rp->pubexp))
663 rsa_modlen = rp->bitlen / 8;
664 if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
667 RSA_set_ex_data(rkey, rsa_capi_idx, key);
669 if (!(ret = EVP_PKEY_new()))
672 EVP_PKEY_assign_RSA(ret, rkey);
675 } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
679 dp = (DSSPUBKEY *) (bh + 1);
680 if (dp->magic != 0x31535344) {
682 BIO_snprintf(magstr, 10, "%lx", dp->magic);
683 CAPIerr(CAPI_F_CAPI_GET_PKEY,
684 CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
685 ERR_add_error_data(2, "magic=0x", magstr);
688 dsa_plen = dp->bitlen / 8;
689 btmp = (unsigned char *)(dp + 1);
690 dkey = DSA_new_method(eng);
696 dkey->pub_key = BN_new();
697 if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key)
699 if (!lend_tobn(dkey->p, btmp, dsa_plen))
702 if (!lend_tobn(dkey->q, btmp, 20))
705 if (!lend_tobn(dkey->g, btmp, dsa_plen))
708 if (!lend_tobn(dkey->pub_key, btmp, dsa_plen))
712 DSA_set_ex_data(dkey, dsa_capi_idx, key);
714 if (!(ret = EVP_PKEY_new()))
717 EVP_PKEY_assign_DSA(ret, dkey);
721 BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg);
722 CAPIerr(CAPI_F_CAPI_GET_PKEY,
723 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
724 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
730 OPENSSL_free(pubkey);
741 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
746 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
747 UI_METHOD *ui_method, void *callback_data)
752 ctx = ENGINE_get_ex_data(eng, capi_idx);
755 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
759 key = capi_find_key(ctx, key_id);
764 ret = capi_get_pkey(eng, key);
772 /* CryptoAPI RSA operations */
774 int capi_rsa_priv_enc(int flen, const unsigned char *from,
775 unsigned char *to, RSA *rsa, int padding)
777 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
781 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
782 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
792 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
794 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
796 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
798 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
801 /* Convert the signature type to a CryptoAPI algorithm ID */
812 alg = CALG_SSL3_SHAMD5;
817 BIO_snprintf(algstr, 10, "%lx", dtype);
818 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
819 ERR_add_error_data(2, "NID=0x", algstr);
824 /* Create the hash object */
825 if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
826 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
830 /* Set the hash value to the value passed */
832 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
833 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
838 /* Finally sign it */
839 slen = RSA_size(rsa);
840 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
841 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
846 /* Inplace byte reversal of signature */
847 for (i = 0; i < slen / 2; i++) {
850 sigret[i] = sigret[slen - i - 1];
851 sigret[slen - i - 1] = c;
859 CryptDestroyHash(hash);
864 int capi_rsa_priv_dec(int flen, const unsigned char *from,
865 unsigned char *to, RSA *rsa, int padding)
868 unsigned char *tmpbuf;
871 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
873 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
875 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
877 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
881 if (padding != RSA_PKCS1_PADDING) {
883 BIO_snprintf(errstr, 10, "%d", padding);
884 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
885 ERR_add_error_data(2, "padding=", errstr);
889 /* Create temp reverse order version of input */
890 if (!(tmpbuf = OPENSSL_malloc(flen))) {
891 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
894 for (i = 0; i < flen; i++)
895 tmpbuf[flen - i - 1] = from[i];
897 /* Finally decrypt it */
898 if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen)) {
899 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
901 OPENSSL_free(tmpbuf);
904 memcpy(to, tmpbuf, flen);
906 OPENSSL_free(tmpbuf);
911 static int capi_rsa_free(RSA *rsa)
914 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
915 capi_free_key(capi_key);
916 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
920 /* CryptoAPI DSA operations */
922 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
930 unsigned char csigbuf[40];
932 ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
934 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
936 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
939 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
944 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
948 /* Create the hash object */
949 if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
950 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
955 /* Set the hash value to the value passed */
956 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
957 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
962 /* Finally sign it */
963 slen = sizeof(csigbuf);
964 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
965 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
974 if (!ret->r || !ret->s)
976 if (!lend_tobn(ret->r, csigbuf, 20)
977 || !lend_tobn(ret->s, csigbuf + 20, 20)) {
987 OPENSSL_cleanse(csigbuf, 40);
988 CryptDestroyHash(hash);
992 static int capi_dsa_free(DSA *dsa)
995 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
996 capi_free_key(capi_key);
997 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1001 static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
1006 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1008 out = BIO_new_file(ctx->debug_file, "a+");
1009 BIO_vprintf(out, format, argptr);
1013 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
1016 va_start(args, format);
1017 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1021 static void capi_addlasterror(void)
1023 capi_adderror(GetLastError());
1026 static void capi_adderror(DWORD err)
1029 BIO_snprintf(errstr, 10, "%lX", err);
1030 ERR_add_error_data(2, "Error code= 0x", errstr);
1033 static char *wide_to_asc(LPCWSTR wstr)
1040 len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1041 sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1043 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1046 str = OPENSSL_malloc(sz);
1048 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1051 if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1053 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1059 static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
1064 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1065 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1066 err = GetLastError();
1067 if (err == ERROR_NO_MORE_ITEMS)
1069 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1073 if (sizeof(TCHAR) != sizeof(char))
1076 name = OPENSSL_malloc(len);
1077 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1078 err = GetLastError();
1079 if (err == ERROR_NO_MORE_ITEMS)
1081 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1085 if (sizeof(TCHAR) != sizeof(char))
1086 *pname = wide_to_asc((WCHAR *)name);
1088 *pname = (char *)name;
1089 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1095 static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
1099 LPSTR provname = NULL;
1100 CAPI_trace(ctx, "capi_list_providers\n");
1101 BIO_printf(out, "Available CSPs:\n");
1102 for (idx = 0;; idx++) {
1103 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1108 BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
1109 OPENSSL_free(provname);
1114 static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
1118 DWORD err, idx, flags, buflen = 0, clen;
1120 LPTSTR cspname = NULL;
1122 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1124 if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
1126 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
1127 cspname = alloca(clen * sizeof(WCHAR));
1128 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1132 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1133 capi_addlasterror();
1137 cspname = (TCHAR *)ctx->cspname;
1138 if (!CryptAcquireContext
1139 (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
1140 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1141 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1142 capi_addlasterror();
1145 if (!CryptGetProvParam
1146 (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
1147 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1148 capi_addlasterror();
1149 CryptReleaseContext(hprov, 0);
1152 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1155 cname = OPENSSL_malloc(buflen);
1157 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1161 for (idx = 0;; idx++) {
1166 flags = CRYPT_FIRST;
1169 if (!CryptGetProvParam
1170 (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
1171 err = GetLastError();
1172 if (err == ERROR_NO_MORE_ITEMS)
1174 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1178 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1179 cname, clen, idx, flags);
1180 if (!cname[0] && (clen == buflen)) {
1181 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1184 BIO_printf(out, "%d. %s\n", idx, cname);
1192 OPENSSL_free(cname);
1193 CryptReleaseContext(hprov, 0);
1198 CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1201 CRYPT_KEY_PROV_INFO *pinfo;
1203 if (!CertGetCertificateContextProperty
1204 (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1206 pinfo = OPENSSL_malloc(len);
1208 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1211 if (!CertGetCertificateContextProperty
1212 (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
1213 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1214 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1215 capi_addlasterror();
1216 OPENSSL_free(pinfo);
1222 static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
1223 CRYPT_KEY_PROV_INFO * pinfo)
1225 char *provname = NULL, *contname = NULL;
1227 BIO_printf(out, " No Private Key\n");
1230 provname = wide_to_asc(pinfo->pwszProvName);
1231 contname = wide_to_asc(pinfo->pwszContainerName);
1232 if (!provname || !contname)
1235 BIO_printf(out, " Private Key Info:\n");
1236 BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname,
1238 BIO_printf(out, " Container Name: %s, Key Type %d\n", contname,
1242 OPENSSL_free(provname);
1244 OPENSSL_free(contname);
1247 char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1252 CAPI_trace(ctx, "capi_cert_get_fname\n");
1253 if (!CertGetCertificateContextProperty
1254 (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1256 wfname = OPENSSL_malloc(dlen);
1257 if (CertGetCertificateContextProperty
1258 (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
1259 char *fname = wide_to_asc(wfname);
1260 OPENSSL_free(wfname);
1263 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1264 capi_addlasterror();
1266 OPENSSL_free(wfname);
1270 void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
1274 unsigned long flags = ctx->dump_flags;
1275 if (flags & CAPI_DMP_FNAME) {
1277 fname = capi_cert_get_fname(ctx, cert);
1279 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1280 OPENSSL_free(fname);
1282 BIO_printf(out, " <No Friendly Name>\n");
1285 p = cert->pbCertEncoded;
1286 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1288 BIO_printf(out, " <Can't parse certificate>\n");
1289 if (flags & CAPI_DMP_SUMMARY) {
1290 BIO_printf(out, " Subject: ");
1291 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1292 BIO_printf(out, "\n Issuer: ");
1293 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1294 BIO_printf(out, "\n");
1296 if (flags & CAPI_DMP_FULL)
1297 X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
1299 if (flags & CAPI_DMP_PKEYINFO) {
1300 CRYPT_KEY_PROV_INFO *pinfo;
1301 pinfo = capi_get_prov_info(ctx, cert);
1302 capi_dump_prov_info(ctx, out, pinfo);
1304 OPENSSL_free(pinfo);
1307 if (flags & CAPI_DMP_PEM)
1308 PEM_write_bio_X509(out, x);
1312 HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
1317 storename = ctx->storename;
1320 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1322 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1323 ctx->store_flags, storename);
1325 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1326 capi_addlasterror();
1331 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
1337 PCCERT_CONTEXT cert = NULL;
1339 storename = ctx->storename;
1342 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1344 hstore = capi_open_store(ctx, storename);
1348 cert = capi_find_cert(ctx, id, hstore);
1353 capi_dump_cert(ctx, out, cert);
1354 CertFreeCertificateContext(cert);
1356 for (idx = 0;; idx++) {
1357 cert = CertEnumCertificatesInStore(hstore, cert);
1360 BIO_printf(out, "Certificate %d\n", idx);
1361 capi_dump_cert(ctx, out, cert);
1365 CertCloseStore(hstore, 0);
1369 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
1372 PCCERT_CONTEXT cert = NULL;
1375 switch (ctx->lookup_method) {
1376 case CAPI_LU_SUBSTR:
1377 return CertFindCertificateInStore(hstore,
1378 X509_ASN_ENCODING, 0,
1379 CERT_FIND_SUBJECT_STR_A, id, NULL);
1382 cert = CertEnumCertificatesInStore(hstore, cert);
1385 fname = capi_cert_get_fname(ctx, cert);
1387 if (strcmp(fname, id))
1391 OPENSSL_free(fname);
1401 static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
1402 TCHAR *provname, DWORD ptype, DWORD keyspec)
1406 key = OPENSSL_malloc(sizeof(CAPI_KEY));
1407 if (sizeof(TCHAR) == sizeof(char))
1408 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1409 contname, provname, ptype);
1410 else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
1411 /* above 'if' is optimization to minimize malloc-ations */
1412 char *_contname = wide_to_asc((WCHAR *)contname);
1413 char *_provname = wide_to_asc((WCHAR *)provname);
1415 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1416 _contname, _provname, ptype);
1418 OPENSSL_free(_provname);
1420 OPENSSL_free(_contname);
1422 if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1423 dwFlags = CRYPT_MACHINE_KEYSET;
1424 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
1425 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1426 capi_addlasterror();
1429 if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1430 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1431 capi_addlasterror();
1432 CryptReleaseContext(key->hprov, 0);
1435 key->keyspec = keyspec;
1444 static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1446 CAPI_KEY *key = NULL;
1447 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1448 char *provname = NULL, *contname = NULL;
1449 pinfo = capi_get_prov_info(ctx, cert);
1452 if (sizeof(TCHAR) != sizeof(char))
1453 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1454 (TCHAR *)pinfo->pwszProvName,
1455 pinfo->dwProvType, pinfo->dwKeySpec);
1457 provname = wide_to_asc(pinfo->pwszProvName);
1458 contname = wide_to_asc(pinfo->pwszContainerName);
1459 if (!provname || !contname)
1461 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1462 pinfo->dwProvType, pinfo->dwKeySpec);
1467 OPENSSL_free(pinfo);
1469 OPENSSL_free(provname);
1471 OPENSSL_free(contname);
1475 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
1477 PCCERT_CONTEXT cert;
1479 CAPI_KEY *key = NULL;
1480 switch (ctx->lookup_method) {
1481 case CAPI_LU_SUBSTR:
1483 hstore = capi_open_store(ctx, NULL);
1486 cert = capi_find_cert(ctx, id, hstore);
1488 key = capi_get_cert_key(ctx, cert);
1489 CertFreeCertificateContext(cert);
1491 CertCloseStore(hstore, 0);
1494 case CAPI_LU_CONTNAME:
1495 if (sizeof(TCHAR) != sizeof(char)) {
1496 WCHAR *contname, *provname;
1499 if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1500 (contname = alloca(len * sizeof(WCHAR)),
1501 MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1503 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
1505 alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
1512 capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1513 ctx->csptype, ctx->keytype);
1515 key = capi_get_key(ctx, (TCHAR *)id,
1516 (TCHAR *)ctx->cspname,
1517 ctx->csptype, ctx->keytype);
1524 void capi_free_key(CAPI_KEY * key)
1528 CryptDestroyKey(key->key);
1529 CryptReleaseContext(key->hprov, 0);
1531 CertFreeCertificateContext(key->pcert);
1535 /* Initialize a CAPI_CTX structure */
1537 static CAPI_CTX *capi_ctx_new()
1540 ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
1542 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1545 ctx->cspname = NULL;
1546 ctx->csptype = PROV_RSA_FULL;
1547 ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1548 ctx->keytype = AT_KEYEXCHANGE;
1549 ctx->storename = NULL;
1550 ctx->ssl_client_store = NULL;
1551 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1552 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1553 ctx->lookup_method = CAPI_LU_SUBSTR;
1554 ctx->debug_level = 0;
1555 ctx->debug_file = NULL;
1556 ctx->client_cert_select = cert_select_simple;
1560 static void capi_ctx_free(CAPI_CTX * ctx)
1562 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1566 OPENSSL_free(ctx->cspname);
1567 if (ctx->debug_file)
1568 OPENSSL_free(ctx->debug_file);
1570 OPENSSL_free(ctx->storename);
1571 if (ctx->ssl_client_store)
1572 OPENSSL_free(ctx->ssl_client_store);
1576 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
1579 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1584 if (sizeof(TCHAR) != sizeof(char)) {
1586 if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1587 name = alloca(len * sizeof(WCHAR));
1588 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1591 name = (TCHAR *)pname;
1593 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1594 CRYPT_VERIFYCONTEXT)) {
1595 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1596 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1597 capi_addlasterror();
1600 CryptReleaseContext(hprov, 0);
1603 OPENSSL_free(ctx->cspname);
1604 ctx->cspname = BUF_strdup(pname);
1605 ctx->csptype = type;
1609 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
1614 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1616 res = capi_ctx_set_provname(ctx, pname, type, 0);
1617 OPENSSL_free(pname);
1621 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1625 /* Special case: empty list: match anything */
1626 if (sk_X509_NAME_num(ca_dn) <= 0)
1628 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1629 nm = sk_X509_NAME_value(ca_dn, i);
1630 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1636 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1637 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1638 EVP_PKEY **pkey, STACK_OF(X509) **pother,
1639 UI_METHOD *ui_method,
1640 void *callback_data)
1642 STACK_OF(X509) *certs = NULL;
1646 int i, client_cert_idx;
1648 PCCERT_CONTEXT cert = NULL, excert = NULL;
1651 ctx = ENGINE_get_ex_data(e, capi_idx);
1656 storename = ctx->ssl_client_store;
1660 hstore = capi_open_store(ctx, storename);
1663 /* Enumerate all certificates collect any matches */
1665 cert = CertEnumCertificatesInStore(hstore, cert);
1668 p = cert->pbCertEncoded;
1669 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1671 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1674 if (cert_issuer_match(ca_dn, x)
1675 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1676 key = capi_get_cert_key(ctx, cert);
1682 * Match found: attach extra data to it so we can retrieve the
1685 excert = CertDuplicateCertificateContext(cert);
1686 key->pcert = excert;
1687 X509_set_ex_data(x, cert_capi_idx, key);
1690 certs = sk_X509_new_null();
1692 sk_X509_push(certs, x);
1699 CertFreeCertificateContext(cert);
1701 CertCloseStore(hstore, 0);
1706 /* Select the appropriate certificate */
1708 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1710 /* Set the selected certificate and free the rest */
1712 for (i = 0; i < sk_X509_num(certs); i++) {
1713 x = sk_X509_value(certs, i);
1714 if (i == client_cert_idx)
1717 key = X509_get_ex_data(x, cert_capi_idx);
1723 sk_X509_free(certs);
1728 /* Setup key for selected certificate */
1730 key = X509_get_ex_data(*pcert, cert_capi_idx);
1731 *pkey = capi_get_pkey(e, key);
1732 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1738 /* Simple client cert selection function: always select first */
1740 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1745 # ifdef OPENSSL_CAPIENG_DIALOG
1748 * More complex cert selection function, using standard function
1749 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1753 * Definitions which are in cryptuiapi.h but this is not present in older
1754 * versions of headers.
1757 # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1758 # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1759 # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1762 # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1763 # define dlg_prompt L"Select a certificate to use for authentication"
1764 # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1765 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1767 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1771 PCCERT_CONTEXT cert;
1776 if (sk_X509_num(certs) == 1)
1778 ctx = ENGINE_get_ex_data(e, capi_idx);
1779 /* Create an in memory store of certificates */
1780 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1781 CERT_STORE_CREATE_NEW_FLAG, NULL);
1783 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1784 capi_addlasterror();
1787 /* Add all certificates to store */
1788 for (i = 0; i < sk_X509_num(certs); i++) {
1789 x = sk_X509_value(certs, i);
1790 key = X509_get_ex_data(x, cert_capi_idx);
1792 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1793 CERT_STORE_ADD_NEW, NULL)) {
1794 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1795 capi_addlasterror();
1800 hwnd = GetForegroundWindow();
1802 hwnd = GetActiveWindow();
1803 if (!hwnd && ctx->getconswindow)
1804 hwnd = ctx->getconswindow();
1805 /* Call dialog to select one */
1806 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1807 dlg_columns, 0, NULL);
1809 /* Find matching cert from list */
1811 for (i = 0; i < sk_X509_num(certs); i++) {
1812 x = sk_X509_value(certs, i);
1813 key = X509_get_ex_data(x, cert_capi_idx);
1814 if (CertCompareCertificate
1815 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1816 key->pcert->pCertInfo)) {
1825 CertCloseStore(dstore, 0);
1831 #else /* !__COMPILE_CAPIENG */
1832 # include <openssl/engine.h>
1833 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1835 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1837 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1842 IMPLEMENT_DYNAMIC_CHECK_FN()
1844 void ENGINE_load_capi(void)