2 * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
12 # define _WIN32_WINNT 0x0400
15 # include <wincrypt.h>
22 # define alloca _alloca
25 # include <openssl/crypto.h>
27 # ifndef OPENSSL_NO_CAPIENG
29 # include <openssl/buffer.h>
30 # include <openssl/bn.h>
31 # include <openssl/rsa.h>
32 # include <openssl/dsa.h>
35 * This module uses several "new" interfaces, among which is
36 * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is
37 * one of possible values you can pass to function in question. By
38 * checking if it's defined we can see if wincrypt.h and accompanying
39 * crypt32.lib are in shape. The native MingW32 headers up to and
40 * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the
41 * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG,
42 * so we check for these too and avoid compiling.
43 * Yes, it's rather "weak" test and if compilation fails,
44 * then re-configure with -DOPENSSL_NO_CAPIENG.
46 # if defined(CERT_KEY_PROV_INFO_PROP_ID) && \
47 defined(CERT_STORE_PROV_SYSTEM_A) && \
48 defined(CERT_STORE_READONLY_FLAG)
49 # define __COMPILE_CAPIENG
50 # endif /* CERT_KEY_PROV_INFO_PROP_ID */
51 # endif /* OPENSSL_NO_CAPIENG */
54 #ifdef __COMPILE_CAPIENG
56 # undef X509_EXTENSIONS
58 /* Definitions which may be missing from earlier version of headers */
59 # ifndef CERT_STORE_OPEN_EXISTING_FLAG
60 # define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
63 # ifndef CERT_STORE_CREATE_NEW_FLAG
64 # define CERT_STORE_CREATE_NEW_FLAG 0x00002000
67 # ifndef CERT_SYSTEM_STORE_CURRENT_USER
68 # define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000
71 # ifndef ALG_SID_SHA_256
72 # define ALG_SID_SHA_256 12
74 # ifndef ALG_SID_SHA_384
75 # define ALG_SID_SHA_384 13
77 # ifndef ALG_SID_SHA_512
78 # define ALG_SID_SHA_512 14
82 # define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
85 # define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
88 # define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
92 # define PROV_RSA_AES 24
95 # include <openssl/engine.h>
96 # include <openssl/pem.h>
97 # include <openssl/x509v3.h>
99 # include "e_capi_err.h"
100 # include "e_capi_err.c"
102 static const char *engine_capi_id = "capi";
103 static const char *engine_capi_name = "CryptoAPI ENGINE";
105 typedef struct CAPI_CTX_st CAPI_CTX;
106 typedef struct CAPI_KEY_st CAPI_KEY;
108 static void capi_addlasterror(void);
109 static void capi_adderror(DWORD err);
111 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...);
113 static int capi_list_providers(CAPI_CTX * ctx, BIO *out);
114 static int capi_list_containers(CAPI_CTX * ctx, BIO *out);
115 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *storename);
116 void capi_free_key(CAPI_KEY * key);
118 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
121 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id);
123 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
124 UI_METHOD *ui_method, void *callback_data);
125 static int capi_rsa_sign(int dtype, const unsigned char *m,
126 unsigned int m_len, unsigned char *sigret,
127 unsigned int *siglen, const RSA *rsa);
128 static int capi_rsa_priv_enc(int flen, const unsigned char *from,
129 unsigned char *to, RSA *rsa, int padding);
130 static int capi_rsa_priv_dec(int flen, const unsigned char *from,
131 unsigned char *to, RSA *rsa, int padding);
132 static int capi_rsa_free(RSA *rsa);
134 # ifndef OPENSSL_NO_DSA
135 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
137 static int capi_dsa_free(DSA *dsa);
140 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
141 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
142 EVP_PKEY **pkey, STACK_OF(X509) **pother,
143 UI_METHOD *ui_method,
144 void *callback_data);
146 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
147 # ifdef OPENSSL_CAPIENG_DIALOG
148 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
151 void engine_load_capi_int(void);
153 typedef PCCERT_CONTEXT(WINAPI *CERTDLG) (HCERTSTORE, HWND, LPCWSTR,
154 LPCWSTR, DWORD, DWORD, void *);
155 typedef HWND(WINAPI *GETCONSWIN) (void);
158 * This structure contains CAPI ENGINE specific data: it contains various
159 * global options and affects how other functions behave.
162 # define CAPI_DBG_TRACE 2
163 # define CAPI_DBG_ERROR 1
168 /* Parameters to use for container lookup */
172 /* Certificate store name to use */
174 LPSTR ssl_client_store;
175 /* System store flags */
177 /* Lookup string meanings in load_private_key */
178 /* Substring of subject: uses "storename" */
179 # define CAPI_LU_SUBSTR 1
180 /* Friendly name: uses storename */
181 # define CAPI_LU_FNAME 2
182 /* Container name: uses cspname, keytype */
183 # define CAPI_LU_CONTNAME 3
185 /* Info to dump with dumpcerts option */
186 /* Issuer and serial name strings */
187 # define CAPI_DMP_SUMMARY 0x1
189 # define CAPI_DMP_FNAME 0x2
190 /* Full X509_print dump */
191 # define CAPI_DMP_FULL 0x4
192 /* Dump PEM format certificate */
193 # define CAPI_DMP_PEM 0x8
194 /* Dump pseudo key (if possible) */
195 # define CAPI_DMP_PSKEY 0x10
196 /* Dump key info (if possible) */
197 # define CAPI_DMP_PKEYINFO 0x20
199 int (*client_cert_select) (ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
200 CERTDLG certselectdlg;
201 GETCONSWIN getconswindow;
204 static CAPI_CTX *capi_ctx_new(void);
205 static void capi_ctx_free(CAPI_CTX * ctx);
206 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
208 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx);
210 # define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
211 # define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
212 # define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
213 # define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
214 # define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
215 # define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
216 # define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
217 # define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
218 # define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
219 # define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
220 # define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
221 # define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
222 # define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
223 # define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
225 static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
226 {CAPI_CMD_LIST_CERTS,
228 "List all certificates in store",
229 ENGINE_CMD_FLAG_NO_INPUT},
230 {CAPI_CMD_LOOKUP_CERT,
232 "Lookup and output certificates",
233 ENGINE_CMD_FLAG_STRING},
234 {CAPI_CMD_DEBUG_LEVEL,
236 "debug level (1=errors, 2=trace)",
237 ENGINE_CMD_FLAG_NUMERIC},
238 {CAPI_CMD_DEBUG_FILE,
240 "debugging filename)",
241 ENGINE_CMD_FLAG_STRING},
244 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
245 ENGINE_CMD_FLAG_NUMERIC},
249 ENGINE_CMD_FLAG_NO_INPUT},
250 {CAPI_CMD_SET_CSP_IDX,
253 ENGINE_CMD_FLAG_NUMERIC},
254 {CAPI_CMD_SET_CSP_NAME,
256 "Set CSP name, (default CSP used if not specified)",
257 ENGINE_CMD_FLAG_STRING},
258 {CAPI_CMD_SET_CSP_TYPE,
260 "Set CSP type, (default RSA_PROV_FULL)",
261 ENGINE_CMD_FLAG_NUMERIC},
262 {CAPI_CMD_LIST_CONTAINERS,
264 "list container names",
265 ENGINE_CMD_FLAG_NO_INPUT},
266 {CAPI_CMD_LIST_OPTIONS,
268 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
269 "32=private key info)",
270 ENGINE_CMD_FLAG_NUMERIC},
271 {CAPI_CMD_LOOKUP_METHOD,
273 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
274 ENGINE_CMD_FLAG_NUMERIC},
275 {CAPI_CMD_STORE_NAME,
277 "certificate store name, default \"MY\"",
278 ENGINE_CMD_FLAG_STRING},
279 {CAPI_CMD_STORE_FLAGS,
281 "Certificate store flags: 1 = system store",
282 ENGINE_CMD_FLAG_NUMERIC},
287 static int capi_idx = -1;
288 static int rsa_capi_idx = -1;
289 static int dsa_capi_idx = -1;
290 static int cert_capi_idx = -1;
292 static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
298 if (capi_idx == -1) {
299 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
302 ctx = ENGINE_get_ex_data(e, capi_idx);
303 out = BIO_new_fp(stdout, BIO_NOCLOSE);
305 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_FILE_OPEN_ERROR);
309 case CAPI_CMD_LIST_CSPS:
310 ret = capi_list_providers(ctx, out);
313 case CAPI_CMD_LIST_CERTS:
314 ret = capi_list_certs(ctx, out, NULL);
317 case CAPI_CMD_LOOKUP_CERT:
318 ret = capi_list_certs(ctx, out, p);
321 case CAPI_CMD_LIST_CONTAINERS:
322 ret = capi_list_containers(ctx, out);
325 case CAPI_CMD_STORE_NAME:
326 tmpstr = OPENSSL_strdup(p);
327 if (tmpstr != NULL) {
328 OPENSSL_free(ctx->storename);
329 ctx->storename = tmpstr;
330 CAPI_trace(ctx, "Setting store name to %s\n", p);
332 CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
337 case CAPI_CMD_STORE_FLAGS:
339 ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE;
340 ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER;
342 ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER;
343 ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE;
345 CAPI_trace(ctx, "Setting flags to %d\n", i);
348 case CAPI_CMD_DEBUG_LEVEL:
349 ctx->debug_level = (int)i;
350 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
353 case CAPI_CMD_DEBUG_FILE:
354 tmpstr = OPENSSL_strdup(p);
355 if (tmpstr != NULL) {
356 ctx->debug_file = tmpstr;
357 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
359 CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
364 case CAPI_CMD_KEYTYPE:
366 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
369 case CAPI_CMD_SET_CSP_IDX:
370 ret = capi_ctx_set_provname_idx(ctx, i);
373 case CAPI_CMD_LIST_OPTIONS:
377 case CAPI_CMD_LOOKUP_METHOD:
378 if (i < 1 || i > 3) {
379 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
383 ctx->lookup_method = i;
386 case CAPI_CMD_SET_CSP_NAME:
387 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
390 case CAPI_CMD_SET_CSP_TYPE:
395 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
404 static RSA_METHOD *capi_rsa_method = NULL;
405 # ifndef OPENSSL_NO_DSA
406 static DSA_METHOD *capi_dsa_method = NULL;
409 static int use_aes_csp = 0;
411 static int capi_init(ENGINE *e)
414 const RSA_METHOD *ossl_rsa_meth;
415 # ifndef OPENSSL_NO_DSA
416 const DSA_METHOD *ossl_dsa_meth;
421 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
425 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
427 /* Setup RSA_METHOD */
428 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
429 ossl_rsa_meth = RSA_PKCS1_OpenSSL();
430 if ( !RSA_meth_set_pub_enc(capi_rsa_method,
431 RSA_meth_get_pub_enc(ossl_rsa_meth))
432 || !RSA_meth_set_pub_dec(capi_rsa_method,
433 RSA_meth_get_pub_dec(ossl_rsa_meth))
434 || !RSA_meth_set_priv_enc(capi_rsa_method, capi_rsa_priv_enc)
435 || !RSA_meth_set_priv_dec(capi_rsa_method, capi_rsa_priv_dec)
436 || !RSA_meth_set_mod_exp(capi_rsa_method,
437 RSA_meth_get_mod_exp(ossl_rsa_meth))
438 || !RSA_meth_set_bn_mod_exp(capi_rsa_method,
439 RSA_meth_get_bn_mod_exp(ossl_rsa_meth))
440 || !RSA_meth_set_finish(capi_rsa_method, capi_rsa_free)
441 || !RSA_meth_set_sign(capi_rsa_method, capi_rsa_sign)) {
445 # ifndef OPENSSL_NO_DSA
446 /* Setup DSA Method */
447 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
448 ossl_dsa_meth = DSA_OpenSSL();
449 if ( !DSA_meth_set_sign(capi_dsa_method, capi_dsa_do_sign)
450 || !DSA_meth_set_verify(capi_dsa_method,
451 DSA_meth_get_verify(ossl_dsa_meth))
452 || !DSA_meth_set_finish(capi_dsa_method, capi_dsa_free)
453 || !DSA_meth_set_mod_exp(capi_dsa_method,
454 DSA_meth_get_mod_exp(ossl_dsa_meth))
455 || !DSA_meth_set_bn_mod_exp(capi_dsa_method,
456 DSA_meth_get_bn_mod_exp(ossl_dsa_meth))) {
462 ctx = capi_ctx_new();
466 ENGINE_set_ex_data(e, capi_idx, ctx);
468 # ifdef OPENSSL_CAPIENG_DIALOG
470 HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL"));
471 HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL"));
474 (CERTDLG) GetProcAddress(cryptui,
475 "CryptUIDlgSelectCertificateFromStore");
478 (GETCONSWIN) GetProcAddress(kernel, "GetConsoleWindow");
479 if (cryptui && !OPENSSL_isservice())
480 ctx->client_cert_select = cert_select_dialog;
484 /* See if we support AES CSP */
486 if (CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_AES,
487 CRYPT_VERIFYCONTEXT)) {
489 CryptReleaseContext(hprov, 0);
495 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
501 static int capi_destroy(ENGINE *e)
503 RSA_meth_free(capi_rsa_method);
504 capi_rsa_method = NULL;
505 # ifndef OPENSSL_NO_DSA
506 DSA_meth_free(capi_dsa_method);
507 capi_dsa_method = NULL;
509 ERR_unload_CAPI_strings();
513 static int capi_finish(ENGINE *e)
516 ctx = ENGINE_get_ex_data(e, capi_idx);
518 ENGINE_set_ex_data(e, capi_idx, NULL);
523 * CryptoAPI key application data. This contains a handle to the private key
524 * container (for sign operations) and a handle to the key (for decrypt
529 /* Associated certificate context (if any) */
530 PCCERT_CONTEXT pcert;
536 static int bind_capi(ENGINE *e)
538 capi_rsa_method = RSA_meth_new("CryptoAPI RSA method", 0);
539 if (capi_rsa_method == NULL)
541 # ifndef OPENSSL_NO_DSA
542 capi_dsa_method = DSA_meth_new("CryptoAPI DSA method", 0);
543 if (capi_dsa_method == NULL)
546 if (!ENGINE_set_id(e, engine_capi_id)
547 || !ENGINE_set_name(e, engine_capi_name)
548 || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
549 || !ENGINE_set_init_function(e, capi_init)
550 || !ENGINE_set_finish_function(e, capi_finish)
551 || !ENGINE_set_destroy_function(e, capi_destroy)
552 || !ENGINE_set_RSA(e, capi_rsa_method)
553 # ifndef OPENSSL_NO_DSA
554 || !ENGINE_set_DSA(e, capi_dsa_method)
556 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
557 || !ENGINE_set_load_ssl_client_cert_function(e,
558 capi_load_ssl_client_cert)
559 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
560 || !ENGINE_set_ctrl_function(e, capi_ctrl))
562 ERR_load_CAPI_strings();
566 RSA_meth_free(capi_rsa_method);
567 capi_rsa_method = NULL;
568 # ifndef OPENSSL_NO_DSA
569 DSA_meth_free(capi_dsa_method);
570 capi_dsa_method = NULL;
575 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
576 static int bind_helper(ENGINE *e, const char *id)
578 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();
593 if (!bind_capi(ret)) {
600 void engine_load_capi_int(void)
602 /* Copied from eng_[openssl|dyn].c */
603 ENGINE *toadd = engine_capi();
612 static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
616 * Reverse buffer in place: since this is a keyblob structure that will
617 * be freed up after conversion anyway it doesn't matter if we change
620 for (i = 0; i < binlen / 2; i++) {
623 bin[i] = bin[binlen - i - 1];
624 bin[binlen - i - 1] = c;
627 if (!BN_bin2bn(bin, binlen, bn))
632 /* Given a CAPI_KEY get an EVP_PKEY structure */
634 static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
636 unsigned char *pubkey = NULL;
641 EVP_PKEY *ret = NULL;
642 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) {
643 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
648 pubkey = OPENSSL_malloc(len);
653 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
654 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
659 bh = (BLOBHEADER *) pubkey;
660 if (bh->bType != PUBLICKEYBLOB) {
661 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
664 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
667 BIGNUM *e = NULL, *n = NULL;
668 unsigned char *rsa_modulus;
669 rp = (RSAPUBKEY *) (bh + 1);
670 if (rp->magic != 0x31415352) {
672 BIO_snprintf(magstr, 10, "%lx", rp->magic);
673 CAPIerr(CAPI_F_CAPI_GET_PKEY,
674 CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
675 ERR_add_error_data(2, "magic=0x", magstr);
678 rsa_modulus = (unsigned char *)(rp + 1);
679 rkey = RSA_new_method(eng);
686 if (e == NULL || n == NULL) {
692 RSA_set0_key(rkey, n, e, NULL);
694 if (!BN_set_word(e, rp->pubexp))
697 rsa_modlen = rp->bitlen / 8;
698 if (!lend_tobn(n, rsa_modulus, rsa_modlen))
701 RSA_set_ex_data(rkey, rsa_capi_idx, key);
703 if ((ret = EVP_PKEY_new()) == NULL)
706 EVP_PKEY_assign_RSA(ret, rkey);
709 # ifndef OPENSSL_NO_DSA
710 } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
714 BIGNUM *p, *q, *g, *pub_key;
715 dp = (DSSPUBKEY *) (bh + 1);
716 if (dp->magic != 0x31535344) {
718 BIO_snprintf(magstr, 10, "%lx", dp->magic);
719 CAPIerr(CAPI_F_CAPI_GET_PKEY,
720 CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
721 ERR_add_error_data(2, "magic=0x", magstr);
724 dsa_plen = dp->bitlen / 8;
725 btmp = (unsigned char *)(dp + 1);
726 dkey = DSA_new_method(eng);
733 if (p == NULL || q == NULL || g == NULL || pub_key == NULL) {
740 DSA_set0_pqg(dkey, p, q, g);
741 DSA_set0_key(dkey, pub_key, NULL);
742 if (!lend_tobn(p, btmp, dsa_plen))
745 if (!lend_tobn(q, btmp, 20))
748 if (!lend_tobn(g, btmp, dsa_plen))
751 if (!lend_tobn(pub_key, btmp, dsa_plen))
755 DSA_set_ex_data(dkey, dsa_capi_idx, key);
757 if ((ret = EVP_PKEY_new()) == NULL)
760 EVP_PKEY_assign_DSA(ret, dkey);
765 BIO_snprintf(algstr, 10, "%ux", bh->aiKeyAlg);
766 CAPIerr(CAPI_F_CAPI_GET_PKEY,
767 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
768 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
773 OPENSSL_free(pubkey);
776 # ifndef OPENSSL_NO_DSA
784 CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
789 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
790 UI_METHOD *ui_method, void *callback_data)
795 ctx = ENGINE_get_ex_data(eng, capi_idx);
798 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
802 key = capi_find_key(ctx, key_id);
807 ret = capi_get_pkey(eng, key);
815 /* CryptoAPI RSA operations */
817 int capi_rsa_priv_enc(int flen, const unsigned char *from,
818 unsigned char *to, RSA *rsa, int padding)
820 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
824 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
825 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
835 ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
837 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
839 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
841 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
844 /* Convert the signature type to a CryptoAPI algorithm ID */
867 alg = CALG_SSL3_SHAMD5;
872 BIO_snprintf(algstr, 10, "%x", dtype);
873 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
874 ERR_add_error_data(2, "NID=0x", algstr);
879 /* Create the hash object */
880 if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
881 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
885 /* Set the hash value to the value passed */
887 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
888 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
893 /* Finally sign it */
894 slen = RSA_size(rsa);
895 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
896 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
901 /* Inplace byte reversal of signature */
902 for (i = 0; i < slen / 2; i++) {
905 sigret[i] = sigret[slen - i - 1];
906 sigret[slen - i - 1] = c;
914 CryptDestroyHash(hash);
919 int capi_rsa_priv_dec(int flen, const unsigned char *from,
920 unsigned char *to, RSA *rsa, int padding)
923 unsigned char *tmpbuf;
931 ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
933 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
935 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
937 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
941 if (padding != RSA_PKCS1_PADDING) {
943 BIO_snprintf(errstr, 10, "%d", padding);
944 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
945 ERR_add_error_data(2, "padding=", errstr);
949 /* Create temp reverse order version of input */
950 if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
951 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
954 for (i = 0; i < flen; i++)
955 tmpbuf[flen - i - 1] = from[i];
957 /* Finally decrypt it */
959 if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &dlen)) {
960 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
962 OPENSSL_free(tmpbuf);
965 memcpy(to, tmpbuf, (flen = (int)dlen));
967 OPENSSL_free(tmpbuf);
972 static int capi_rsa_free(RSA *rsa)
975 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
976 capi_free_key(capi_key);
977 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
981 # ifndef OPENSSL_NO_DSA
982 /* CryptoAPI DSA operations */
984 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
992 unsigned char csigbuf[40];
994 ctx = ENGINE_get_ex_data(DSA_get0_engine(dsa), capi_idx);
996 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
998 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1001 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
1006 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
1010 /* Create the hash object */
1011 if (!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) {
1012 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
1013 capi_addlasterror();
1017 /* Set the hash value to the value passed */
1018 if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) {
1019 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
1020 capi_addlasterror();
1024 /* Finally sign it */
1025 slen = sizeof(csigbuf);
1026 if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) {
1027 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
1028 capi_addlasterror();
1031 BIGNUM *r = BN_new(), *s = BN_new();
1033 if (r == NULL || s == NULL
1034 || !lend_tobn(r, csigbuf, 20)
1035 || !lend_tobn(s, csigbuf + 20, 20)
1036 || (ret = DSA_SIG_new()) == NULL) {
1037 BN_free(r); /* BN_free checks for BIGNUM * being NULL */
1041 DSA_SIG_set0(ret, r, s);
1047 OPENSSL_cleanse(csigbuf, 40);
1048 CryptDestroyHash(hash);
1052 static int capi_dsa_free(DSA *dsa)
1055 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
1056 capi_free_key(capi_key);
1057 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
1062 static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
1067 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
1069 out = BIO_new_file(ctx->debug_file, "a+");
1071 CAPIerr(CAPI_F_CAPI_VTRACE, CAPI_R_FILE_OPEN_ERROR);
1074 BIO_vprintf(out, format, argptr);
1078 static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
1081 va_start(args, format);
1082 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
1086 static void capi_addlasterror(void)
1088 capi_adderror(GetLastError());
1091 static void capi_adderror(DWORD err)
1094 BIO_snprintf(errstr, 10, "%lX", err);
1095 ERR_add_error_data(2, "Error code= 0x", errstr);
1098 static char *wide_to_asc(LPCWSTR wstr)
1105 len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
1106 sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
1108 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1111 str = OPENSSL_malloc(sz);
1113 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
1116 if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
1118 CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
1124 static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
1129 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
1130 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len)) {
1131 err = GetLastError();
1132 if (err == ERROR_NO_MORE_ITEMS)
1134 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1138 name = OPENSSL_malloc(len);
1140 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
1143 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
1144 err = GetLastError();
1146 if (err == ERROR_NO_MORE_ITEMS)
1148 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1152 if (sizeof(TCHAR) != sizeof(char)) {
1153 *pname = wide_to_asc((WCHAR *)name);
1158 *pname = (char *)name;
1159 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
1165 static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
1169 LPSTR provname = NULL;
1170 CAPI_trace(ctx, "capi_list_providers\n");
1171 BIO_printf(out, "Available CSPs:\n");
1172 for (idx = 0;; idx++) {
1173 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1178 BIO_printf(out, "%lu. %s, type %lu\n", idx, provname, ptype);
1179 OPENSSL_free(provname);
1184 static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
1188 DWORD err, idx, flags, buflen = 0, clen;
1190 LPTSTR cspname = NULL;
1192 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
1194 if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
1196 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
1197 cspname = alloca(clen * sizeof(WCHAR));
1198 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
1202 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1203 capi_addlasterror();
1207 cspname = (TCHAR *)ctx->cspname;
1208 if (!CryptAcquireContext
1209 (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
1210 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
1211 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1212 capi_addlasterror();
1215 if (!CryptGetProvParam
1216 (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
1217 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1218 capi_addlasterror();
1219 CryptReleaseContext(hprov, 0);
1222 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1225 cname = OPENSSL_malloc(buflen);
1226 if (cname == NULL) {
1227 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1231 for (idx = 0;; idx++) {
1236 flags = CRYPT_FIRST;
1239 if (!CryptGetProvParam
1240 (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
1241 err = GetLastError();
1242 if (err == ERROR_NO_MORE_ITEMS)
1244 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1248 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n",
1249 cname, clen, idx, flags);
1250 if (!cname[0] && (clen == buflen)) {
1251 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1254 BIO_printf(out, "%lu. %s\n", idx, cname);
1261 OPENSSL_free(cname);
1262 CryptReleaseContext(hprov, 0);
1267 static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1270 CRYPT_KEY_PROV_INFO *pinfo;
1272 if (!CertGetCertificateContextProperty
1273 (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1275 pinfo = OPENSSL_malloc(len);
1276 if (pinfo == NULL) {
1277 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1280 if (!CertGetCertificateContextProperty
1281 (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
1282 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
1283 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1284 capi_addlasterror();
1285 OPENSSL_free(pinfo);
1291 static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
1292 CRYPT_KEY_PROV_INFO * pinfo)
1294 char *provname = NULL, *contname = NULL;
1296 BIO_printf(out, " No Private Key\n");
1299 provname = wide_to_asc(pinfo->pwszProvName);
1300 contname = wide_to_asc(pinfo->pwszContainerName);
1301 if (!provname || !contname)
1304 BIO_printf(out, " Private Key Info:\n");
1305 BIO_printf(out, " Provider Name: %s, Provider Type %lu\n", provname,
1307 BIO_printf(out, " Container Name: %s, Key Type %lu\n", contname,
1310 OPENSSL_free(provname);
1311 OPENSSL_free(contname);
1314 static char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1319 CAPI_trace(ctx, "capi_cert_get_fname\n");
1320 if (!CertGetCertificateContextProperty
1321 (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1323 wfname = OPENSSL_malloc(dlen);
1326 if (CertGetCertificateContextProperty
1327 (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
1328 char *fname = wide_to_asc(wfname);
1329 OPENSSL_free(wfname);
1332 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1333 capi_addlasterror();
1335 OPENSSL_free(wfname);
1339 static void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
1342 const unsigned char *p;
1343 unsigned long flags = ctx->dump_flags;
1344 if (flags & CAPI_DMP_FNAME) {
1346 fname = capi_cert_get_fname(ctx, cert);
1348 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1349 OPENSSL_free(fname);
1351 BIO_printf(out, " <No Friendly Name>\n");
1354 p = cert->pbCertEncoded;
1355 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1357 BIO_printf(out, " <Can't parse certificate>\n");
1358 if (flags & CAPI_DMP_SUMMARY) {
1359 BIO_printf(out, " Subject: ");
1360 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1361 BIO_printf(out, "\n Issuer: ");
1362 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1363 BIO_printf(out, "\n");
1365 if (flags & CAPI_DMP_FULL)
1366 X509_print_ex(out, x, XN_FLAG_ONELINE, 0);
1368 if (flags & CAPI_DMP_PKEYINFO) {
1369 CRYPT_KEY_PROV_INFO *pinfo;
1370 pinfo = capi_get_prov_info(ctx, cert);
1371 capi_dump_prov_info(ctx, out, pinfo);
1372 OPENSSL_free(pinfo);
1375 if (flags & CAPI_DMP_PEM)
1376 PEM_write_bio_X509(out, x);
1380 static HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
1385 storename = ctx->storename;
1388 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1390 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
1391 ctx->store_flags, storename);
1393 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1394 capi_addlasterror();
1399 int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
1405 PCCERT_CONTEXT cert = NULL;
1407 storename = ctx->storename;
1410 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1412 hstore = capi_open_store(ctx, storename);
1416 cert = capi_find_cert(ctx, id, hstore);
1421 capi_dump_cert(ctx, out, cert);
1422 CertFreeCertificateContext(cert);
1424 for (idx = 0;; idx++) {
1425 cert = CertEnumCertificatesInStore(hstore, cert);
1428 BIO_printf(out, "Certificate %d\n", idx);
1429 capi_dump_cert(ctx, out, cert);
1433 CertCloseStore(hstore, 0);
1437 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
1440 PCCERT_CONTEXT cert = NULL;
1443 switch (ctx->lookup_method) {
1444 case CAPI_LU_SUBSTR:
1445 return CertFindCertificateInStore(hstore,
1446 X509_ASN_ENCODING, 0,
1447 CERT_FIND_SUBJECT_STR_A, id, NULL);
1450 cert = CertEnumCertificatesInStore(hstore, cert);
1453 fname = capi_cert_get_fname(ctx, cert);
1455 if (strcmp(fname, id))
1459 OPENSSL_free(fname);
1469 static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
1470 TCHAR *provname, DWORD ptype, DWORD keyspec)
1473 CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
1477 /* If PROV_RSA_AES supported use it instead */
1478 if (ptype == PROV_RSA_FULL && use_aes_csp) {
1480 ptype = PROV_RSA_AES;
1481 CAPI_trace(ctx, "capi_get_key, contname=%s, RSA_AES_CSP\n", contname);
1482 } else if (sizeof(TCHAR) == sizeof(char)) {
1483 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1484 contname, provname, ptype);
1485 } else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
1486 /* above 'if' is optimization to minimize malloc-ations */
1487 char *_contname = wide_to_asc((WCHAR *)contname);
1488 char *_provname = wide_to_asc((WCHAR *)provname);
1490 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1491 _contname, _provname, ptype);
1492 OPENSSL_free(_provname);
1493 OPENSSL_free(_contname);
1495 if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
1496 dwFlags = CRYPT_MACHINE_KEYSET;
1497 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
1498 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1499 capi_addlasterror();
1502 if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) {
1503 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1504 capi_addlasterror();
1505 CryptReleaseContext(key->hprov, 0);
1508 key->keyspec = keyspec;
1517 static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
1519 CAPI_KEY *key = NULL;
1520 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1521 char *provname = NULL, *contname = NULL;
1522 pinfo = capi_get_prov_info(ctx, cert);
1525 if (sizeof(TCHAR) != sizeof(char))
1526 key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
1527 (TCHAR *)pinfo->pwszProvName,
1528 pinfo->dwProvType, pinfo->dwKeySpec);
1530 provname = wide_to_asc(pinfo->pwszProvName);
1531 contname = wide_to_asc(pinfo->pwszContainerName);
1532 if (!provname || !contname)
1534 key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1535 pinfo->dwProvType, pinfo->dwKeySpec);
1539 OPENSSL_free(pinfo);
1540 OPENSSL_free(provname);
1541 OPENSSL_free(contname);
1545 CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
1547 PCCERT_CONTEXT cert;
1549 CAPI_KEY *key = NULL;
1550 switch (ctx->lookup_method) {
1551 case CAPI_LU_SUBSTR:
1553 hstore = capi_open_store(ctx, NULL);
1556 cert = capi_find_cert(ctx, id, hstore);
1558 key = capi_get_cert_key(ctx, cert);
1559 CertFreeCertificateContext(cert);
1561 CertCloseStore(hstore, 0);
1564 case CAPI_LU_CONTNAME:
1565 if (sizeof(TCHAR) != sizeof(char)) {
1566 WCHAR *contname, *provname;
1569 if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
1570 (contname = alloca(len * sizeof(WCHAR)),
1571 MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
1573 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
1575 alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
1582 capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
1583 ctx->csptype, ctx->keytype);
1585 key = capi_get_key(ctx, (TCHAR *)id,
1586 (TCHAR *)ctx->cspname,
1587 ctx->csptype, ctx->keytype);
1594 void capi_free_key(CAPI_KEY * key)
1598 CryptDestroyKey(key->key);
1599 CryptReleaseContext(key->hprov, 0);
1601 CertFreeCertificateContext(key->pcert);
1605 /* Initialize a CAPI_CTX structure */
1607 static CAPI_CTX *capi_ctx_new(void)
1609 CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
1612 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1615 ctx->csptype = PROV_RSA_FULL;
1616 ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
1617 ctx->keytype = AT_KEYEXCHANGE;
1618 ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
1619 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
1620 ctx->lookup_method = CAPI_LU_SUBSTR;
1621 ctx->client_cert_select = cert_select_simple;
1625 static void capi_ctx_free(CAPI_CTX * ctx)
1627 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1630 OPENSSL_free(ctx->cspname);
1631 OPENSSL_free(ctx->debug_file);
1632 OPENSSL_free(ctx->storename);
1633 OPENSSL_free(ctx->ssl_client_store);
1637 static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
1642 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1647 if (sizeof(TCHAR) != sizeof(char)) {
1649 if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
1650 name = alloca(len * sizeof(WCHAR));
1651 MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
1654 name = (TCHAR *)pname;
1656 if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
1657 CRYPT_VERIFYCONTEXT)) {
1658 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
1659 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1660 capi_addlasterror();
1663 CryptReleaseContext(hprov, 0);
1665 tmpcspname = OPENSSL_strdup(pname);
1666 if (tmpcspname == NULL) {
1667 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, ERR_R_MALLOC_FAILURE);
1670 OPENSSL_free(ctx->cspname);
1671 ctx->cspname = tmpcspname;
1672 ctx->csptype = type;
1676 static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
1681 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1683 res = capi_ctx_set_provname(ctx, pname, type, 0);
1684 OPENSSL_free(pname);
1688 static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1692 /* Special case: empty list: match anything */
1693 if (sk_X509_NAME_num(ca_dn) <= 0)
1695 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) {
1696 nm = sk_X509_NAME_value(ca_dn, i);
1697 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1703 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1704 STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
1705 EVP_PKEY **pkey, STACK_OF(X509) **pother,
1706 UI_METHOD *ui_method,
1707 void *callback_data)
1709 STACK_OF(X509) *certs = NULL;
1712 const unsigned char *p;
1713 int i, client_cert_idx;
1715 PCCERT_CONTEXT cert = NULL, excert = NULL;
1718 ctx = ENGINE_get_ex_data(e, capi_idx);
1723 storename = ctx->ssl_client_store;
1727 hstore = capi_open_store(ctx, storename);
1730 /* Enumerate all certificates collect any matches */
1732 cert = CertEnumCertificatesInStore(hstore, cert);
1735 p = cert->pbCertEncoded;
1736 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1738 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1741 if (cert_issuer_match(ca_dn, x)
1742 && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) {
1743 key = capi_get_cert_key(ctx, cert);
1749 * Match found: attach extra data to it so we can retrieve the
1752 excert = CertDuplicateCertificateContext(cert);
1753 key->pcert = excert;
1754 X509_set_ex_data(x, cert_capi_idx, key);
1757 certs = sk_X509_new_null();
1759 sk_X509_push(certs, x);
1766 CertFreeCertificateContext(cert);
1768 CertCloseStore(hstore, 0);
1773 /* Select the appropriate certificate */
1775 client_cert_idx = ctx->client_cert_select(e, ssl, certs);
1777 /* Set the selected certificate and free the rest */
1779 for (i = 0; i < sk_X509_num(certs); i++) {
1780 x = sk_X509_value(certs, i);
1781 if (i == client_cert_idx)
1784 key = X509_get_ex_data(x, cert_capi_idx);
1790 sk_X509_free(certs);
1795 /* Setup key for selected certificate */
1797 key = X509_get_ex_data(*pcert, cert_capi_idx);
1798 *pkey = capi_get_pkey(e, key);
1799 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1805 /* Simple client cert selection function: always select first */
1807 static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1812 # ifdef OPENSSL_CAPIENG_DIALOG
1815 * More complex cert selection function, using standard function
1816 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1820 * Definitions which are in cryptuiapi.h but this is not present in older
1821 * versions of headers.
1824 # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1825 # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1826 # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1829 # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1830 # define dlg_prompt L"Select a certificate to use for authentication"
1831 # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1832 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1834 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1838 PCCERT_CONTEXT cert;
1843 if (sk_X509_num(certs) == 1)
1845 ctx = ENGINE_get_ex_data(e, capi_idx);
1846 /* Create an in memory store of certificates */
1847 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1848 CERT_STORE_CREATE_NEW_FLAG, NULL);
1850 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE);
1851 capi_addlasterror();
1854 /* Add all certificates to store */
1855 for (i = 0; i < sk_X509_num(certs); i++) {
1856 x = sk_X509_value(certs, i);
1857 key = X509_get_ex_data(x, cert_capi_idx);
1859 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1860 CERT_STORE_ADD_NEW, NULL)) {
1861 CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT);
1862 capi_addlasterror();
1867 hwnd = GetForegroundWindow();
1869 hwnd = GetActiveWindow();
1870 if (!hwnd && ctx->getconswindow)
1871 hwnd = ctx->getconswindow();
1872 /* Call dialog to select one */
1873 cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt,
1874 dlg_columns, 0, NULL);
1876 /* Find matching cert from list */
1878 for (i = 0; i < sk_X509_num(certs); i++) {
1879 x = sk_X509_value(certs, i);
1880 key = X509_get_ex_data(x, cert_capi_idx);
1881 if (CertCompareCertificate
1882 (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo,
1883 key->pcert->pCertInfo)) {
1892 CertCloseStore(dstore, 0);
1898 #else /* !__COMPILE_CAPIENG */
1899 # include <openssl/engine.h>
1900 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1902 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1904 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
1909 IMPLEMENT_DYNAMIC_CHECK_FN()
1911 void engine_load_capi_int(void);
1912 void engine_load_capi_int(void)