2 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
5 /* ====================================================================
6 * Copyright (c) 2008 The OpenSSL Project. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
34 * 6. Redistributions of any form whatsoever must retain the following
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
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
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"
125 static const char *engine_capi_id = "capi";
126 static const char *engine_capi_name = "CryptoAPI ENGINE";
128 typedef struct CAPI_CTX_st CAPI_CTX;
129 typedef struct CAPI_KEY_st CAPI_KEY;
131 static void capi_addlasterror(void);
132 static void capi_adderror(DWORD err);
134 static void CAPI_trace(CAPI_CTX *ctx, char *format, ...);
136 static int capi_list_providers(CAPI_CTX *ctx, BIO *out);
137 static int capi_list_containers(CAPI_CTX *ctx, BIO *out);
138 int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *storename);
139 void capi_free_key(CAPI_KEY *key);
141 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore);
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, unsigned int m_len,
148 unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
149 static int capi_rsa_priv_enc(int flen, const unsigned char *from,
150 unsigned char *to, RSA *rsa, int padding);
151 static int capi_rsa_priv_dec(int flen, const unsigned char *from,
152 unsigned char *to, RSA *rsa, int padding);
153 static int capi_rsa_free(RSA *rsa);
155 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
157 static int capi_dsa_free(DSA *dsa);
159 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
160 STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey,
161 STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data);
163 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
164 #ifdef OPENSSL_CAPIENG_DIALOG
165 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
168 typedef PCCERT_CONTEXT (WINAPI *CERTDLG)(HCERTSTORE, HWND, LPCWSTR,
169 LPCWSTR, DWORD, DWORD,
171 typedef HWND (WINAPI *GETCONSWIN)(void);
173 /* This structure contains CAPI ENGINE specific data:
174 * it contains various global options and affects how
175 * other functions behave.
178 #define CAPI_DBG_TRACE 2
179 #define CAPI_DBG_ERROR 1
184 /* Parameters to use for container lookup */
188 /* Certificate store name to use */
190 LPSTR ssl_client_store;
191 /* System store flags */
194 /* Lookup string meanings in load_private_key */
195 /* Substring of subject: uses "storename" */
196 #define CAPI_LU_SUBSTR 1
197 /* Friendly name: uses storename */
198 #define CAPI_LU_FNAME 2
199 /* Container name: uses cspname, keytype */
200 #define CAPI_LU_CONTNAME 3
202 /* Info to dump with dumpcerts option */
203 /* Issuer and serial name strings */
204 #define CAPI_DMP_SUMMARY 0x1
206 #define CAPI_DMP_FNAME 0x2
207 /* Full X509_print dump */
208 #define CAPI_DMP_FULL 0x4
209 /* Dump PEM format certificate */
210 #define CAPI_DMP_PEM 0x8
211 /* Dump pseudo key (if possible) */
212 #define CAPI_DMP_PSKEY 0x10
213 /* Dump key info (if possible) */
214 #define CAPI_DMP_PKEYINFO 0x20
217 int (*client_cert_select)(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
219 CERTDLG certselectdlg;
220 GETCONSWIN getconswindow;
224 static CAPI_CTX *capi_ctx_new();
225 static void capi_ctx_free(CAPI_CTX *ctx);
226 static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check);
227 static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx);
229 #define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
230 #define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
231 #define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
232 #define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
233 #define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
234 #define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
235 #define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
236 #define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
237 #define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
238 #define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
239 #define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
240 #define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
241 #define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
242 #define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
244 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
245 {CAPI_CMD_LIST_CERTS,
247 "List all certificates in store",
248 ENGINE_CMD_FLAG_NO_INPUT},
249 {CAPI_CMD_LOOKUP_CERT,
251 "Lookup and output certificates",
252 ENGINE_CMD_FLAG_STRING},
253 {CAPI_CMD_DEBUG_LEVEL,
255 "debug level (1=errors, 2=trace)",
256 ENGINE_CMD_FLAG_NUMERIC},
257 {CAPI_CMD_DEBUG_FILE,
259 "debugging filename)",
260 ENGINE_CMD_FLAG_STRING},
263 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
264 ENGINE_CMD_FLAG_NUMERIC},
268 ENGINE_CMD_FLAG_NO_INPUT},
269 {CAPI_CMD_SET_CSP_IDX,
272 ENGINE_CMD_FLAG_NUMERIC},
273 {CAPI_CMD_SET_CSP_NAME,
275 "Set CSP name, (default CSP used if not specified)",
276 ENGINE_CMD_FLAG_STRING},
277 {CAPI_CMD_SET_CSP_TYPE,
279 "Set CSP type, (default RSA_PROV_FULL)",
280 ENGINE_CMD_FLAG_NUMERIC},
281 {CAPI_CMD_LIST_CONTAINERS,
283 "list container names",
284 ENGINE_CMD_FLAG_NO_INPUT},
285 {CAPI_CMD_LIST_OPTIONS,
287 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
288 "32=private key info)",
289 ENGINE_CMD_FLAG_NUMERIC},
290 {CAPI_CMD_LOOKUP_METHOD,
292 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
293 ENGINE_CMD_FLAG_NUMERIC},
294 {CAPI_CMD_STORE_NAME,
296 "certificate store name, default \"MY\"",
297 ENGINE_CMD_FLAG_STRING},
298 {CAPI_CMD_STORE_FLAGS,
300 "Certificate store flags: 1 = system store",
301 ENGINE_CMD_FLAG_NUMERIC},
306 static int capi_idx = -1;
307 static int rsa_capi_idx = -1;
308 static int dsa_capi_idx = -1;
309 static int cert_capi_idx = -1;
311 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
318 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
321 ctx = ENGINE_get_ex_data(e, capi_idx);
322 out = BIO_new_fp(stdout, BIO_NOCLOSE);
325 case CAPI_CMD_LIST_CSPS:
326 ret = capi_list_providers(ctx, out);
329 case CAPI_CMD_LIST_CERTS:
330 ret = capi_list_certs(ctx, out, NULL);
333 case CAPI_CMD_LOOKUP_CERT:
334 ret = capi_list_certs(ctx, out, p);
337 case CAPI_CMD_LIST_CONTAINERS:
338 ret = capi_list_containers(ctx, out);
341 case CAPI_CMD_STORE_NAME:
343 OPENSSL_free(ctx->storename);
344 ctx->storename = BUF_strdup(p);
345 CAPI_trace(ctx, "Setting store name to %s\n", p);
348 case CAPI_CMD_STORE_FLAGS:
351 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
352 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
356 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
357 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
359 CAPI_trace(ctx, "Setting flags to %d\n", i);
362 case CAPI_CMD_DEBUG_LEVEL:
363 ctx->debug_level = (int)i;
364 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
367 case CAPI_CMD_DEBUG_FILE:
368 ctx->debug_file = BUF_strdup(p);
369 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
372 case CAPI_CMD_KEYTYPE:
374 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
377 case CAPI_CMD_SET_CSP_IDX:
378 ret = capi_ctx_set_provname_idx(ctx, i);
381 case CAPI_CMD_LIST_OPTIONS:
385 case CAPI_CMD_LOOKUP_METHOD:
388 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
391 ctx->lookup_method = i;
394 case CAPI_CMD_SET_CSP_NAME:
395 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
398 case CAPI_CMD_SET_CSP_TYPE:
403 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
412 static RSA_METHOD capi_rsa_method =
414 "CryptoAPI RSA method",
417 capi_rsa_priv_enc, /* priv_enc */
418 capi_rsa_priv_dec, /* priv_dec */
422 capi_rsa_free, /* finish */
423 RSA_FLAG_SIGN_VER, /* flags */
425 capi_rsa_sign, /* rsa_sign */
429 static DSA_METHOD capi_dsa_method =
431 "CryptoAPI DSA method",
432 capi_dsa_do_sign, /* dsa_do_sign */
433 0, /* dsa_sign_setup */
434 0, /* dsa_do_verify */
438 capi_dsa_free, /* finish */
441 0, /* dsa_paramgen */
445 static int capi_init(ENGINE *e)
448 const RSA_METHOD *ossl_rsa_meth;
449 const DSA_METHOD *ossl_dsa_meth;
450 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
451 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
453 ctx = capi_ctx_new();
454 if (!ctx || (capi_idx < 0))
457 ENGINE_set_ex_data(e, capi_idx, ctx);
458 /* Setup RSA_METHOD */
459 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
460 ossl_rsa_meth = RSA_PKCS1_SSLeay();
461 capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc;
462 capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec;
463 capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp;
464 capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp;
466 /* Setup DSA Method */
467 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
468 ossl_dsa_meth = DSA_OpenSSL();
469 capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify;
470 capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp;
471 capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp;
473 #ifdef OPENSSL_CAPIENG_DIALOG
475 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
476 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
478 ctx->certselectdlg = (CERTDLG)GetProcAddress(cryptui, "CryptUIDlgSelectCertificateFromStore");
480 ctx->getconswindow = (GETCONSWIN)GetProcAddress(kernel, "GetConsoleWindow");
481 if (cryptui && !OPENSSL_isservice())
482 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
513 * a handle to the private key container (for sign operations)
514 * and a handle to the key (for decrypt operations).
519 /* Associated certificate context (if any) */
520 PCCERT_CONTEXT pcert;
526 static int bind_capi(ENGINE *e)
528 if (!ENGINE_set_id(e, engine_capi_id)
529 || !ENGINE_set_name(e, engine_capi_name)
530 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
531 || !ENGINE_set_init_function(e, capi_init)
532 || !ENGINE_set_finish_function(e, capi_finish)
533 || !ENGINE_set_destroy_function(e, capi_destroy)
534 || !ENGINE_set_RSA(e, &capi_rsa_method)
535 || !ENGINE_set_DSA(e, &capi_dsa_method)
536 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
537 || !ENGINE_set_load_ssl_client_cert_function(e,
538 capi_load_ssl_client_cert)
539 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
540 || !ENGINE_set_ctrl_function(e, capi_ctrl))
542 ERR_load_CAPI_strings();
548 #ifndef OPENSSL_NO_DYNAMIC_ENGINE
549 static int bind_helper(ENGINE *e, const char *id)
551 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();
573 void ENGINE_load_capi(void)
575 /* Copied from eng_[openssl|dyn].c */
576 ENGINE *toadd = engine_capi();
585 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
588 /* Reverse buffer in place: since this is a keyblob structure
589 * that will be freed up after conversion anyway it doesn't
590 * matter if we change it.
592 for(i = 0; i < binlen / 2; i++)
596 bin[i] = bin[binlen - i - 1];
597 bin[binlen - i - 1] = c;
600 if (!BN_bin2bn(bin, binlen, bn))
605 /* Given a CAPI_KEY get an EVP_PKEY structure */
607 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY *key)
609 unsigned char *pubkey = NULL;
614 EVP_PKEY *ret = NULL;
615 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len))
617 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
622 pubkey = OPENSSL_malloc(len);
627 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len))
629 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
634 bh = (BLOBHEADER *)pubkey;
635 if (bh->bType != PUBLICKEYBLOB)
637 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
640 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX)
644 unsigned char *rsa_modulus;
645 rp = (RSAPUBKEY *)(bh + 1);
646 if (rp->magic != 0x31415352)
649 BIO_snprintf(magstr, 10, "%lx", rp->magic);
650 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
651 ERR_add_error_data(2, "magic=0x", magstr);
654 rsa_modulus = (unsigned char *)(rp + 1);
655 rkey = RSA_new_method(eng);
662 if (!rkey->e || !rkey->n)
665 if (!BN_set_word(rkey->e, rp->pubexp))
668 rsa_modlen = rp->bitlen / 8;
669 if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
672 RSA_set_ex_data(rkey, rsa_capi_idx, key);
674 if (!(ret = EVP_PKEY_new()))
677 EVP_PKEY_assign_RSA(ret, rkey);
681 else if (bh->aiKeyAlg == CALG_DSS_SIGN)
686 dp = (DSSPUBKEY *)(bh + 1);
687 if (dp->magic != 0x31535344)
690 BIO_snprintf(magstr, 10, "%lx", dp->magic);
691 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
692 ERR_add_error_data(2, "magic=0x", magstr);
695 dsa_plen = dp->bitlen / 8;
696 btmp = (unsigned char *)(dp + 1);
697 dkey = DSA_new_method(eng);
703 dkey->pub_key = BN_new();
704 if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key)
706 if (!lend_tobn(dkey->p, btmp, dsa_plen))
709 if (!lend_tobn(dkey->q, btmp, 20))
712 if (!lend_tobn(dkey->g, btmp, dsa_plen))
715 if (!lend_tobn(dkey->pub_key, btmp, dsa_plen))
719 DSA_set_ex_data(dkey, dsa_capi_idx, key);
721 if (!(ret = EVP_PKEY_new()))
724 EVP_PKEY_assign_DSA(ret, dkey);
730 BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg);
731 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
732 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
739 OPENSSL_free(pubkey);
751 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
756 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
757 UI_METHOD *ui_method, void *callback_data)
762 ctx = ENGINE_get_ex_data(eng, capi_idx);
766 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
770 key = capi_find_key(ctx, key_id);
775 ret = capi_get_pkey(eng, key);
783 /* CryptoAPI RSA operations */
785 int capi_rsa_priv_enc(int flen, const unsigned char *from,
786 unsigned char *to, RSA *rsa, int padding)
788 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
792 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
793 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
803 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
805 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
807 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
810 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
813 /* Convert the signature type to a CryptoAPI algorithm ID */
825 alg = CALG_SSL3_SHAMD5;
830 BIO_snprintf(algstr, 10, "%lx", dtype);
831 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
832 ERR_add_error_data(2, "NID=0x", algstr);
839 /* Create the hash object */
840 if(!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash))
842 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
846 /* Set the hash value to the value passed */
848 if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0))
850 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
856 /* Finally sign it */
857 slen = RSA_size(rsa);
858 if(!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen))
860 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
867 /* Inplace byte reversal of signature */
868 for(i = 0; i < slen / 2; i++)
872 sigret[i] = sigret[slen - i - 1];
873 sigret[slen - i - 1] = c;
881 CryptDestroyHash(hash);
886 int capi_rsa_priv_dec(int flen, const unsigned char *from,
887 unsigned char *to, RSA *rsa, int padding)
890 unsigned char *tmpbuf;
893 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
895 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
898 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
901 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
905 if(padding != RSA_PKCS1_PADDING)
908 BIO_snprintf(errstr, 10, "%d", padding);
909 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
910 ERR_add_error_data(2, "padding=", errstr);
914 /* Create temp reverse order version of input */
915 if(!(tmpbuf = OPENSSL_malloc(flen)) )
917 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
920 for(i = 0; i < flen; i++)
921 tmpbuf[flen - i - 1] = from[i];
923 /* Finally decrypt it */
924 if(!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen))
926 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
928 OPENSSL_free(tmpbuf);
931 else memcpy(to, tmpbuf, flen);
933 OPENSSL_free(tmpbuf);
938 static int capi_rsa_free(RSA *rsa)
941 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
942 capi_free_key(capi_key);
943 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
947 /* CryptoAPI DSA operations */
949 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
957 unsigned char csigbuf[40];
959 ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
961 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
963 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
967 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
973 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
977 /* Create the hash object */
978 if(!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash))
980 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
985 /* Set the hash value to the value passed */
986 if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0))
988 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
994 /* Finally sign it */
995 slen = sizeof(csigbuf);
996 if(!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen))
998 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1004 ret = DSA_SIG_new();
1009 if (!ret->r || !ret->s)
1011 if (!lend_tobn(ret->r, csigbuf, 20)
1012 || !lend_tobn(ret->s, csigbuf + 20, 20))
1023 OPENSSL_cleanse(csigbuf, 40);
1024 CryptDestroyHash(hash);
1028 static int capi_dsa_free(DSA *dsa)
1031 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1032 capi_free_key(capi_key);
1033 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1037 static void capi_vtrace(CAPI_CTX *ctx, int level, char *format, va_list argptr)
1041 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1043 out = BIO_new_file(ctx->debug_file, "a+");
1044 BIO_vprintf(out, format, argptr);
1048 static void CAPI_trace(CAPI_CTX *ctx, char *format, ...)
1051 va_start(args, format);
1052 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1056 static void capi_addlasterror(void)
1058 capi_adderror(GetLastError());
1061 static void capi_adderror(DWORD err)
1064 BIO_snprintf(errstr, 10, "%lX", err);
1065 ERR_add_error_data(2, "Error code= 0x", errstr);
1068 static char *wide_to_asc(LPCWSTR wstr)
1075 len_0 = (int)wcslen(wstr)+1; /* WideCharToMultiByte expects int */
1076 sz = WideCharToMultiByte(CP_ACP,0,wstr,len_0,NULL,0,NULL,NULL);
1079 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1082 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))
1091 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1097 static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype, DWORD idx)
1101 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1102 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len))
1104 err = GetLastError();
1105 if (err == ERROR_NO_MORE_ITEMS)
1107 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1111 if (sizeof(TCHAR) != sizeof(char))
1114 name = OPENSSL_malloc(len);
1115 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len))
1117 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);
1127 *pname = (char *)name;
1128 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname, *ptype);
1133 static int capi_list_providers(CAPI_CTX *ctx, BIO *out)
1137 LPSTR provname = NULL;
1138 CAPI_trace(ctx, "capi_list_providers\n");
1139 BIO_printf(out, "Available CSPs:\n");
1140 for(idx = 0; ; idx++)
1142 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1147 BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
1148 OPENSSL_free(provname);
1153 static int capi_list_containers(CAPI_CTX *ctx, BIO *out)
1157 DWORD err, idx, flags, buflen = 0, clen;
1159 LPTSTR cspname = NULL;
1161 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname, ctx->csptype);
1162 if (ctx->cspname && sizeof(TCHAR)!=sizeof(char))
1164 if ((clen=MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,NULL,0)))
1166 cspname = alloca(clen*sizeof(WCHAR));
1167 MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,(WCHAR *)cspname,clen);
1171 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1172 capi_addlasterror();
1177 cspname = (TCHAR *)ctx->cspname;
1178 if (!CryptAcquireContext(&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT))
1180 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1181 capi_addlasterror();
1184 if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST))
1186 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1187 capi_addlasterror();
1190 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1193 cname = OPENSSL_malloc(buflen);
1196 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1200 for (idx = 0;;idx++)
1206 flags = CRYPT_FIRST;
1209 if(!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, (BYTE *)cname, &clen, flags))
1211 err = GetLastError();
1212 if (err == ERROR_NO_MORE_ITEMS)
1214 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1218 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n", cname, clen, idx, flags);
1219 if (!cname[0] && (clen == buflen))
1221 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1224 BIO_printf(out, "%d. %s\n", idx, cname);
1232 OPENSSL_free(cname);
1233 CryptReleaseContext(hprov, 0);
1238 CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1241 CRYPT_KEY_PROV_INFO *pinfo;
1243 if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1245 pinfo = OPENSSL_malloc(len);
1248 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1251 if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len))
1253 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1254 capi_addlasterror();
1255 OPENSSL_free(pinfo);
1261 static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out, CRYPT_KEY_PROV_INFO *pinfo)
1263 char *provname = NULL, *contname = NULL;
1266 BIO_printf(out, " No Private Key\n");
1269 provname = wide_to_asc(pinfo->pwszProvName);
1270 contname = wide_to_asc(pinfo->pwszContainerName);
1271 if (!provname || !contname)
1274 BIO_printf(out, " Private Key Info:\n");
1275 BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname, pinfo->dwProvType);
1276 BIO_printf(out, " Container Name: %s, Key Type %d\n", contname, pinfo->dwKeySpec);
1279 OPENSSL_free(provname);
1281 OPENSSL_free(contname);
1284 char * capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1289 CAPI_trace(ctx, "capi_cert_get_fname\n");
1290 if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1292 wfname = OPENSSL_malloc(dlen);
1293 if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen))
1295 char *fname = wide_to_asc(wfname);
1296 OPENSSL_free(wfname);
1299 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1300 capi_addlasterror();
1302 OPENSSL_free(wfname);
1307 void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert)
1311 unsigned long flags = ctx->dump_flags;
1312 if (flags & CAPI_DMP_FNAME)
1315 fname = capi_cert_get_fname(ctx, cert);
1318 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1319 OPENSSL_free(fname);
1322 BIO_printf(out, " <No Friendly Name>\n");
1325 p = cert->pbCertEncoded;
1326 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1328 BIO_printf(out, " <Can't parse certificate>\n");
1329 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)
1342 CRYPT_KEY_PROV_INFO *pinfo;
1343 pinfo = capi_get_prov_info(ctx, cert);
1344 capi_dump_prov_info(ctx, out, pinfo);
1346 OPENSSL_free(pinfo);
1349 if (flags & CAPI_DMP_PEM)
1350 PEM_write_bio_X509(out, x);
1354 HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename)
1359 storename = ctx->storename;
1362 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1364 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1365 ctx->store_flags, storename);
1368 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1369 capi_addlasterror();
1374 int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id)
1380 PCCERT_CONTEXT cert = NULL;
1382 storename = ctx->storename;
1385 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1387 hstore = capi_open_store(ctx, storename);
1392 cert = capi_find_cert(ctx, id, hstore);
1398 capi_dump_cert(ctx, out, cert);
1399 CertFreeCertificateContext(cert);
1405 cert = CertEnumCertificatesInStore(hstore, cert);
1408 BIO_printf(out, "Certificate %d\n", idx);
1409 capi_dump_cert(ctx, out, cert);
1413 CertCloseStore(hstore, 0);
1417 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore)
1419 PCCERT_CONTEXT cert = NULL;
1422 switch(ctx->lookup_method)
1424 case CAPI_LU_SUBSTR:
1425 return CertFindCertificateInStore(hstore,
1426 X509_ASN_ENCODING, 0,
1427 CERT_FIND_SUBJECT_STR_A, id, NULL);
1431 cert = CertEnumCertificatesInStore(hstore, cert);
1434 fname = capi_cert_get_fname(ctx, cert);
1437 if (strcmp(fname, id))
1441 OPENSSL_free(fname);
1451 static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const TCHAR *contname, TCHAR *provname, DWORD ptype, DWORD keyspec)
1454 key = OPENSSL_malloc(sizeof(CAPI_KEY));
1455 if (sizeof(TCHAR)==sizeof(char))
1456 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1457 contname, provname, ptype);
1458 else if (ctx && ctx->debug_level>=CAPI_DBG_TRACE && ctx->debug_file)
1460 /* above 'if' is optimization to minimize malloc-ations */
1461 char *_contname = wide_to_asc((WCHAR *)contname);
1462 char *_provname = wide_to_asc((WCHAR *)provname);
1464 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1465 _contname, _provname, ptype);
1466 if (_provname) OPENSSL_free(_provname);
1467 if (_contname) OPENSSL_free(_contname);
1469 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, 0))
1471 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1472 capi_addlasterror();
1475 if (!CryptGetUserKey(key->hprov, keyspec, &key->key))
1477 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1478 capi_addlasterror();
1479 CryptReleaseContext(key->hprov, 0);
1482 key->keyspec = keyspec;
1491 static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1493 CAPI_KEY *key = NULL;
1494 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1495 char *provname = NULL, *contname = NULL;
1496 pinfo = capi_get_prov_info(ctx, cert);
1499 if (sizeof(TCHAR) != sizeof(char))
1500 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1501 (TCHAR *)pinfo->pwszProvName,
1502 pinfo->dwProvType, pinfo->dwKeySpec);
1505 provname = wide_to_asc(pinfo->pwszProvName);
1506 contname = wide_to_asc(pinfo->pwszContainerName);
1507 if (!provname || !contname)
1509 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1510 pinfo->dwProvType, pinfo->dwKeySpec);
1515 OPENSSL_free(pinfo);
1517 OPENSSL_free(provname);
1519 OPENSSL_free(contname);
1523 CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id)
1525 PCCERT_CONTEXT cert;
1527 CAPI_KEY *key = NULL;
1528 switch (ctx->lookup_method)
1530 case CAPI_LU_SUBSTR:
1532 hstore = capi_open_store(ctx, NULL);
1535 cert = capi_find_cert(ctx, id, hstore);
1538 key = capi_get_cert_key(ctx, cert);
1539 CertFreeCertificateContext(cert);
1541 CertCloseStore(hstore, 0);
1544 case CAPI_LU_CONTNAME:
1545 if (sizeof(TCHAR)!=sizeof(char))
1547 WCHAR *contname, *provname;
1550 if ((len=MultiByteToWideChar(CP_ACP,0,id,-1,NULL,0)) &&
1551 (contname=alloca(len*sizeof(WCHAR)),
1552 MultiByteToWideChar(CP_ACP,0,id,-1,contname,len)) &&
1553 (len=MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,NULL,0)) &&
1554 (provname=alloca(len*sizeof(WCHAR)),
1555 MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,provname,len)))
1556 key = capi_get_key(ctx,(TCHAR *)contname,
1558 ctx->csptype,ctx->keytype);
1561 key = capi_get_key(ctx, (TCHAR *)id,
1562 (TCHAR *)ctx->cspname,
1563 ctx->csptype,ctx->keytype);
1570 void capi_free_key(CAPI_KEY *key)
1574 CryptDestroyKey(key->key);
1575 CryptReleaseContext(key->hprov, 0);
1577 CertFreeCertificateContext(key->pcert);
1582 /* Initialize a CAPI_CTX structure */
1584 static CAPI_CTX *capi_ctx_new()
1587 ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
1590 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1593 ctx->cspname = NULL;
1594 ctx->csptype = PROV_RSA_FULL;
1595 ctx->dump_flags = CAPI_DMP_SUMMARY|CAPI_DMP_FNAME;
1596 ctx->keytype = AT_KEYEXCHANGE;
1597 ctx->storename = NULL;
1598 ctx->ssl_client_store = NULL;
1599 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1600 CERT_STORE_READONLY_FLAG |
1601 CERT_SYSTEM_STORE_CURRENT_USER;
1602 ctx->lookup_method = CAPI_LU_SUBSTR;
1603 ctx->debug_level = 0;
1604 ctx->debug_file = NULL;
1605 ctx->client_cert_select = cert_select_simple;
1609 static void capi_ctx_free(CAPI_CTX *ctx)
1611 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1615 OPENSSL_free(ctx->cspname);
1616 if (ctx->debug_file)
1617 OPENSSL_free(ctx->debug_file);
1619 OPENSSL_free(ctx->storename);
1620 if (ctx->ssl_client_store)
1621 OPENSSL_free(ctx->ssl_client_store);
1625 static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check)
1627 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1633 if (sizeof(TCHAR)!=sizeof(char))
1636 if ((len=MultiByteToWideChar(CP_ACP,0,pname,-1,NULL,0)))
1638 name = alloca(len*sizeof(WCHAR));
1639 MultiByteToWideChar(CP_ACP,0,pname,-1,(WCHAR *)name,len);
1643 name = (TCHAR *)pname;
1645 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1646 CRYPT_VERIFYCONTEXT))
1648 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1649 capi_addlasterror();
1652 CryptReleaseContext(hprov, 0);
1654 ctx->cspname = BUF_strdup(pname);
1655 ctx->csptype = type;
1659 static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx)
1663 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1665 return capi_ctx_set_provname(ctx, pname, type, 0);
1668 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1672 /* Special case: empty list: match anything */
1673 if (sk_X509_NAME_num(ca_dn) <= 0)
1675 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++)
1677 nm = sk_X509_NAME_value(ca_dn, i);
1678 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1686 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1687 STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey,
1688 STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data)
1690 STACK_OF(X509) *certs = NULL;
1694 int i, client_cert_idx;
1696 PCCERT_CONTEXT cert = NULL, excert = NULL;
1699 ctx = ENGINE_get_ex_data(e, capi_idx);
1704 storename = ctx->ssl_client_store;
1708 hstore = capi_open_store(ctx, storename);
1711 /* Enumerate all certificates collect any matches */
1714 cert = CertEnumCertificatesInStore(hstore, cert);
1717 p = cert->pbCertEncoded;
1718 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1721 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1724 if (cert_issuer_match(ca_dn, x)
1725 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0))
1727 key = capi_get_cert_key(ctx, cert);
1733 /* Match found: attach extra data to it so
1734 * we can retrieve the key later.
1736 excert = CertDuplicateCertificateContext(cert);
1737 key->pcert = excert;
1738 X509_set_ex_data(x, cert_capi_idx, key);
1741 certs = sk_X509_new_null();
1743 sk_X509_push(certs, x);
1751 CertFreeCertificateContext(cert);
1753 CertCloseStore(hstore, 0);
1759 /* Select the appropriate certificate */
1761 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1763 /* Set the selected certificate and free the rest */
1765 for(i = 0; i < sk_X509_num(certs); i++)
1767 x = sk_X509_value(certs, i);
1768 if (i == client_cert_idx)
1772 key = X509_get_ex_data(x, cert_capi_idx);
1778 sk_X509_free(certs);
1783 /* Setup key for selected certificate */
1785 key = X509_get_ex_data(*pcert, cert_capi_idx);
1786 *pkey = capi_get_pkey(e, key);
1787 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1794 /* Simple client cert selection function: always select first */
1796 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1801 #ifdef OPENSSL_CAPIENG_DIALOG
1803 /* More complex cert selection function, using standard function
1804 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1807 /* Definitions which are in cryptuiapi.h but this is not present in older
1808 * versions of headers.
1811 #ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1812 #define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1813 #define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1816 #define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1817 #define dlg_prompt L"Select a certificate to use for authentication"
1818 #define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1819 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1821 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1825 PCCERT_CONTEXT cert;
1830 if (sk_X509_num(certs) == 1)
1832 ctx = ENGINE_get_ex_data(e, capi_idx);
1833 /* Create an in memory store of certificates */
1834 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1835 CERT_STORE_CREATE_NEW_FLAG, NULL);
1838 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1839 capi_addlasterror();
1842 /* Add all certificates to store */
1843 for(i = 0; i < sk_X509_num(certs); i++)
1845 x = sk_X509_value(certs, i);
1846 key = X509_get_ex_data(x, cert_capi_idx);
1848 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1849 CERT_STORE_ADD_NEW, NULL))
1851 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1852 capi_addlasterror();
1857 hwnd = GetForegroundWindow();
1859 hwnd = GetActiveWindow();
1860 if (!hwnd && ctx->getconswindow)
1861 hwnd = ctx->getconswindow();
1862 /* Call dialog to select one */
1863 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1864 dlg_columns, 0, NULL);
1866 /* Find matching cert from list */
1869 for(i = 0; i < sk_X509_num(certs); i++)
1871 x = sk_X509_value(certs, i);
1872 key = X509_get_ex_data(x, cert_capi_idx);
1873 if (CertCompareCertificate(
1874 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1876 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) { return 0; }
1899 IMPLEMENT_DYNAMIC_CHECK_FN()
1901 void ENGINE_load_capi(void){}