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 #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
128 #define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
131 #define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
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"
145 static const char *engine_capi_id = "capi";
146 static const char *engine_capi_name = "CryptoAPI ENGINE";
148 typedef struct CAPI_CTX_st CAPI_CTX;
149 typedef struct CAPI_KEY_st CAPI_KEY;
151 static void capi_addlasterror(void);
152 static void capi_adderror(DWORD err);
154 static void CAPI_trace(CAPI_CTX *ctx, char *format, ...);
156 static int capi_list_providers(CAPI_CTX *ctx, BIO *out);
157 static int capi_list_containers(CAPI_CTX *ctx, BIO *out);
158 int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *storename);
159 void capi_free_key(CAPI_KEY *key);
161 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore);
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, unsigned int m_len,
168 unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
169 static int capi_rsa_priv_enc(int flen, const unsigned char *from,
170 unsigned char *to, RSA *rsa, int padding);
171 static int capi_rsa_priv_dec(int flen, const unsigned char *from,
172 unsigned char *to, RSA *rsa, int padding);
173 static int capi_rsa_free(RSA *rsa);
175 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
177 static int capi_dsa_free(DSA *dsa);
179 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
180 STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey,
181 STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data);
183 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
184 #ifdef OPENSSL_CAPIENG_DIALOG
185 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
188 typedef PCCERT_CONTEXT (WINAPI *CERTDLG)(HCERTSTORE, HWND, LPCWSTR,
189 LPCWSTR, DWORD, DWORD,
191 typedef HWND (WINAPI *GETCONSWIN)(void);
193 /* This structure contains CAPI ENGINE specific data:
194 * it contains various global options and affects how
195 * other functions behave.
198 #define CAPI_DBG_TRACE 2
199 #define CAPI_DBG_ERROR 1
204 /* Parameters to use for container lookup */
208 /* Certificate store name to use */
210 LPSTR ssl_client_store;
211 /* System store flags */
214 /* Lookup string meanings in load_private_key */
215 /* Substring of subject: uses "storename" */
216 #define CAPI_LU_SUBSTR 1
217 /* Friendly name: uses storename */
218 #define CAPI_LU_FNAME 2
219 /* Container name: uses cspname, keytype */
220 #define CAPI_LU_CONTNAME 3
222 /* Info to dump with dumpcerts option */
223 /* Issuer and serial name strings */
224 #define CAPI_DMP_SUMMARY 0x1
226 #define CAPI_DMP_FNAME 0x2
227 /* Full X509_print dump */
228 #define CAPI_DMP_FULL 0x4
229 /* Dump PEM format certificate */
230 #define CAPI_DMP_PEM 0x8
231 /* Dump pseudo key (if possible) */
232 #define CAPI_DMP_PSKEY 0x10
233 /* Dump key info (if possible) */
234 #define CAPI_DMP_PKEYINFO 0x20
237 int (*client_cert_select)(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
239 CERTDLG certselectdlg;
240 GETCONSWIN getconswindow;
244 static CAPI_CTX *capi_ctx_new();
245 static void capi_ctx_free(CAPI_CTX *ctx);
246 static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check);
247 static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx);
249 #define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
250 #define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
251 #define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
252 #define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
253 #define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
254 #define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
255 #define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
256 #define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
257 #define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
258 #define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
259 #define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
260 #define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
261 #define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
262 #define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
264 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
265 {CAPI_CMD_LIST_CERTS,
267 "List all certificates in store",
268 ENGINE_CMD_FLAG_NO_INPUT},
269 {CAPI_CMD_LOOKUP_CERT,
271 "Lookup and output certificates",
272 ENGINE_CMD_FLAG_STRING},
273 {CAPI_CMD_DEBUG_LEVEL,
275 "debug level (1=errors, 2=trace)",
276 ENGINE_CMD_FLAG_NUMERIC},
277 {CAPI_CMD_DEBUG_FILE,
279 "debugging filename)",
280 ENGINE_CMD_FLAG_STRING},
283 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
284 ENGINE_CMD_FLAG_NUMERIC},
288 ENGINE_CMD_FLAG_NO_INPUT},
289 {CAPI_CMD_SET_CSP_IDX,
292 ENGINE_CMD_FLAG_NUMERIC},
293 {CAPI_CMD_SET_CSP_NAME,
295 "Set CSP name, (default CSP used if not specified)",
296 ENGINE_CMD_FLAG_STRING},
297 {CAPI_CMD_SET_CSP_TYPE,
299 "Set CSP type, (default RSA_PROV_FULL)",
300 ENGINE_CMD_FLAG_NUMERIC},
301 {CAPI_CMD_LIST_CONTAINERS,
303 "list container names",
304 ENGINE_CMD_FLAG_NO_INPUT},
305 {CAPI_CMD_LIST_OPTIONS,
307 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
308 "32=private key info)",
309 ENGINE_CMD_FLAG_NUMERIC},
310 {CAPI_CMD_LOOKUP_METHOD,
312 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
313 ENGINE_CMD_FLAG_NUMERIC},
314 {CAPI_CMD_STORE_NAME,
316 "certificate store name, default \"MY\"",
317 ENGINE_CMD_FLAG_STRING},
318 {CAPI_CMD_STORE_FLAGS,
320 "Certificate store flags: 1 = system store",
321 ENGINE_CMD_FLAG_NUMERIC},
326 static int capi_idx = -1;
327 static int rsa_capi_idx = -1;
328 static int dsa_capi_idx = -1;
329 static int cert_capi_idx = -1;
331 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
338 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
341 ctx = ENGINE_get_ex_data(e, capi_idx);
342 out = BIO_new_fp(stdout, BIO_NOCLOSE);
345 case CAPI_CMD_LIST_CSPS:
346 ret = capi_list_providers(ctx, out);
349 case CAPI_CMD_LIST_CERTS:
350 ret = capi_list_certs(ctx, out, NULL);
353 case CAPI_CMD_LOOKUP_CERT:
354 ret = capi_list_certs(ctx, out, p);
357 case CAPI_CMD_LIST_CONTAINERS:
358 ret = capi_list_containers(ctx, out);
361 case CAPI_CMD_STORE_NAME:
363 OPENSSL_free(ctx->storename);
364 ctx->storename = BUF_strdup(p);
365 CAPI_trace(ctx, "Setting store name to %s\n", p);
368 case CAPI_CMD_STORE_FLAGS:
371 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
372 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
376 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
377 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
379 CAPI_trace(ctx, "Setting flags to %d\n", i);
382 case CAPI_CMD_DEBUG_LEVEL:
383 ctx->debug_level = (int)i;
384 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
387 case CAPI_CMD_DEBUG_FILE:
388 ctx->debug_file = BUF_strdup(p);
389 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
392 case CAPI_CMD_KEYTYPE:
394 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
397 case CAPI_CMD_SET_CSP_IDX:
398 ret = capi_ctx_set_provname_idx(ctx, i);
401 case CAPI_CMD_LIST_OPTIONS:
405 case CAPI_CMD_LOOKUP_METHOD:
408 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
411 ctx->lookup_method = i;
414 case CAPI_CMD_SET_CSP_NAME:
415 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
418 case CAPI_CMD_SET_CSP_TYPE:
423 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
432 static RSA_METHOD capi_rsa_method =
434 "CryptoAPI RSA method",
437 capi_rsa_priv_enc, /* priv_enc */
438 capi_rsa_priv_dec, /* priv_dec */
442 capi_rsa_free, /* finish */
443 RSA_FLAG_SIGN_VER, /* flags */
445 capi_rsa_sign, /* rsa_sign */
449 static DSA_METHOD capi_dsa_method =
451 "CryptoAPI DSA method",
452 capi_dsa_do_sign, /* dsa_do_sign */
453 0, /* dsa_sign_setup */
454 0, /* dsa_do_verify */
458 capi_dsa_free, /* finish */
461 0, /* dsa_paramgen */
465 static int capi_init(ENGINE *e)
468 const RSA_METHOD *ossl_rsa_meth;
469 const DSA_METHOD *ossl_dsa_meth;
473 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
477 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
479 /* Setup RSA_METHOD */
480 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
481 ossl_rsa_meth = RSA_PKCS1_SSLeay();
482 capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc;
483 capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec;
484 capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp;
485 capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp;
487 /* Setup DSA Method */
488 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
489 ossl_dsa_meth = DSA_OpenSSL();
490 capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify;
491 capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp;
492 capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp;
495 ctx = capi_ctx_new();
499 ENGINE_set_ex_data(e, capi_idx, ctx);
501 #ifdef OPENSSL_CAPIENG_DIALOG
503 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
504 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
506 ctx->certselectdlg = (CERTDLG)GetProcAddress(cryptui, "CryptUIDlgSelectCertificateFromStore");
508 ctx->getconswindow = (GETCONSWIN)GetProcAddress(kernel, "GetConsoleWindow");
509 if (cryptui && !OPENSSL_isservice())
510 ctx->client_cert_select = cert_select_dialog;
518 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
524 static int capi_destroy(ENGINE *e)
526 ERR_unload_CAPI_strings();
530 static int capi_finish(ENGINE *e)
533 ctx = ENGINE_get_ex_data(e, capi_idx);
535 ENGINE_set_ex_data(e, capi_idx, NULL);
540 /* CryptoAPI key application data. This contains
541 * a handle to the private key container (for sign operations)
542 * and a handle to the key (for decrypt operations).
547 /* Associated certificate context (if any) */
548 PCCERT_CONTEXT pcert;
554 static int bind_capi(ENGINE *e)
556 if (!ENGINE_set_id(e, engine_capi_id)
557 || !ENGINE_set_name(e, engine_capi_name)
558 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
559 || !ENGINE_set_init_function(e, capi_init)
560 || !ENGINE_set_finish_function(e, capi_finish)
561 || !ENGINE_set_destroy_function(e, capi_destroy)
562 || !ENGINE_set_RSA(e, &capi_rsa_method)
563 || !ENGINE_set_DSA(e, &capi_dsa_method)
564 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
565 || !ENGINE_set_load_ssl_client_cert_function(e,
566 capi_load_ssl_client_cert)
567 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
568 || !ENGINE_set_ctrl_function(e, capi_ctrl))
570 ERR_load_CAPI_strings();
576 #ifndef OPENSSL_NO_DYNAMIC_ENGINE
577 static int bind_helper(ENGINE *e, const char *id)
579 if(id && (strcmp(id, engine_capi_id) != 0))
585 IMPLEMENT_DYNAMIC_CHECK_FN()
586 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
588 static ENGINE *engine_capi(void)
590 ENGINE *ret = ENGINE_new();
601 void ENGINE_load_capi(void)
603 /* Copied from eng_[openssl|dyn].c */
604 ENGINE *toadd = engine_capi();
613 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
616 /* Reverse buffer in place: since this is a keyblob structure
617 * that will be freed up after conversion anyway it doesn't
618 * matter if we change it.
620 for(i = 0; i < binlen / 2; i++)
624 bin[i] = bin[binlen - i - 1];
625 bin[binlen - i - 1] = c;
628 if (!BN_bin2bn(bin, binlen, bn))
633 /* Given a CAPI_KEY get an EVP_PKEY structure */
635 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY *key)
637 unsigned char *pubkey = NULL;
642 EVP_PKEY *ret = NULL;
643 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len))
645 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
650 pubkey = OPENSSL_malloc(len);
655 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len))
657 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
662 bh = (BLOBHEADER *)pubkey;
663 if (bh->bType != PUBLICKEYBLOB)
665 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
668 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX)
672 unsigned char *rsa_modulus;
673 rp = (RSAPUBKEY *)(bh + 1);
674 if (rp->magic != 0x31415352)
677 BIO_snprintf(magstr, 10, "%lx", rp->magic);
678 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
679 ERR_add_error_data(2, "magic=0x", magstr);
682 rsa_modulus = (unsigned char *)(rp + 1);
683 rkey = RSA_new_method(eng);
690 if (!rkey->e || !rkey->n)
693 if (!BN_set_word(rkey->e, rp->pubexp))
696 rsa_modlen = rp->bitlen / 8;
697 if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
700 RSA_set_ex_data(rkey, rsa_capi_idx, key);
702 if (!(ret = EVP_PKEY_new()))
705 EVP_PKEY_assign_RSA(ret, rkey);
709 else if (bh->aiKeyAlg == CALG_DSS_SIGN)
714 dp = (DSSPUBKEY *)(bh + 1);
715 if (dp->magic != 0x31535344)
718 BIO_snprintf(magstr, 10, "%lx", dp->magic);
719 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
720 ERR_add_error_data(2, "magic=0x", magstr);
723 dsa_plen = dp->bitlen / 8;
724 btmp = (unsigned char *)(dp + 1);
725 dkey = DSA_new_method(eng);
731 dkey->pub_key = BN_new();
732 if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key)
734 if (!lend_tobn(dkey->p, btmp, dsa_plen))
737 if (!lend_tobn(dkey->q, btmp, 20))
740 if (!lend_tobn(dkey->g, btmp, dsa_plen))
743 if (!lend_tobn(dkey->pub_key, btmp, dsa_plen))
747 DSA_set_ex_data(dkey, dsa_capi_idx, key);
749 if (!(ret = EVP_PKEY_new()))
752 EVP_PKEY_assign_DSA(ret, dkey);
758 BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg);
759 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
760 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
767 OPENSSL_free(pubkey);
779 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
784 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
785 UI_METHOD *ui_method, void *callback_data)
790 ctx = ENGINE_get_ex_data(eng, capi_idx);
794 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
798 key = capi_find_key(ctx, key_id);
803 ret = capi_get_pkey(eng, key);
811 /* CryptoAPI RSA operations */
813 int capi_rsa_priv_enc(int flen, const unsigned char *from,
814 unsigned char *to, RSA *rsa, int padding)
816 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
820 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
821 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
831 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
833 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
835 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
838 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
841 /* Convert the signature type to a CryptoAPI algorithm ID */
865 alg = CALG_SSL3_SHAMD5;
870 BIO_snprintf(algstr, 10, "%lx", dtype);
871 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
872 ERR_add_error_data(2, "NID=0x", algstr);
879 /* Create the hash object */
880 if(!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash))
882 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
886 /* Set the hash value to the value passed */
888 if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0))
890 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
896 /* Finally sign it */
897 slen = RSA_size(rsa);
898 if(!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen))
900 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
907 /* Inplace byte reversal of signature */
908 for(i = 0; i < slen / 2; i++)
912 sigret[i] = sigret[slen - i - 1];
913 sigret[slen - i - 1] = c;
921 CryptDestroyHash(hash);
926 int capi_rsa_priv_dec(int flen, const unsigned char *from,
927 unsigned char *to, RSA *rsa, int padding)
930 unsigned char *tmpbuf;
933 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
935 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
938 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
941 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
945 if(padding != RSA_PKCS1_PADDING)
948 BIO_snprintf(errstr, 10, "%d", padding);
949 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
950 ERR_add_error_data(2, "padding=", errstr);
954 /* Create temp reverse order version of input */
955 if(!(tmpbuf = OPENSSL_malloc(flen)) )
957 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
960 for(i = 0; i < flen; i++)
961 tmpbuf[flen - i - 1] = from[i];
963 /* Finally decrypt it */
964 if(!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen))
966 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
968 OPENSSL_free(tmpbuf);
971 else memcpy(to, tmpbuf, flen);
973 OPENSSL_free(tmpbuf);
978 static int capi_rsa_free(RSA *rsa)
981 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
982 capi_free_key(capi_key);
983 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
987 /* CryptoAPI DSA operations */
989 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
997 unsigned char csigbuf[40];
999 ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
1001 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
1003 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1007 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
1013 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
1017 /* Create the hash object */
1018 if(!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash))
1020 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
1021 capi_addlasterror();
1025 /* Set the hash value to the value passed */
1026 if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0))
1028 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
1029 capi_addlasterror();
1034 /* Finally sign it */
1035 slen = sizeof(csigbuf);
1036 if(!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen))
1038 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1039 capi_addlasterror();
1044 ret = DSA_SIG_new();
1049 if (!ret->r || !ret->s)
1051 if (!lend_tobn(ret->r, csigbuf, 20)
1052 || !lend_tobn(ret->s, csigbuf + 20, 20))
1063 OPENSSL_cleanse(csigbuf, 40);
1064 CryptDestroyHash(hash);
1068 static int capi_dsa_free(DSA *dsa)
1071 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1072 capi_free_key(capi_key);
1073 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1077 static void capi_vtrace(CAPI_CTX *ctx, int level, char *format, va_list argptr)
1081 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1083 out = BIO_new_file(ctx->debug_file, "a+");
1084 BIO_vprintf(out, format, argptr);
1088 static void CAPI_trace(CAPI_CTX *ctx, char *format, ...)
1091 va_start(args, format);
1092 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1096 static void capi_addlasterror(void)
1098 capi_adderror(GetLastError());
1101 static void capi_adderror(DWORD err)
1104 BIO_snprintf(errstr, 10, "%lX", err);
1105 ERR_add_error_data(2, "Error code= 0x", errstr);
1108 static char *wide_to_asc(LPCWSTR wstr)
1115 len_0 = (int)wcslen(wstr)+1; /* WideCharToMultiByte expects int */
1116 sz = WideCharToMultiByte(CP_ACP,0,wstr,len_0,NULL,0,NULL,NULL);
1119 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1122 str = OPENSSL_malloc(sz);
1125 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1128 if (!WideCharToMultiByte(CP_ACP,0,wstr,len_0,str,sz,NULL,NULL))
1131 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1137 static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype, DWORD idx)
1141 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1142 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len))
1144 err = GetLastError();
1145 if (err == ERROR_NO_MORE_ITEMS)
1147 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1151 if (sizeof(TCHAR) != sizeof(char))
1154 name = OPENSSL_malloc(len);
1155 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len))
1157 err = GetLastError();
1158 if (err == ERROR_NO_MORE_ITEMS)
1160 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1164 if (sizeof(TCHAR) != sizeof(char))
1165 *pname = wide_to_asc((WCHAR *)name);
1167 *pname = (char *)name;
1168 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname, *ptype);
1173 static int capi_list_providers(CAPI_CTX *ctx, BIO *out)
1177 LPSTR provname = NULL;
1178 CAPI_trace(ctx, "capi_list_providers\n");
1179 BIO_printf(out, "Available CSPs:\n");
1180 for(idx = 0; ; idx++)
1182 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1187 BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
1188 OPENSSL_free(provname);
1193 static int capi_list_containers(CAPI_CTX *ctx, BIO *out)
1197 DWORD err, idx, flags, buflen = 0, clen;
1199 LPTSTR cspname = NULL;
1201 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname, ctx->csptype);
1202 if (ctx->cspname && sizeof(TCHAR)!=sizeof(char))
1204 if ((clen=MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,NULL,0)))
1206 cspname = alloca(clen*sizeof(WCHAR));
1207 MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,(WCHAR *)cspname,clen);
1211 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1212 capi_addlasterror();
1217 cspname = (TCHAR *)ctx->cspname;
1218 if (!CryptAcquireContext(&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT))
1220 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1221 capi_addlasterror();
1224 if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST))
1226 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1227 capi_addlasterror();
1228 CryptReleaseContext(hprov, 0);
1231 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1234 cname = OPENSSL_malloc(buflen);
1237 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1241 for (idx = 0;;idx++)
1247 flags = CRYPT_FIRST;
1250 if(!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, (BYTE *)cname, &clen, flags))
1252 err = GetLastError();
1253 if (err == ERROR_NO_MORE_ITEMS)
1255 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1259 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n", cname, clen, idx, flags);
1260 if (!cname[0] && (clen == buflen))
1262 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1265 BIO_printf(out, "%d. %s\n", idx, cname);
1273 OPENSSL_free(cname);
1274 CryptReleaseContext(hprov, 0);
1279 CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1282 CRYPT_KEY_PROV_INFO *pinfo;
1284 if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1286 pinfo = OPENSSL_malloc(len);
1289 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1292 if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len))
1294 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1295 capi_addlasterror();
1296 OPENSSL_free(pinfo);
1302 static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out, CRYPT_KEY_PROV_INFO *pinfo)
1304 char *provname = NULL, *contname = NULL;
1307 BIO_printf(out, " No Private Key\n");
1310 provname = wide_to_asc(pinfo->pwszProvName);
1311 contname = wide_to_asc(pinfo->pwszContainerName);
1312 if (!provname || !contname)
1315 BIO_printf(out, " Private Key Info:\n");
1316 BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname, pinfo->dwProvType);
1317 BIO_printf(out, " Container Name: %s, Key Type %d\n", contname, pinfo->dwKeySpec);
1320 OPENSSL_free(provname);
1322 OPENSSL_free(contname);
1325 char * capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1330 CAPI_trace(ctx, "capi_cert_get_fname\n");
1331 if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1333 wfname = OPENSSL_malloc(dlen);
1334 if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen))
1336 char *fname = wide_to_asc(wfname);
1337 OPENSSL_free(wfname);
1340 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1341 capi_addlasterror();
1343 OPENSSL_free(wfname);
1348 void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert)
1352 unsigned long flags = ctx->dump_flags;
1353 if (flags & CAPI_DMP_FNAME)
1356 fname = capi_cert_get_fname(ctx, cert);
1359 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1360 OPENSSL_free(fname);
1363 BIO_printf(out, " <No Friendly Name>\n");
1366 p = cert->pbCertEncoded;
1367 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1369 BIO_printf(out, " <Can't parse certificate>\n");
1370 if (flags & CAPI_DMP_SUMMARY)
1372 BIO_printf(out, " Subject: ");
1373 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1374 BIO_printf(out, "\n Issuer: ");
1375 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1376 BIO_printf(out, "\n");
1378 if (flags & CAPI_DMP_FULL)
1379 X509_print_ex(out, x, XN_FLAG_ONELINE,0);
1381 if (flags & CAPI_DMP_PKEYINFO)
1383 CRYPT_KEY_PROV_INFO *pinfo;
1384 pinfo = capi_get_prov_info(ctx, cert);
1385 capi_dump_prov_info(ctx, out, pinfo);
1387 OPENSSL_free(pinfo);
1390 if (flags & CAPI_DMP_PEM)
1391 PEM_write_bio_X509(out, x);
1395 HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename)
1400 storename = ctx->storename;
1403 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1405 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1406 ctx->store_flags, storename);
1409 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1410 capi_addlasterror();
1415 int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id)
1421 PCCERT_CONTEXT cert = NULL;
1423 storename = ctx->storename;
1426 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1428 hstore = capi_open_store(ctx, storename);
1433 cert = capi_find_cert(ctx, id, hstore);
1439 capi_dump_cert(ctx, out, cert);
1440 CertFreeCertificateContext(cert);
1446 cert = CertEnumCertificatesInStore(hstore, cert);
1449 BIO_printf(out, "Certificate %d\n", idx);
1450 capi_dump_cert(ctx, out, cert);
1454 CertCloseStore(hstore, 0);
1458 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore)
1460 PCCERT_CONTEXT cert = NULL;
1463 switch(ctx->lookup_method)
1465 case CAPI_LU_SUBSTR:
1466 return CertFindCertificateInStore(hstore,
1467 X509_ASN_ENCODING, 0,
1468 CERT_FIND_SUBJECT_STR_A, id, NULL);
1472 cert = CertEnumCertificatesInStore(hstore, cert);
1475 fname = capi_cert_get_fname(ctx, cert);
1478 if (strcmp(fname, id))
1482 OPENSSL_free(fname);
1492 static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const TCHAR *contname, TCHAR *provname, DWORD ptype, DWORD keyspec)
1496 key = OPENSSL_malloc(sizeof(CAPI_KEY));
1497 if (sizeof(TCHAR)==sizeof(char))
1498 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1499 contname, provname, ptype);
1500 else if (ctx && ctx->debug_level>=CAPI_DBG_TRACE && ctx->debug_file)
1502 /* above 'if' is optimization to minimize malloc-ations */
1503 char *_contname = wide_to_asc((WCHAR *)contname);
1504 char *_provname = wide_to_asc((WCHAR *)provname);
1506 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1507 _contname, _provname, ptype);
1508 if (_provname) OPENSSL_free(_provname);
1509 if (_contname) OPENSSL_free(_contname);
1511 if(ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1512 dwFlags = CRYPT_MACHINE_KEYSET;
1513 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags))
1515 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1516 capi_addlasterror();
1519 if (!CryptGetUserKey(key->hprov, keyspec, &key->key))
1521 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1522 capi_addlasterror();
1523 CryptReleaseContext(key->hprov, 0);
1526 key->keyspec = keyspec;
1535 static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1537 CAPI_KEY *key = NULL;
1538 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1539 char *provname = NULL, *contname = NULL;
1540 pinfo = capi_get_prov_info(ctx, cert);
1543 if (sizeof(TCHAR) != sizeof(char))
1544 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1545 (TCHAR *)pinfo->pwszProvName,
1546 pinfo->dwProvType, pinfo->dwKeySpec);
1549 provname = wide_to_asc(pinfo->pwszProvName);
1550 contname = wide_to_asc(pinfo->pwszContainerName);
1551 if (!provname || !contname)
1553 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1554 pinfo->dwProvType, pinfo->dwKeySpec);
1559 OPENSSL_free(pinfo);
1561 OPENSSL_free(provname);
1563 OPENSSL_free(contname);
1567 CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id)
1569 PCCERT_CONTEXT cert;
1571 CAPI_KEY *key = NULL;
1572 switch (ctx->lookup_method)
1574 case CAPI_LU_SUBSTR:
1576 hstore = capi_open_store(ctx, NULL);
1579 cert = capi_find_cert(ctx, id, hstore);
1582 key = capi_get_cert_key(ctx, cert);
1583 CertFreeCertificateContext(cert);
1585 CertCloseStore(hstore, 0);
1588 case CAPI_LU_CONTNAME:
1589 if (sizeof(TCHAR)!=sizeof(char))
1591 WCHAR *contname, *provname;
1594 if ((len=MultiByteToWideChar(CP_ACP,0,id,-1,NULL,0)) &&
1595 (contname=alloca(len*sizeof(WCHAR)),
1596 MultiByteToWideChar(CP_ACP,0,id,-1,contname,len)) &&
1597 (len=MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,NULL,0)) &&
1598 (provname=alloca(len*sizeof(WCHAR)),
1599 MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,provname,len)))
1600 key = capi_get_key(ctx,(TCHAR *)contname,
1602 ctx->csptype,ctx->keytype);
1605 key = capi_get_key(ctx, (TCHAR *)id,
1606 (TCHAR *)ctx->cspname,
1607 ctx->csptype,ctx->keytype);
1614 void capi_free_key(CAPI_KEY *key)
1618 CryptDestroyKey(key->key);
1619 CryptReleaseContext(key->hprov, 0);
1621 CertFreeCertificateContext(key->pcert);
1626 /* Initialize a CAPI_CTX structure */
1628 static CAPI_CTX *capi_ctx_new()
1631 ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
1634 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1637 ctx->cspname = NULL;
1638 ctx->csptype = PROV_RSA_FULL;
1639 ctx->dump_flags = CAPI_DMP_SUMMARY|CAPI_DMP_FNAME;
1640 ctx->keytype = AT_KEYEXCHANGE;
1641 ctx->storename = NULL;
1642 ctx->ssl_client_store = NULL;
1643 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1644 CERT_STORE_READONLY_FLAG |
1645 CERT_SYSTEM_STORE_CURRENT_USER;
1646 ctx->lookup_method = CAPI_LU_SUBSTR;
1647 ctx->debug_level = 0;
1648 ctx->debug_file = NULL;
1649 ctx->client_cert_select = cert_select_simple;
1653 static void capi_ctx_free(CAPI_CTX *ctx)
1655 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1659 OPENSSL_free(ctx->cspname);
1660 if (ctx->debug_file)
1661 OPENSSL_free(ctx->debug_file);
1663 OPENSSL_free(ctx->storename);
1664 if (ctx->ssl_client_store)
1665 OPENSSL_free(ctx->ssl_client_store);
1669 static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check)
1671 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1677 if (sizeof(TCHAR)!=sizeof(char))
1680 if ((len=MultiByteToWideChar(CP_ACP,0,pname,-1,NULL,0)))
1682 name = alloca(len*sizeof(WCHAR));
1683 MultiByteToWideChar(CP_ACP,0,pname,-1,(WCHAR *)name,len);
1687 name = (TCHAR *)pname;
1689 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1690 CRYPT_VERIFYCONTEXT))
1692 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1693 capi_addlasterror();
1696 CryptReleaseContext(hprov, 0);
1699 OPENSSL_free(ctx->cspname);
1700 ctx->cspname = BUF_strdup(pname);
1701 ctx->csptype = type;
1705 static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx)
1710 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1712 res = capi_ctx_set_provname(ctx, pname, type, 0);
1713 OPENSSL_free(pname);
1717 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1721 /* Special case: empty list: match anything */
1722 if (sk_X509_NAME_num(ca_dn) <= 0)
1724 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++)
1726 nm = sk_X509_NAME_value(ca_dn, i);
1727 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1735 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1736 STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey,
1737 STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data)
1739 STACK_OF(X509) *certs = NULL;
1743 int i, client_cert_idx;
1745 PCCERT_CONTEXT cert = NULL, excert = NULL;
1748 ctx = ENGINE_get_ex_data(e, capi_idx);
1753 storename = ctx->ssl_client_store;
1757 hstore = capi_open_store(ctx, storename);
1760 /* Enumerate all certificates collect any matches */
1763 cert = CertEnumCertificatesInStore(hstore, cert);
1766 p = cert->pbCertEncoded;
1767 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1770 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1773 if (cert_issuer_match(ca_dn, x)
1774 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0))
1776 key = capi_get_cert_key(ctx, cert);
1782 /* Match found: attach extra data to it so
1783 * we can retrieve the key later.
1785 excert = CertDuplicateCertificateContext(cert);
1786 key->pcert = excert;
1787 X509_set_ex_data(x, cert_capi_idx, key);
1790 certs = sk_X509_new_null();
1792 sk_X509_push(certs, x);
1800 CertFreeCertificateContext(cert);
1802 CertCloseStore(hstore, 0);
1808 /* Select the appropriate certificate */
1810 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1812 /* Set the selected certificate and free the rest */
1814 for(i = 0; i < sk_X509_num(certs); i++)
1816 x = sk_X509_value(certs, i);
1817 if (i == client_cert_idx)
1821 key = X509_get_ex_data(x, cert_capi_idx);
1827 sk_X509_free(certs);
1832 /* Setup key for selected certificate */
1834 key = X509_get_ex_data(*pcert, cert_capi_idx);
1835 *pkey = capi_get_pkey(e, key);
1836 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1843 /* Simple client cert selection function: always select first */
1845 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1850 #ifdef OPENSSL_CAPIENG_DIALOG
1852 /* More complex cert selection function, using standard function
1853 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1856 /* Definitions which are in cryptuiapi.h but this is not present in older
1857 * versions of headers.
1860 #ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1861 #define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1862 #define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1865 #define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1866 #define dlg_prompt L"Select a certificate to use for authentication"
1867 #define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1868 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1870 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1874 PCCERT_CONTEXT cert;
1879 if (sk_X509_num(certs) == 1)
1881 ctx = ENGINE_get_ex_data(e, capi_idx);
1882 /* Create an in memory store of certificates */
1883 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1884 CERT_STORE_CREATE_NEW_FLAG, NULL);
1887 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1888 capi_addlasterror();
1891 /* Add all certificates to store */
1892 for(i = 0; i < sk_X509_num(certs); i++)
1894 x = sk_X509_value(certs, i);
1895 key = X509_get_ex_data(x, cert_capi_idx);
1897 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1898 CERT_STORE_ADD_NEW, NULL))
1900 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1901 capi_addlasterror();
1906 hwnd = GetForegroundWindow();
1908 hwnd = GetActiveWindow();
1909 if (!hwnd && ctx->getconswindow)
1910 hwnd = ctx->getconswindow();
1911 /* Call dialog to select one */
1912 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1913 dlg_columns, 0, NULL);
1915 /* Find matching cert from list */
1918 for(i = 0; i < sk_X509_num(certs); i++)
1920 x = sk_X509_value(certs, i);
1921 key = X509_get_ex_data(x, cert_capi_idx);
1922 if (CertCompareCertificate(
1923 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1925 key->pcert->pCertInfo))
1935 CertCloseStore(dstore, 0);
1941 #else /* !__COMPILE_CAPIENG */
1942 #include <openssl/engine.h>
1943 #ifndef OPENSSL_NO_DYNAMIC_ENGINE
1945 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1947 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { return 0; }
1948 IMPLEMENT_DYNAMIC_CHECK_FN()
1950 void ENGINE_load_capi(void){}