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>
67 #include <openssl/dsa.h>
70 #define _WIN32_WINNT 0x0400
77 # define alloca _alloca
81 * This module uses several "new" interfaces, among which is
82 * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is
83 * one of possible values you can pass to function in question. By
84 * checking if it's defined we can see if wincrypt.h and accompanying
85 * crypt32.lib are in shape. The native MingW32 headers up to and
86 * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the
87 * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG,
88 * so we check for these too and avoid compiling.
89 * Yes, it's rather "weak" test and if compilation fails,
90 * then re-configure with -DOPENSSL_NO_CAPIENG.
92 #if defined(CERT_KEY_PROV_INFO_PROP_ID) && \
93 defined(CERT_STORE_PROV_SYSTEM_A) && \
94 defined(CERT_STORE_READONLY_FLAG)
95 # define __COMPILE_CAPIENG
96 #endif /* CERT_KEY_PROV_INFO_PROP_ID */
97 #endif /* OPENSSL_NO_CAPIENG */
98 #endif /* OPENSSL_SYS_WIN32 */
100 #ifdef __COMPILE_CAPIENG
102 #undef X509_EXTENSIONS
103 #undef X509_CERT_PAIR
105 /* Definitions which may be missing from earlier version of headers */
106 #ifndef CERT_STORE_OPEN_EXISTING_FLAG
107 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
110 #ifndef CERT_STORE_CREATE_NEW_FLAG
111 #define CERT_STORE_CREATE_NEW_FLAG 0x00002000
114 #ifndef CERT_SYSTEM_STORE_CURRENT_USER
115 #define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000
118 #ifndef ALG_SID_SHA_256
119 #define ALG_SID_SHA_256 12
121 #ifndef ALG_SID_SHA_384
122 #define ALG_SID_SHA_384 13
124 #ifndef ALG_SID_SHA_512
125 #define ALG_SID_SHA_512 14
129 #define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
132 #define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
135 #define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
138 #include <openssl/engine.h>
139 #include <openssl/pem.h>
140 #include <openssl/x509v3.h>
142 #include "e_capi_err.h"
143 #include "e_capi_err.c"
146 static const char *engine_capi_id = "capi";
147 static const char *engine_capi_name = "CryptoAPI ENGINE";
149 typedef struct CAPI_CTX_st CAPI_CTX;
150 typedef struct CAPI_KEY_st CAPI_KEY;
152 static void capi_addlasterror(void);
153 static void capi_adderror(DWORD err);
155 static void CAPI_trace(CAPI_CTX *ctx, char *format, ...);
157 static int capi_list_providers(CAPI_CTX *ctx, BIO *out);
158 static int capi_list_containers(CAPI_CTX *ctx, BIO *out);
159 int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *storename);
160 void capi_free_key(CAPI_KEY *key);
162 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore);
164 CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id);
166 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
167 UI_METHOD *ui_method, void *callback_data);
168 static int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
169 unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
170 static int capi_rsa_priv_enc(int flen, const unsigned char *from,
171 unsigned char *to, RSA *rsa, int padding);
172 static int capi_rsa_priv_dec(int flen, const unsigned char *from,
173 unsigned char *to, RSA *rsa, int padding);
174 static int capi_rsa_free(RSA *rsa);
176 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
178 static int capi_dsa_free(DSA *dsa);
180 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
181 STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey,
182 STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data);
184 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
185 #ifdef OPENSSL_CAPIENG_DIALOG
186 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
189 typedef PCCERT_CONTEXT (WINAPI *CERTDLG)(HCERTSTORE, HWND, LPCWSTR,
190 LPCWSTR, DWORD, DWORD,
192 typedef HWND (WINAPI *GETCONSWIN)(void);
194 /* This structure contains CAPI ENGINE specific data:
195 * it contains various global options and affects how
196 * other functions behave.
199 #define CAPI_DBG_TRACE 2
200 #define CAPI_DBG_ERROR 1
205 /* Parameters to use for container lookup */
209 /* Certificate store name to use */
211 LPSTR ssl_client_store;
212 /* System store flags */
215 /* Lookup string meanings in load_private_key */
216 /* Substring of subject: uses "storename" */
217 #define CAPI_LU_SUBSTR 1
218 /* Friendly name: uses storename */
219 #define CAPI_LU_FNAME 2
220 /* Container name: uses cspname, keytype */
221 #define CAPI_LU_CONTNAME 3
223 /* Info to dump with dumpcerts option */
224 /* Issuer and serial name strings */
225 #define CAPI_DMP_SUMMARY 0x1
227 #define CAPI_DMP_FNAME 0x2
228 /* Full X509_print dump */
229 #define CAPI_DMP_FULL 0x4
230 /* Dump PEM format certificate */
231 #define CAPI_DMP_PEM 0x8
232 /* Dump pseudo key (if possible) */
233 #define CAPI_DMP_PSKEY 0x10
234 /* Dump key info (if possible) */
235 #define CAPI_DMP_PKEYINFO 0x20
238 int (*client_cert_select)(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
240 CERTDLG certselectdlg;
241 GETCONSWIN getconswindow;
245 static CAPI_CTX *capi_ctx_new();
246 static void capi_ctx_free(CAPI_CTX *ctx);
247 static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check);
248 static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx);
250 #define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
251 #define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
252 #define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
253 #define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
254 #define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
255 #define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
256 #define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
257 #define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
258 #define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
259 #define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
260 #define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
261 #define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
262 #define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
263 #define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
265 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
266 {CAPI_CMD_LIST_CERTS,
268 "List all certificates in store",
269 ENGINE_CMD_FLAG_NO_INPUT},
270 {CAPI_CMD_LOOKUP_CERT,
272 "Lookup and output certificates",
273 ENGINE_CMD_FLAG_STRING},
274 {CAPI_CMD_DEBUG_LEVEL,
276 "debug level (1=errors, 2=trace)",
277 ENGINE_CMD_FLAG_NUMERIC},
278 {CAPI_CMD_DEBUG_FILE,
280 "debugging filename)",
281 ENGINE_CMD_FLAG_STRING},
284 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
285 ENGINE_CMD_FLAG_NUMERIC},
289 ENGINE_CMD_FLAG_NO_INPUT},
290 {CAPI_CMD_SET_CSP_IDX,
293 ENGINE_CMD_FLAG_NUMERIC},
294 {CAPI_CMD_SET_CSP_NAME,
296 "Set CSP name, (default CSP used if not specified)",
297 ENGINE_CMD_FLAG_STRING},
298 {CAPI_CMD_SET_CSP_TYPE,
300 "Set CSP type, (default RSA_PROV_FULL)",
301 ENGINE_CMD_FLAG_NUMERIC},
302 {CAPI_CMD_LIST_CONTAINERS,
304 "list container names",
305 ENGINE_CMD_FLAG_NO_INPUT},
306 {CAPI_CMD_LIST_OPTIONS,
308 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
309 "32=private key info)",
310 ENGINE_CMD_FLAG_NUMERIC},
311 {CAPI_CMD_LOOKUP_METHOD,
313 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
314 ENGINE_CMD_FLAG_NUMERIC},
315 {CAPI_CMD_STORE_NAME,
317 "certificate store name, default \"MY\"",
318 ENGINE_CMD_FLAG_STRING},
319 {CAPI_CMD_STORE_FLAGS,
321 "Certificate store flags: 1 = system store",
322 ENGINE_CMD_FLAG_NUMERIC},
327 static int capi_idx = -1;
328 static int rsa_capi_idx = -1;
329 static int dsa_capi_idx = -1;
330 static int cert_capi_idx = -1;
332 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
339 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
342 ctx = ENGINE_get_ex_data(e, capi_idx);
343 out = BIO_new_fp(stdout, BIO_NOCLOSE);
346 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_FILE_OPEN_ERROR);
351 case CAPI_CMD_LIST_CSPS:
352 ret = capi_list_providers(ctx, out);
355 case CAPI_CMD_LIST_CERTS:
356 ret = capi_list_certs(ctx, out, NULL);
359 case CAPI_CMD_LOOKUP_CERT:
360 ret = capi_list_certs(ctx, out, p);
363 case CAPI_CMD_LIST_CONTAINERS:
364 ret = capi_list_containers(ctx, out);
367 case CAPI_CMD_STORE_NAME:
369 OPENSSL_free(ctx->storename);
370 ctx->storename = BUF_strdup(p);
371 CAPI_trace(ctx, "Setting store name to %s\n", p);
374 case CAPI_CMD_STORE_FLAGS:
377 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
378 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
382 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
383 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
385 CAPI_trace(ctx, "Setting flags to %d\n", i);
388 case CAPI_CMD_DEBUG_LEVEL:
389 ctx->debug_level = (int)i;
390 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
393 case CAPI_CMD_DEBUG_FILE:
394 ctx->debug_file = BUF_strdup(p);
395 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
398 case CAPI_CMD_KEYTYPE:
400 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
403 case CAPI_CMD_SET_CSP_IDX:
404 ret = capi_ctx_set_provname_idx(ctx, i);
407 case CAPI_CMD_LIST_OPTIONS:
411 case CAPI_CMD_LOOKUP_METHOD:
414 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
418 ctx->lookup_method = i;
421 case CAPI_CMD_SET_CSP_NAME:
422 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
425 case CAPI_CMD_SET_CSP_TYPE:
430 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
439 static RSA_METHOD capi_rsa_method =
441 "CryptoAPI RSA method",
444 capi_rsa_priv_enc, /* priv_enc */
445 capi_rsa_priv_dec, /* priv_dec */
449 capi_rsa_free, /* finish */
450 RSA_FLAG_SIGN_VER, /* flags */
452 capi_rsa_sign, /* rsa_sign */
456 static DSA_METHOD capi_dsa_method =
458 "CryptoAPI DSA method",
459 capi_dsa_do_sign, /* dsa_do_sign */
460 0, /* dsa_sign_setup */
461 0, /* dsa_do_verify */
465 capi_dsa_free, /* finish */
468 0, /* dsa_paramgen */
472 static int capi_init(ENGINE *e)
475 const RSA_METHOD *ossl_rsa_meth;
476 const DSA_METHOD *ossl_dsa_meth;
480 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
484 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
486 /* Setup RSA_METHOD */
487 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
488 ossl_rsa_meth = RSA_PKCS1_SSLeay();
489 capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc;
490 capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec;
491 capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp;
492 capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp;
494 /* Setup DSA Method */
495 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
496 ossl_dsa_meth = DSA_OpenSSL();
497 capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify;
498 capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp;
499 capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp;
502 ctx = capi_ctx_new();
506 ENGINE_set_ex_data(e, capi_idx, ctx);
508 #ifdef OPENSSL_CAPIENG_DIALOG
510 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
511 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
513 ctx->certselectdlg = (CERTDLG)GetProcAddress(cryptui, "CryptUIDlgSelectCertificateFromStore");
515 ctx->getconswindow = (GETCONSWIN)GetProcAddress(kernel, "GetConsoleWindow");
516 if (cryptui && !OPENSSL_isservice())
517 ctx->client_cert_select = cert_select_dialog;
525 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
531 static int capi_destroy(ENGINE *e)
533 ERR_unload_CAPI_strings();
537 static int capi_finish(ENGINE *e)
540 ctx = ENGINE_get_ex_data(e, capi_idx);
542 ENGINE_set_ex_data(e, capi_idx, NULL);
547 /* CryptoAPI key application data. This contains
548 * a handle to the private key container (for sign operations)
549 * and a handle to the key (for decrypt operations).
554 /* Associated certificate context (if any) */
555 PCCERT_CONTEXT pcert;
561 static int bind_capi(ENGINE *e)
563 if (!ENGINE_set_id(e, engine_capi_id)
564 || !ENGINE_set_name(e, engine_capi_name)
565 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
566 || !ENGINE_set_init_function(e, capi_init)
567 || !ENGINE_set_finish_function(e, capi_finish)
568 || !ENGINE_set_destroy_function(e, capi_destroy)
569 || !ENGINE_set_RSA(e, &capi_rsa_method)
570 || !ENGINE_set_DSA(e, &capi_dsa_method)
571 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
572 || !ENGINE_set_load_ssl_client_cert_function(e,
573 capi_load_ssl_client_cert)
574 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
575 || !ENGINE_set_ctrl_function(e, capi_ctrl))
577 ERR_load_CAPI_strings();
583 #ifndef OPENSSL_NO_DYNAMIC_ENGINE
584 static int bind_helper(ENGINE *e, const char *id)
586 if(id && (strcmp(id, engine_capi_id) != 0))
592 IMPLEMENT_DYNAMIC_CHECK_FN()
593 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
595 static ENGINE *engine_capi(void)
597 ENGINE *ret = ENGINE_new();
608 void ENGINE_load_capi(void)
610 /* Copied from eng_[openssl|dyn].c */
611 ENGINE *toadd = engine_capi();
620 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
623 /* Reverse buffer in place: since this is a keyblob structure
624 * that will be freed up after conversion anyway it doesn't
625 * matter if we change it.
627 for(i = 0; i < binlen / 2; i++)
631 bin[i] = bin[binlen - i - 1];
632 bin[binlen - i - 1] = c;
635 if (!BN_bin2bn(bin, binlen, bn))
640 /* Given a CAPI_KEY get an EVP_PKEY structure */
642 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY *key)
644 unsigned char *pubkey = NULL;
649 EVP_PKEY *ret = NULL;
650 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len))
652 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
657 pubkey = OPENSSL_malloc(len);
662 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len))
664 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
669 bh = (BLOBHEADER *)pubkey;
670 if (bh->bType != PUBLICKEYBLOB)
672 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
675 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX)
679 unsigned char *rsa_modulus;
680 rp = (RSAPUBKEY *)(bh + 1);
681 if (rp->magic != 0x31415352)
684 BIO_snprintf(magstr, 10, "%lx", rp->magic);
685 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
686 ERR_add_error_data(2, "magic=0x", magstr);
689 rsa_modulus = (unsigned char *)(rp + 1);
690 rkey = RSA_new_method(eng);
697 if (!rkey->e || !rkey->n)
700 if (!BN_set_word(rkey->e, rp->pubexp))
703 rsa_modlen = rp->bitlen / 8;
704 if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
707 RSA_set_ex_data(rkey, rsa_capi_idx, key);
709 if (!(ret = EVP_PKEY_new()))
712 EVP_PKEY_assign_RSA(ret, rkey);
716 else if (bh->aiKeyAlg == CALG_DSS_SIGN)
721 dp = (DSSPUBKEY *)(bh + 1);
722 if (dp->magic != 0x31535344)
725 BIO_snprintf(magstr, 10, "%lx", dp->magic);
726 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
727 ERR_add_error_data(2, "magic=0x", magstr);
730 dsa_plen = dp->bitlen / 8;
731 btmp = (unsigned char *)(dp + 1);
732 dkey = DSA_new_method(eng);
738 dkey->pub_key = BN_new();
739 if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key)
741 if (!lend_tobn(dkey->p, btmp, dsa_plen))
744 if (!lend_tobn(dkey->q, btmp, 20))
747 if (!lend_tobn(dkey->g, btmp, dsa_plen))
750 if (!lend_tobn(dkey->pub_key, btmp, dsa_plen))
754 DSA_set_ex_data(dkey, dsa_capi_idx, key);
756 if (!(ret = EVP_PKEY_new()))
759 EVP_PKEY_assign_DSA(ret, dkey);
765 BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg);
766 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
767 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
774 OPENSSL_free(pubkey);
786 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
791 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
792 UI_METHOD *ui_method, void *callback_data)
797 ctx = ENGINE_get_ex_data(eng, capi_idx);
801 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
805 key = capi_find_key(ctx, key_id);
810 ret = capi_get_pkey(eng, key);
818 /* CryptoAPI RSA operations */
820 int capi_rsa_priv_enc(int flen, const unsigned char *from,
821 unsigned char *to, RSA *rsa, int padding)
823 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
827 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
828 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
838 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
840 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
842 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
845 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
848 /* Convert the signature type to a CryptoAPI algorithm ID */
872 alg = CALG_SSL3_SHAMD5;
877 BIO_snprintf(algstr, 10, "%lx", dtype);
878 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
879 ERR_add_error_data(2, "NID=0x", algstr);
886 /* Create the hash object */
887 if(!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash))
889 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
893 /* Set the hash value to the value passed */
895 if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0))
897 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
903 /* Finally sign it */
904 slen = RSA_size(rsa);
905 if(!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen))
907 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
914 /* Inplace byte reversal of signature */
915 for(i = 0; i < slen / 2; i++)
919 sigret[i] = sigret[slen - i - 1];
920 sigret[slen - i - 1] = c;
928 CryptDestroyHash(hash);
933 int capi_rsa_priv_dec(int flen, const unsigned char *from,
934 unsigned char *to, RSA *rsa, int padding)
937 unsigned char *tmpbuf;
940 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
942 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
945 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
948 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
952 if(padding != RSA_PKCS1_PADDING)
955 BIO_snprintf(errstr, 10, "%d", padding);
956 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
957 ERR_add_error_data(2, "padding=", errstr);
961 /* Create temp reverse order version of input */
962 if(!(tmpbuf = OPENSSL_malloc(flen)) )
964 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
967 for(i = 0; i < flen; i++)
968 tmpbuf[flen - i - 1] = from[i];
970 /* Finally decrypt it */
971 if(!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen))
973 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
975 OPENSSL_free(tmpbuf);
978 else memcpy(to, tmpbuf, flen);
980 OPENSSL_free(tmpbuf);
985 static int capi_rsa_free(RSA *rsa)
988 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
989 capi_free_key(capi_key);
990 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
994 /* CryptoAPI DSA operations */
996 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
1001 DSA_SIG *ret = NULL;
1004 unsigned char csigbuf[40];
1006 ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
1008 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
1010 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1014 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
1020 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
1024 /* Create the hash object */
1025 if(!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash))
1027 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
1028 capi_addlasterror();
1032 /* Set the hash value to the value passed */
1033 if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0))
1035 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
1036 capi_addlasterror();
1041 /* Finally sign it */
1042 slen = sizeof(csigbuf);
1043 if(!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen))
1045 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1046 capi_addlasterror();
1051 ret = DSA_SIG_new();
1056 if (!ret->r || !ret->s)
1058 if (!lend_tobn(ret->r, csigbuf, 20)
1059 || !lend_tobn(ret->s, csigbuf + 20, 20))
1070 OPENSSL_cleanse(csigbuf, 40);
1071 CryptDestroyHash(hash);
1075 static int capi_dsa_free(DSA *dsa)
1078 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1079 capi_free_key(capi_key);
1080 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1084 static void capi_vtrace(CAPI_CTX *ctx, int level, char *format, va_list argptr)
1088 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1090 out = BIO_new_file(ctx->debug_file, "a+");
1093 CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
1096 BIO_vprintf(out, format, argptr);
1100 static void CAPI_trace(CAPI_CTX *ctx, char *format, ...)
1103 va_start(args, format);
1104 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1108 static void capi_addlasterror(void)
1110 capi_adderror(GetLastError());
1113 static void capi_adderror(DWORD err)
1116 BIO_snprintf(errstr, 10, "%lX", err);
1117 ERR_add_error_data(2, "Error code= 0x", errstr);
1120 static char *wide_to_asc(LPCWSTR wstr)
1127 len_0 = (int)wcslen(wstr)+1; /* WideCharToMultiByte expects int */
1128 sz = WideCharToMultiByte(CP_ACP,0,wstr,len_0,NULL,0,NULL,NULL);
1131 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1134 str = OPENSSL_malloc(sz);
1137 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1140 if (!WideCharToMultiByte(CP_ACP,0,wstr,len_0,str,sz,NULL,NULL))
1143 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1149 static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype, DWORD idx)
1153 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1154 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len))
1156 err = GetLastError();
1157 if (err == ERROR_NO_MORE_ITEMS)
1159 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1163 name = OPENSSL_malloc(len);
1166 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1169 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len))
1171 err = GetLastError();
1173 if (err == ERROR_NO_MORE_ITEMS)
1175 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1179 if (sizeof(TCHAR) != sizeof(char))
1181 *pname = wide_to_asc((WCHAR *)name);
1187 *pname = (char *)name;
1188 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname, *ptype);
1193 static int capi_list_providers(CAPI_CTX *ctx, BIO *out)
1197 LPSTR provname = NULL;
1198 CAPI_trace(ctx, "capi_list_providers\n");
1199 BIO_printf(out, "Available CSPs:\n");
1200 for(idx = 0; ; idx++)
1202 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1207 BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
1208 OPENSSL_free(provname);
1213 static int capi_list_containers(CAPI_CTX *ctx, BIO *out)
1217 DWORD err, idx, flags, buflen = 0, clen;
1219 LPTSTR cspname = NULL;
1221 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname, ctx->csptype);
1222 if (ctx->cspname && sizeof(TCHAR)!=sizeof(char))
1224 if ((clen=MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,NULL,0)))
1226 cspname = alloca(clen*sizeof(WCHAR));
1227 MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,(WCHAR *)cspname,clen);
1231 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1232 capi_addlasterror();
1237 cspname = (TCHAR *)ctx->cspname;
1238 if (!CryptAcquireContext(&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT))
1240 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1241 capi_addlasterror();
1244 if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST))
1246 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1247 capi_addlasterror();
1248 CryptReleaseContext(hprov, 0);
1251 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1254 cname = OPENSSL_malloc(buflen);
1257 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1261 for (idx = 0;;idx++)
1267 flags = CRYPT_FIRST;
1270 if(!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, (BYTE *)cname, &clen, flags))
1272 err = GetLastError();
1273 if (err == ERROR_NO_MORE_ITEMS)
1275 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1279 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n", cname, clen, idx, flags);
1280 if (!cname[0] && (clen == buflen))
1282 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1285 BIO_printf(out, "%d. %s\n", idx, cname);
1293 OPENSSL_free(cname);
1294 CryptReleaseContext(hprov, 0);
1299 CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1302 CRYPT_KEY_PROV_INFO *pinfo;
1304 if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1306 pinfo = OPENSSL_malloc(len);
1309 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1312 if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len))
1314 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1315 capi_addlasterror();
1316 OPENSSL_free(pinfo);
1322 static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out, CRYPT_KEY_PROV_INFO *pinfo)
1324 char *provname = NULL, *contname = NULL;
1327 BIO_printf(out, " No Private Key\n");
1330 provname = wide_to_asc(pinfo->pwszProvName);
1331 contname = wide_to_asc(pinfo->pwszContainerName);
1332 if (!provname || !contname)
1335 BIO_printf(out, " Private Key Info:\n");
1336 BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname, pinfo->dwProvType);
1337 BIO_printf(out, " Container Name: %s, Key Type %d\n", contname, pinfo->dwKeySpec);
1340 OPENSSL_free(provname);
1342 OPENSSL_free(contname);
1345 char * capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1350 CAPI_trace(ctx, "capi_cert_get_fname\n");
1351 if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1353 wfname = OPENSSL_malloc(dlen);
1356 if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen))
1358 char *fname = wide_to_asc(wfname);
1359 OPENSSL_free(wfname);
1362 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1363 capi_addlasterror();
1365 OPENSSL_free(wfname);
1370 void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert)
1374 unsigned long flags = ctx->dump_flags;
1375 if (flags & CAPI_DMP_FNAME)
1378 fname = capi_cert_get_fname(ctx, cert);
1381 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1382 OPENSSL_free(fname);
1385 BIO_printf(out, " <No Friendly Name>\n");
1388 p = cert->pbCertEncoded;
1389 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1391 BIO_printf(out, " <Can't parse certificate>\n");
1392 if (flags & CAPI_DMP_SUMMARY)
1394 BIO_printf(out, " Subject: ");
1395 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1396 BIO_printf(out, "\n Issuer: ");
1397 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1398 BIO_printf(out, "\n");
1400 if (flags & CAPI_DMP_FULL)
1401 X509_print_ex(out, x, XN_FLAG_ONELINE,0);
1403 if (flags & CAPI_DMP_PKEYINFO)
1405 CRYPT_KEY_PROV_INFO *pinfo;
1406 pinfo = capi_get_prov_info(ctx, cert);
1407 capi_dump_prov_info(ctx, out, pinfo);
1409 OPENSSL_free(pinfo);
1412 if (flags & CAPI_DMP_PEM)
1413 PEM_write_bio_X509(out, x);
1417 HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename)
1422 storename = ctx->storename;
1425 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1427 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1428 ctx->store_flags, storename);
1431 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1432 capi_addlasterror();
1437 int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id)
1443 PCCERT_CONTEXT cert = NULL;
1445 storename = ctx->storename;
1448 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1450 hstore = capi_open_store(ctx, storename);
1455 cert = capi_find_cert(ctx, id, hstore);
1461 capi_dump_cert(ctx, out, cert);
1462 CertFreeCertificateContext(cert);
1468 cert = CertEnumCertificatesInStore(hstore, cert);
1471 BIO_printf(out, "Certificate %d\n", idx);
1472 capi_dump_cert(ctx, out, cert);
1476 CertCloseStore(hstore, 0);
1480 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore)
1482 PCCERT_CONTEXT cert = NULL;
1485 switch(ctx->lookup_method)
1487 case CAPI_LU_SUBSTR:
1488 return CertFindCertificateInStore(hstore,
1489 X509_ASN_ENCODING, 0,
1490 CERT_FIND_SUBJECT_STR_A, id, NULL);
1494 cert = CertEnumCertificatesInStore(hstore, cert);
1497 fname = capi_cert_get_fname(ctx, cert);
1500 if (strcmp(fname, id))
1504 OPENSSL_free(fname);
1514 static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const TCHAR *contname, TCHAR *provname, DWORD ptype, DWORD keyspec)
1518 key = OPENSSL_malloc(sizeof(CAPI_KEY));
1521 if (sizeof(TCHAR)==sizeof(char))
1522 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1523 contname, provname, ptype);
1524 else if (ctx && ctx->debug_level>=CAPI_DBG_TRACE && ctx->debug_file)
1526 /* above 'if' is optimization to minimize malloc-ations */
1527 char *_contname = wide_to_asc((WCHAR *)contname);
1528 char *_provname = wide_to_asc((WCHAR *)provname);
1530 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1531 _contname, _provname, ptype);
1532 if (_provname) OPENSSL_free(_provname);
1533 if (_contname) OPENSSL_free(_contname);
1535 if(ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1536 dwFlags = CRYPT_MACHINE_KEYSET;
1537 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags))
1539 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1540 capi_addlasterror();
1543 if (!CryptGetUserKey(key->hprov, keyspec, &key->key))
1545 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1546 capi_addlasterror();
1547 CryptReleaseContext(key->hprov, 0);
1550 key->keyspec = keyspec;
1559 static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1561 CAPI_KEY *key = NULL;
1562 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1563 char *provname = NULL, *contname = NULL;
1564 pinfo = capi_get_prov_info(ctx, cert);
1567 if (sizeof(TCHAR) != sizeof(char))
1568 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1569 (TCHAR *)pinfo->pwszProvName,
1570 pinfo->dwProvType, pinfo->dwKeySpec);
1573 provname = wide_to_asc(pinfo->pwszProvName);
1574 contname = wide_to_asc(pinfo->pwszContainerName);
1575 if (!provname || !contname)
1577 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1578 pinfo->dwProvType, pinfo->dwKeySpec);
1583 OPENSSL_free(pinfo);
1585 OPENSSL_free(provname);
1587 OPENSSL_free(contname);
1591 CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id)
1593 PCCERT_CONTEXT cert;
1595 CAPI_KEY *key = NULL;
1596 switch (ctx->lookup_method)
1598 case CAPI_LU_SUBSTR:
1600 hstore = capi_open_store(ctx, NULL);
1603 cert = capi_find_cert(ctx, id, hstore);
1606 key = capi_get_cert_key(ctx, cert);
1607 CertFreeCertificateContext(cert);
1609 CertCloseStore(hstore, 0);
1612 case CAPI_LU_CONTNAME:
1613 if (sizeof(TCHAR)!=sizeof(char))
1615 WCHAR *contname, *provname;
1618 if ((len=MultiByteToWideChar(CP_ACP,0,id,-1,NULL,0)) &&
1619 (contname=alloca(len*sizeof(WCHAR)),
1620 MultiByteToWideChar(CP_ACP,0,id,-1,contname,len)) &&
1621 (len=MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,NULL,0)) &&
1622 (provname=alloca(len*sizeof(WCHAR)),
1623 MultiByteToWideChar(CP_ACP,0,ctx->cspname,-1,provname,len)))
1624 key = capi_get_key(ctx,(TCHAR *)contname,
1626 ctx->csptype,ctx->keytype);
1629 key = capi_get_key(ctx, (TCHAR *)id,
1630 (TCHAR *)ctx->cspname,
1631 ctx->csptype,ctx->keytype);
1638 void capi_free_key(CAPI_KEY *key)
1642 CryptDestroyKey(key->key);
1643 CryptReleaseContext(key->hprov, 0);
1645 CertFreeCertificateContext(key->pcert);
1650 /* Initialize a CAPI_CTX structure */
1652 static CAPI_CTX *capi_ctx_new()
1655 ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
1658 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1661 ctx->cspname = NULL;
1662 ctx->csptype = PROV_RSA_FULL;
1663 ctx->dump_flags = CAPI_DMP_SUMMARY|CAPI_DMP_FNAME;
1664 ctx->keytype = AT_KEYEXCHANGE;
1665 ctx->storename = NULL;
1666 ctx->ssl_client_store = NULL;
1667 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1668 CERT_STORE_READONLY_FLAG |
1669 CERT_SYSTEM_STORE_CURRENT_USER;
1670 ctx->lookup_method = CAPI_LU_SUBSTR;
1671 ctx->debug_level = 0;
1672 ctx->debug_file = NULL;
1673 ctx->client_cert_select = cert_select_simple;
1677 static void capi_ctx_free(CAPI_CTX *ctx)
1679 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1683 OPENSSL_free(ctx->cspname);
1684 if (ctx->debug_file)
1685 OPENSSL_free(ctx->debug_file);
1687 OPENSSL_free(ctx->storename);
1688 if (ctx->ssl_client_store)
1689 OPENSSL_free(ctx->ssl_client_store);
1693 static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check)
1695 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1701 if (sizeof(TCHAR)!=sizeof(char))
1704 if ((len=MultiByteToWideChar(CP_ACP,0,pname,-1,NULL,0)))
1706 name = alloca(len*sizeof(WCHAR));
1707 MultiByteToWideChar(CP_ACP,0,pname,-1,(WCHAR *)name,len);
1711 name = (TCHAR *)pname;
1713 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1714 CRYPT_VERIFYCONTEXT))
1716 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1717 capi_addlasterror();
1720 CryptReleaseContext(hprov, 0);
1723 OPENSSL_free(ctx->cspname);
1724 ctx->cspname = BUF_strdup(pname);
1725 ctx->csptype = type;
1729 static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx)
1734 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1736 res = capi_ctx_set_provname(ctx, pname, type, 0);
1737 OPENSSL_free(pname);
1741 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1745 /* Special case: empty list: match anything */
1746 if (sk_X509_NAME_num(ca_dn) <= 0)
1748 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++)
1750 nm = sk_X509_NAME_value(ca_dn, i);
1751 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1759 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1760 STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey,
1761 STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data)
1763 STACK_OF(X509) *certs = NULL;
1767 int i, client_cert_idx;
1769 PCCERT_CONTEXT cert = NULL, excert = NULL;
1772 ctx = ENGINE_get_ex_data(e, capi_idx);
1777 storename = ctx->ssl_client_store;
1781 hstore = capi_open_store(ctx, storename);
1784 /* Enumerate all certificates collect any matches */
1787 cert = CertEnumCertificatesInStore(hstore, cert);
1790 p = cert->pbCertEncoded;
1791 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1794 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1797 if (cert_issuer_match(ca_dn, x)
1798 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0))
1800 key = capi_get_cert_key(ctx, cert);
1806 /* Match found: attach extra data to it so
1807 * we can retrieve the key later.
1809 excert = CertDuplicateCertificateContext(cert);
1810 key->pcert = excert;
1811 X509_set_ex_data(x, cert_capi_idx, key);
1814 certs = sk_X509_new_null();
1816 sk_X509_push(certs, x);
1824 CertFreeCertificateContext(cert);
1826 CertCloseStore(hstore, 0);
1832 /* Select the appropriate certificate */
1834 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1836 /* Set the selected certificate and free the rest */
1838 for(i = 0; i < sk_X509_num(certs); i++)
1840 x = sk_X509_value(certs, i);
1841 if (i == client_cert_idx)
1845 key = X509_get_ex_data(x, cert_capi_idx);
1851 sk_X509_free(certs);
1856 /* Setup key for selected certificate */
1858 key = X509_get_ex_data(*pcert, cert_capi_idx);
1859 *pkey = capi_get_pkey(e, key);
1860 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1867 /* Simple client cert selection function: always select first */
1869 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1874 #ifdef OPENSSL_CAPIENG_DIALOG
1876 /* More complex cert selection function, using standard function
1877 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1880 /* Definitions which are in cryptuiapi.h but this is not present in older
1881 * versions of headers.
1884 #ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1885 #define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1886 #define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1889 #define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1890 #define dlg_prompt L"Select a certificate to use for authentication"
1891 #define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1892 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1894 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1898 PCCERT_CONTEXT cert;
1903 if (sk_X509_num(certs) == 1)
1905 ctx = ENGINE_get_ex_data(e, capi_idx);
1906 /* Create an in memory store of certificates */
1907 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1908 CERT_STORE_CREATE_NEW_FLAG, NULL);
1911 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1912 capi_addlasterror();
1915 /* Add all certificates to store */
1916 for(i = 0; i < sk_X509_num(certs); i++)
1918 x = sk_X509_value(certs, i);
1919 key = X509_get_ex_data(x, cert_capi_idx);
1921 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1922 CERT_STORE_ADD_NEW, NULL))
1924 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1925 capi_addlasterror();
1930 hwnd = GetForegroundWindow();
1932 hwnd = GetActiveWindow();
1933 if (!hwnd && ctx->getconswindow)
1934 hwnd = ctx->getconswindow();
1935 /* Call dialog to select one */
1936 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1937 dlg_columns, 0, NULL);
1939 /* Find matching cert from list */
1942 for(i = 0; i < sk_X509_num(certs); i++)
1944 x = sk_X509_value(certs, i);
1945 key = X509_get_ex_data(x, cert_capi_idx);
1946 if (CertCompareCertificate(
1947 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1949 key->pcert->pCertInfo))
1959 CertCloseStore(dstore, 0);
1965 #else /* !__COMPILE_CAPIENG */
1966 #include <openssl/engine.h>
1967 #ifndef OPENSSL_NO_DYNAMIC_ENGINE
1969 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1971 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { return 0; }
1972 IMPLEMENT_DYNAMIC_CHECK_FN()
1974 void ENGINE_load_capi(void){}