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 * ====================================================================
58 #include <openssl/crypto.h>
60 #ifdef OPENSSL_SYS_WIN32
61 # ifndef OPENSSL_NO_CAPIENG
63 # include <openssl/buffer.h>
64 # include <openssl/bn.h>
65 # include <openssl/rsa.h>
66 # include <openssl/dsa.h>
69 # define _WIN32_WINNT 0x0400
73 # include <wincrypt.h>
76 # define alloca _alloca
80 * This module uses several "new" interfaces, among which is
81 * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is
82 * one of possible values you can pass to function in question. By
83 * checking if it's defined we can see if wincrypt.h and accompanying
84 * crypt32.lib are in shape. The native MingW32 headers up to and
85 * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the
86 * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG,
87 * so we check for these too and avoid compiling.
88 * Yes, it's rather "weak" test and if compilation fails,
89 * then re-configure with -DOPENSSL_NO_CAPIENG.
91 # if defined(CERT_KEY_PROV_INFO_PROP_ID) && \
92 defined(CERT_STORE_PROV_SYSTEM_A) && \
93 defined(CERT_STORE_READONLY_FLAG)
94 # define __COMPILE_CAPIENG
95 # endif /* CERT_KEY_PROV_INFO_PROP_ID */
96 # endif /* OPENSSL_NO_CAPIENG */
97 #endif /* OPENSSL_SYS_WIN32 */
99 #ifdef __COMPILE_CAPIENG
101 # undef X509_EXTENSIONS
103 /* Definitions which may be missing from earlier version of headers */
104 # ifndef CERT_STORE_OPEN_EXISTING_FLAG
105 # define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
108 # ifndef CERT_STORE_CREATE_NEW_FLAG
109 # define CERT_STORE_CREATE_NEW_FLAG 0x00002000
112 # ifndef CERT_SYSTEM_STORE_CURRENT_USER
113 # define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000
116 # ifndef ALG_SID_SHA_256
117 # define ALG_SID_SHA_256 12
119 # ifndef ALG_SID_SHA_384
120 # define ALG_SID_SHA_384 13
122 # ifndef ALG_SID_SHA_512
123 # define ALG_SID_SHA_512 14
126 # ifndef CALG_SHA_256
127 # define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
129 # ifndef CALG_SHA_384
130 # define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
132 # ifndef CALG_SHA_512
133 # define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
136 # ifndef PROV_RSA_AES
137 # define PROV_RSA_AES 24
140 # include <openssl/engine.h>
141 # include <openssl/pem.h>
142 # include <openssl/x509v3.h>
144 # include "e_capi_err.h"
145 # include "e_capi_err.c"
147 static const char *engine_capi_id
= "capi";
148 static const char *engine_capi_name
= "CryptoAPI ENGINE";
150 typedef struct CAPI_CTX_st CAPI_CTX
;
151 typedef struct CAPI_KEY_st CAPI_KEY
;
153 static void capi_addlasterror(void);
154 static void capi_adderror(DWORD err
);
156 static void CAPI_trace(CAPI_CTX
* ctx
, char *format
, ...);
158 static int capi_list_providers(CAPI_CTX
* ctx
, BIO
*out
);
159 static int capi_list_containers(CAPI_CTX
* ctx
, BIO
*out
);
160 int capi_list_certs(CAPI_CTX
* ctx
, BIO
*out
, char *storename
);
161 void capi_free_key(CAPI_KEY
* key
);
163 static PCCERT_CONTEXT
capi_find_cert(CAPI_CTX
* ctx
, const char *id
,
166 CAPI_KEY
*capi_find_key(CAPI_CTX
* ctx
, const char *id
);
168 static EVP_PKEY
*capi_load_privkey(ENGINE
*eng
, const char *key_id
,
169 UI_METHOD
*ui_method
, void *callback_data
);
170 static int capi_rsa_sign(int dtype
, const unsigned char *m
,
171 unsigned int m_len
, unsigned char *sigret
,
172 unsigned int *siglen
, const RSA
*rsa
);
173 static int capi_rsa_priv_enc(int flen
, const unsigned char *from
,
174 unsigned char *to
, RSA
*rsa
, int padding
);
175 static int capi_rsa_priv_dec(int flen
, const unsigned char *from
,
176 unsigned char *to
, RSA
*rsa
, int padding
);
177 static int capi_rsa_free(RSA
*rsa
);
179 static DSA_SIG
*capi_dsa_do_sign(const unsigned char *digest
, int dlen
,
181 static int capi_dsa_free(DSA
*dsa
);
183 static int capi_load_ssl_client_cert(ENGINE
*e
, SSL
*ssl
,
184 STACK_OF(X509_NAME
) *ca_dn
, X509
**pcert
,
185 EVP_PKEY
**pkey
, STACK_OF(X509
) **pother
,
186 UI_METHOD
*ui_method
,
187 void *callback_data
);
189 static int cert_select_simple(ENGINE
*e
, SSL
*ssl
, STACK_OF(X509
) *certs
);
190 # ifdef OPENSSL_CAPIENG_DIALOG
191 static int cert_select_dialog(ENGINE
*e
, SSL
*ssl
, STACK_OF(X509
) *certs
);
194 void int_engine_load_capi(void);
196 typedef PCCERT_CONTEXT(WINAPI
*CERTDLG
) (HCERTSTORE
, HWND
, LPCWSTR
,
197 LPCWSTR
, DWORD
, DWORD
, void *);
198 typedef HWND(WINAPI
*GETCONSWIN
) (void);
201 * This structure contains CAPI ENGINE specific data: it contains various
202 * global options and affects how other functions behave.
205 # define CAPI_DBG_TRACE 2
206 # define CAPI_DBG_ERROR 1
211 /* Parameters to use for container lookup */
215 /* Certificate store name to use */
217 LPSTR ssl_client_store
;
218 /* System store flags */
220 /* Lookup string meanings in load_private_key */
221 /* Substring of subject: uses "storename" */
222 # define CAPI_LU_SUBSTR 1
223 /* Friendly name: uses storename */
224 # define CAPI_LU_FNAME 2
225 /* Container name: uses cspname, keytype */
226 # define CAPI_LU_CONTNAME 3
228 /* Info to dump with dumpcerts option */
229 /* Issuer and serial name strings */
230 # define CAPI_DMP_SUMMARY 0x1
232 # define CAPI_DMP_FNAME 0x2
233 /* Full X509_print dump */
234 # define CAPI_DMP_FULL 0x4
235 /* Dump PEM format certificate */
236 # define CAPI_DMP_PEM 0x8
237 /* Dump pseudo key (if possible) */
238 # define CAPI_DMP_PSKEY 0x10
239 /* Dump key info (if possible) */
240 # define CAPI_DMP_PKEYINFO 0x20
242 int (*client_cert_select
) (ENGINE
*e
, SSL
*ssl
, STACK_OF(X509
) *certs
);
243 CERTDLG certselectdlg
;
244 GETCONSWIN getconswindow
;
247 static CAPI_CTX
*capi_ctx_new(void);
248 static void capi_ctx_free(CAPI_CTX
* ctx
);
249 static int capi_ctx_set_provname(CAPI_CTX
* ctx
, LPSTR pname
, DWORD type
,
251 static int capi_ctx_set_provname_idx(CAPI_CTX
* ctx
, int idx
);
253 # define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
254 # define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
255 # define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
256 # define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
257 # define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
258 # define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
259 # define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
260 # define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
261 # define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
262 # define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
263 # define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
264 # define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
265 # define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
266 # define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13)
268 static const ENGINE_CMD_DEFN capi_cmd_defns
[] = {
269 {CAPI_CMD_LIST_CERTS
,
271 "List all certificates in store",
272 ENGINE_CMD_FLAG_NO_INPUT
},
273 {CAPI_CMD_LOOKUP_CERT
,
275 "Lookup and output certificates",
276 ENGINE_CMD_FLAG_STRING
},
277 {CAPI_CMD_DEBUG_LEVEL
,
279 "debug level (1=errors, 2=trace)",
280 ENGINE_CMD_FLAG_NUMERIC
},
281 {CAPI_CMD_DEBUG_FILE
,
283 "debugging filename)",
284 ENGINE_CMD_FLAG_STRING
},
287 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
288 ENGINE_CMD_FLAG_NUMERIC
},
292 ENGINE_CMD_FLAG_NO_INPUT
},
293 {CAPI_CMD_SET_CSP_IDX
,
296 ENGINE_CMD_FLAG_NUMERIC
},
297 {CAPI_CMD_SET_CSP_NAME
,
299 "Set CSP name, (default CSP used if not specified)",
300 ENGINE_CMD_FLAG_STRING
},
301 {CAPI_CMD_SET_CSP_TYPE
,
303 "Set CSP type, (default RSA_PROV_FULL)",
304 ENGINE_CMD_FLAG_NUMERIC
},
305 {CAPI_CMD_LIST_CONTAINERS
,
307 "list container names",
308 ENGINE_CMD_FLAG_NO_INPUT
},
309 {CAPI_CMD_LIST_OPTIONS
,
311 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
312 "32=private key info)",
313 ENGINE_CMD_FLAG_NUMERIC
},
314 {CAPI_CMD_LOOKUP_METHOD
,
316 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
317 ENGINE_CMD_FLAG_NUMERIC
},
318 {CAPI_CMD_STORE_NAME
,
320 "certificate store name, default \"MY\"",
321 ENGINE_CMD_FLAG_STRING
},
322 {CAPI_CMD_STORE_FLAGS
,
324 "Certificate store flags: 1 = system store",
325 ENGINE_CMD_FLAG_NUMERIC
},
330 static int capi_idx
= -1;
331 static int rsa_capi_idx
= -1;
332 static int dsa_capi_idx
= -1;
333 static int cert_capi_idx
= -1;
335 static int capi_ctrl(ENGINE
*e
, int cmd
, long i
, void *p
, void (*f
) (void))
340 if (capi_idx
== -1) {
341 CAPIerr(CAPI_F_CAPI_CTRL
, CAPI_R_ENGINE_NOT_INITIALIZED
);
344 ctx
= ENGINE_get_ex_data(e
, capi_idx
);
345 out
= BIO_new_fp(stdout
, BIO_NOCLOSE
);
347 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
:
368 OPENSSL_free(ctx
->storename
);
369 ctx
->storename
= OPENSSL_strdup(p
);
370 CAPI_trace(ctx
, "Setting store name to %s\n", p
);
373 case CAPI_CMD_STORE_FLAGS
:
375 ctx
->store_flags
|= CERT_SYSTEM_STORE_LOCAL_MACHINE
;
376 ctx
->store_flags
&= ~CERT_SYSTEM_STORE_CURRENT_USER
;
378 ctx
->store_flags
|= CERT_SYSTEM_STORE_CURRENT_USER
;
379 ctx
->store_flags
&= ~CERT_SYSTEM_STORE_LOCAL_MACHINE
;
381 CAPI_trace(ctx
, "Setting flags to %d\n", i
);
384 case CAPI_CMD_DEBUG_LEVEL
:
385 ctx
->debug_level
= (int)i
;
386 CAPI_trace(ctx
, "Setting debug level to %d\n", ctx
->debug_level
);
389 case CAPI_CMD_DEBUG_FILE
:
390 ctx
->debug_file
= OPENSSL_strdup(p
);
391 CAPI_trace(ctx
, "Setting debug file to %s\n", ctx
->debug_file
);
394 case CAPI_CMD_KEYTYPE
:
396 CAPI_trace(ctx
, "Setting key type to %d\n", ctx
->keytype
);
399 case CAPI_CMD_SET_CSP_IDX
:
400 ret
= capi_ctx_set_provname_idx(ctx
, i
);
403 case CAPI_CMD_LIST_OPTIONS
:
407 case CAPI_CMD_LOOKUP_METHOD
:
408 if (i
< 1 || i
> 3) {
409 CAPIerr(CAPI_F_CAPI_CTRL
, CAPI_R_INVALID_LOOKUP_METHOD
);
413 ctx
->lookup_method
= i
;
416 case CAPI_CMD_SET_CSP_NAME
:
417 ret
= capi_ctx_set_provname(ctx
, p
, ctx
->csptype
, 1);
420 case CAPI_CMD_SET_CSP_TYPE
:
425 CAPIerr(CAPI_F_CAPI_CTRL
, CAPI_R_UNKNOWN_COMMAND
);
434 static RSA_METHOD
*capi_rsa_method
= NULL
;
435 static DSA_METHOD
*capi_dsa_method
= NULL
;
437 static int use_aes_csp
= 0;
439 static int capi_init(ENGINE
*e
)
442 const RSA_METHOD
*ossl_rsa_meth
;
443 const DSA_METHOD
*ossl_dsa_meth
;
447 capi_idx
= ENGINE_get_ex_new_index(0, NULL
, NULL
, NULL
, 0);
451 cert_capi_idx
= X509_get_ex_new_index(0, NULL
, NULL
, NULL
, 0);
453 /* Setup RSA_METHOD */
454 rsa_capi_idx
= RSA_get_ex_new_index(0, NULL
, NULL
, NULL
, 0);
455 ossl_rsa_meth
= RSA_PKCS1_OpenSSL();
456 if ( !RSA_meth_set_pub_enc(capi_rsa_method
,
457 RSA_meth_get_pub_enc(ossl_rsa_meth
))
458 || !RSA_meth_set_pub_dec(capi_rsa_method
,
459 RSA_meth_get_pub_dec(ossl_rsa_meth
))
460 || !RSA_meth_set_priv_enc(capi_rsa_method
, capi_rsa_priv_enc
)
461 || !RSA_meth_set_priv_dec(capi_rsa_method
, capi_rsa_priv_dec
)
462 || !RSA_meth_set_mod_exp(capi_rsa_method
,
463 RSA_meth_get_mod_exp(ossl_rsa_meth
))
464 || !RSA_meth_set_bn_mod_exp(capi_rsa_method
,
465 RSA_meth_get_bn_mod_exp(ossl_rsa_meth
))
466 || !RSA_meth_set_finish(capi_rsa_method
, capi_rsa_free
)
467 || !RSA_meth_set_sign(capi_rsa_method
, capi_rsa_sign
)) {
471 /* Setup DSA Method */
472 dsa_capi_idx
= DSA_get_ex_new_index(0, NULL
, NULL
, NULL
, 0);
473 ossl_dsa_meth
= DSA_OpenSSL();
474 if ( !DSA_meth_set_sign(capi_dsa_method
, capi_dsa_do_sign
)
475 || !DSA_meth_set_verify(capi_dsa_method
,
476 DSA_meth_get_verify(ossl_dsa_meth
))
477 || !DSA_meth_set_finish(capi_dsa_method
, capi_dsa_free
)
478 || !DSA_meth_set_mod_exp(capi_dsa_method
,
479 DSA_meth_get_mod_exp(ossl_dsa_meth
))
480 || !DSA_meth_set_bn_mod_exp(capi_dsa_method
,
481 DSA_meth_get_bn_mod_exp(ossl_dsa_meth
))) {
486 ctx
= capi_ctx_new();
490 ENGINE_set_ex_data(e
, capi_idx
, ctx
);
492 # ifdef OPENSSL_CAPIENG_DIALOG
494 HMODULE cryptui
= LoadLibrary(TEXT("CRYPTUI.DLL"));
495 HMODULE kernel
= GetModuleHandle(TEXT("KERNEL32.DLL"));
498 (CERTDLG
) GetProcAddress(cryptui
,
499 "CryptUIDlgSelectCertificateFromStore");
502 (GETCONSWIN
) GetProcAddress(kernel
, "GetConsoleWindow");
503 if (cryptui
&& !OPENSSL_isservice())
504 ctx
->client_cert_select
= cert_select_dialog
;
508 /* See if we support AES CSP */
510 if (CryptAcquireContext(&hprov
, NULL
, NULL
, PROV_RSA_AES
,
511 CRYPT_VERIFYCONTEXT
)) {
513 CryptReleaseContext(hprov
, 0);
519 CAPIerr(CAPI_F_CAPI_INIT
, ERR_R_MALLOC_FAILURE
);
525 static int capi_destroy(ENGINE
*e
)
527 RSA_meth_free(capi_rsa_method
);
528 capi_rsa_method
= NULL
;
529 DSA_meth_free(capi_dsa_method
);
530 capi_dsa_method
= NULL
;
531 ERR_unload_CAPI_strings();
535 static int capi_finish(ENGINE
*e
)
538 ctx
= ENGINE_get_ex_data(e
, capi_idx
);
540 ENGINE_set_ex_data(e
, capi_idx
, NULL
);
545 * CryptoAPI key application data. This contains a handle to the private key
546 * container (for sign operations) and a handle to the key (for decrypt
551 /* Associated certificate context (if any) */
552 PCCERT_CONTEXT pcert
;
558 static int bind_capi(ENGINE
*e
)
560 capi_rsa_method
= RSA_meth_new("CryptoAPI RSA method", 0);
561 if (capi_rsa_method
== NULL
)
563 capi_dsa_method
= DSA_meth_new("CryptoAPI DSA method", 0);
564 if (capi_dsa_method
== NULL
)
566 if (!ENGINE_set_id(e
, engine_capi_id
)
567 || !ENGINE_set_name(e
, engine_capi_name
)
568 || !ENGINE_set_flags(e
, ENGINE_FLAGS_NO_REGISTER_ALL
)
569 || !ENGINE_set_init_function(e
, capi_init
)
570 || !ENGINE_set_finish_function(e
, capi_finish
)
571 || !ENGINE_set_destroy_function(e
, capi_destroy
)
572 || !ENGINE_set_RSA(e
, capi_rsa_method
)
573 || !ENGINE_set_DSA(e
, capi_dsa_method
)
574 || !ENGINE_set_load_privkey_function(e
, capi_load_privkey
)
575 || !ENGINE_set_load_ssl_client_cert_function(e
,
576 capi_load_ssl_client_cert
)
577 || !ENGINE_set_cmd_defns(e
, capi_cmd_defns
)
578 || !ENGINE_set_ctrl_function(e
, capi_ctrl
))
580 ERR_load_CAPI_strings();
584 RSA_meth_free(capi_rsa_method
);
585 capi_rsa_method
= NULL
;
586 DSA_meth_free(capi_dsa_method
);
587 capi_dsa_method
= NULL
;
591 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
592 static int bind_helper(ENGINE
*e
, const char *id
)
594 if (id
&& (strcmp(id
, engine_capi_id
) != 0))
601 IMPLEMENT_DYNAMIC_CHECK_FN()
602 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper
)
604 static ENGINE
*engine_capi(void)
606 ENGINE
*ret
= ENGINE_new();
609 if (!bind_capi(ret
)) {
616 void int_engine_load_capi(void)
618 /* Copied from eng_[openssl|dyn].c */
619 ENGINE
*toadd
= engine_capi();
628 static int lend_tobn(BIGNUM
*bn
, unsigned char *bin
, int binlen
)
632 * Reverse buffer in place: since this is a keyblob structure that will
633 * be freed up after conversion anyway it doesn't matter if we change
636 for (i
= 0; i
< binlen
/ 2; i
++) {
639 bin
[i
] = bin
[binlen
- i
- 1];
640 bin
[binlen
- i
- 1] = c
;
643 if (!BN_bin2bn(bin
, binlen
, bn
))
648 /* Given a CAPI_KEY get an EVP_PKEY structure */
650 static EVP_PKEY
*capi_get_pkey(ENGINE
*eng
, CAPI_KEY
* key
)
652 unsigned char *pubkey
= NULL
;
657 EVP_PKEY
*ret
= NULL
;
658 if (!CryptExportKey(key
->key
, 0, PUBLICKEYBLOB
, 0, NULL
, &len
)) {
659 CAPIerr(CAPI_F_CAPI_GET_PKEY
, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR
);
664 pubkey
= OPENSSL_malloc(len
);
669 if (!CryptExportKey(key
->key
, 0, PUBLICKEYBLOB
, 0, pubkey
, &len
)) {
670 CAPIerr(CAPI_F_CAPI_GET_PKEY
, CAPI_R_PUBKEY_EXPORT_ERROR
);
675 bh
= (BLOBHEADER
*) pubkey
;
676 if (bh
->bType
!= PUBLICKEYBLOB
) {
677 CAPIerr(CAPI_F_CAPI_GET_PKEY
, CAPI_R_INVALID_PUBLIC_KEY_BLOB
);
680 if (bh
->aiKeyAlg
== CALG_RSA_SIGN
|| bh
->aiKeyAlg
== CALG_RSA_KEYX
) {
683 BIGNUM
*e
= NULL
, *n
= NULL
;
684 unsigned char *rsa_modulus
;
685 rp
= (RSAPUBKEY
*) (bh
+ 1);
686 if (rp
->magic
!= 0x31415352) {
688 BIO_snprintf(magstr
, 10, "%lx", rp
->magic
);
689 CAPIerr(CAPI_F_CAPI_GET_PKEY
,
690 CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER
);
691 ERR_add_error_data(2, "magic=0x", magstr
);
694 rsa_modulus
= (unsigned char *)(rp
+ 1);
695 rkey
= RSA_new_method(eng
);
702 if (e
== NULL
|| n
== NULL
) {
708 RSA_set0_key(rkey
, n
, e
, NULL
);
710 if (!BN_set_word(e
, rp
->pubexp
))
713 rsa_modlen
= rp
->bitlen
/ 8;
714 if (!lend_tobn(n
, rsa_modulus
, rsa_modlen
))
717 RSA_set_ex_data(rkey
, rsa_capi_idx
, key
);
719 if ((ret
= EVP_PKEY_new()) == NULL
)
722 EVP_PKEY_assign_RSA(ret
, rkey
);
725 } else if (bh
->aiKeyAlg
== CALG_DSS_SIGN
) {
729 BIGNUM
*p
, *q
, *g
, *pub_key
;
730 dp
= (DSSPUBKEY
*) (bh
+ 1);
731 if (dp
->magic
!= 0x31535344) {
733 BIO_snprintf(magstr
, 10, "%lx", dp
->magic
);
734 CAPIerr(CAPI_F_CAPI_GET_PKEY
,
735 CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER
);
736 ERR_add_error_data(2, "magic=0x", magstr
);
739 dsa_plen
= dp
->bitlen
/ 8;
740 btmp
= (unsigned char *)(dp
+ 1);
741 dkey
= DSA_new_method(eng
);
748 if (p
== NULL
|| q
== NULL
|| g
== NULL
|| pub_key
== NULL
) {
755 DSA_set0_pqg(dkey
, p
, q
, g
);
756 DSA_set0_key(dkey
, pub_key
, NULL
);
757 if (!lend_tobn(p
, btmp
, dsa_plen
))
760 if (!lend_tobn(q
, btmp
, 20))
763 if (!lend_tobn(g
, btmp
, dsa_plen
))
766 if (!lend_tobn(pub_key
, btmp
, dsa_plen
))
770 DSA_set_ex_data(dkey
, dsa_capi_idx
, key
);
772 if ((ret
= EVP_PKEY_new()) == NULL
)
775 EVP_PKEY_assign_DSA(ret
, dkey
);
779 BIO_snprintf(algstr
, 10, "%ux", bh
->aiKeyAlg
);
780 CAPIerr(CAPI_F_CAPI_GET_PKEY
,
781 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM
);
782 ERR_add_error_data(2, "aiKeyAlg=0x", algstr
);
787 OPENSSL_free(pubkey
);
796 CAPIerr(CAPI_F_CAPI_GET_PKEY
, ERR_R_MALLOC_FAILURE
);
801 static EVP_PKEY
*capi_load_privkey(ENGINE
*eng
, const char *key_id
,
802 UI_METHOD
*ui_method
, void *callback_data
)
807 ctx
= ENGINE_get_ex_data(eng
, capi_idx
);
810 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY
, CAPI_R_CANT_FIND_CAPI_CONTEXT
);
814 key
= capi_find_key(ctx
, key_id
);
819 ret
= capi_get_pkey(eng
, key
);
827 /* CryptoAPI RSA operations */
829 int capi_rsa_priv_enc(int flen
, const unsigned char *from
,
830 unsigned char *to
, RSA
*rsa
, int padding
)
832 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC
, CAPI_R_FUNCTION_NOT_SUPPORTED
);
836 int capi_rsa_sign(int dtype
, const unsigned char *m
, unsigned int m_len
,
837 unsigned char *sigret
, unsigned int *siglen
, const RSA
*rsa
)
847 ctx
= ENGINE_get_ex_data(RSA_get0_engine(rsa
), capi_idx
);
849 CAPI_trace(ctx
, "Called CAPI_rsa_sign()\n");
851 capi_key
= RSA_get_ex_data(rsa
, rsa_capi_idx
);
853 CAPIerr(CAPI_F_CAPI_RSA_SIGN
, CAPI_R_CANT_GET_KEY
);
856 /* Convert the signature type to a CryptoAPI algorithm ID */
879 alg
= CALG_SSL3_SHAMD5
;
884 BIO_snprintf(algstr
, 10, "%x", dtype
);
885 CAPIerr(CAPI_F_CAPI_RSA_SIGN
, CAPI_R_UNSUPPORTED_ALGORITHM_NID
);
886 ERR_add_error_data(2, "NID=0x", algstr
);
891 /* Create the hash object */
892 if (!CryptCreateHash(capi_key
->hprov
, alg
, 0, 0, &hash
)) {
893 CAPIerr(CAPI_F_CAPI_RSA_SIGN
, CAPI_R_CANT_CREATE_HASH_OBJECT
);
897 /* Set the hash value to the value passed */
899 if (!CryptSetHashParam(hash
, HP_HASHVAL
, (unsigned char *)m
, 0)) {
900 CAPIerr(CAPI_F_CAPI_RSA_SIGN
, CAPI_R_CANT_SET_HASH_VALUE
);
905 /* Finally sign it */
906 slen
= RSA_size(rsa
);
907 if (!CryptSignHash(hash
, capi_key
->keyspec
, NULL
, 0, sigret
, &slen
)) {
908 CAPIerr(CAPI_F_CAPI_RSA_SIGN
, CAPI_R_ERROR_SIGNING_HASH
);
913 /* Inplace byte reversal of signature */
914 for (i
= 0; i
< slen
/ 2; i
++) {
917 sigret
[i
] = sigret
[slen
- i
- 1];
918 sigret
[slen
- i
- 1] = c
;
926 CryptDestroyHash(hash
);
931 int capi_rsa_priv_dec(int flen
, const unsigned char *from
,
932 unsigned char *to
, RSA
*rsa
, int padding
)
935 unsigned char *tmpbuf
;
943 ctx
= ENGINE_get_ex_data(RSA_get0_engine(rsa
), capi_idx
);
945 CAPI_trace(ctx
, "Called capi_rsa_priv_dec()\n");
947 capi_key
= RSA_get_ex_data(rsa
, rsa_capi_idx
);
949 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC
, CAPI_R_CANT_GET_KEY
);
953 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
)) == NULL
) {
963 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC
, ERR_R_MALLOC_FAILURE
);
966 for (i
= 0; i
< flen
; i
++)
967 tmpbuf
[flen
- i
- 1] = from
[i
];
969 /* Finally decrypt it */
971 if (!CryptDecrypt(capi_key
->key
, 0, TRUE
, 0, tmpbuf
, &dlen
)) {
972 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC
, CAPI_R_DECRYPT_ERROR
);
974 OPENSSL_free(tmpbuf
);
977 memcpy(to
, tmpbuf
, (flen
= (int)dlen
));
979 OPENSSL_free(tmpbuf
);
984 static int capi_rsa_free(RSA
*rsa
)
987 capi_key
= RSA_get_ex_data(rsa
, rsa_capi_idx
);
988 capi_free_key(capi_key
);
989 RSA_set_ex_data(rsa
, rsa_capi_idx
, 0);
993 /* CryptoAPI DSA operations */
995 static DSA_SIG
*capi_dsa_do_sign(const unsigned char *digest
, int dlen
,
1000 DSA_SIG
*ret
= NULL
;
1003 unsigned char csigbuf
[40];
1005 ctx
= ENGINE_get_ex_data(DSA_get0_engine(dsa
), capi_idx
);
1007 CAPI_trace(ctx
, "Called CAPI_dsa_do_sign()\n");
1009 capi_key
= DSA_get_ex_data(dsa
, dsa_capi_idx
);
1012 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN
, CAPI_R_CANT_GET_KEY
);
1017 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN
, CAPI_R_INVALID_DIGEST_LENGTH
);
1021 /* Create the hash object */
1022 if (!CryptCreateHash(capi_key
->hprov
, CALG_SHA1
, 0, 0, &hash
)) {
1023 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN
, CAPI_R_CANT_CREATE_HASH_OBJECT
);
1024 capi_addlasterror();
1028 /* Set the hash value to the value passed */
1029 if (!CryptSetHashParam(hash
, HP_HASHVAL
, (unsigned char *)digest
, 0)) {
1030 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN
, CAPI_R_CANT_SET_HASH_VALUE
);
1031 capi_addlasterror();
1035 /* Finally sign it */
1036 slen
= sizeof(csigbuf
);
1037 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();
1042 BIGNUM
*r
= NULL
, *s
= NULL
;
1043 ret
= DSA_SIG_new();
1046 DSA_SIG_get0(&r
, &s
, ret
);
1047 if (!lend_tobn(r
, csigbuf
, 20)
1048 || !lend_tobn(s
, csigbuf
+ 20, 20)) {
1058 OPENSSL_cleanse(csigbuf
, 40);
1059 CryptDestroyHash(hash
);
1063 static int capi_dsa_free(DSA
*dsa
)
1066 capi_key
= DSA_get_ex_data(dsa
, dsa_capi_idx
);
1067 capi_free_key(capi_key
);
1068 DSA_set_ex_data(dsa
, dsa_capi_idx
, 0);
1072 static void capi_vtrace(CAPI_CTX
* ctx
, int level
, char *format
,
1077 if (!ctx
|| (ctx
->debug_level
< level
) || (!ctx
->debug_file
))
1079 out
= BIO_new_file(ctx
->debug_file
, "a+");
1081 CAPIerr(CAPI_F_CAPI_VTRACE
, CAPI_R_FILE_OPEN_ERROR
);
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
);
1118 CAPIerr(CAPI_F_WIDE_TO_ASC
, CAPI_R_WIN32_ERROR
);
1121 str
= OPENSSL_malloc(sz
);
1123 CAPIerr(CAPI_F_WIDE_TO_ASC
, ERR_R_MALLOC_FAILURE
);
1126 if (!WideCharToMultiByte(CP_ACP
, 0, wstr
, len_0
, str
, sz
, NULL
, NULL
)) {
1128 CAPIerr(CAPI_F_WIDE_TO_ASC
, CAPI_R_WIN32_ERROR
);
1134 static int capi_get_provname(CAPI_CTX
* ctx
, LPSTR
* pname
, DWORD
* ptype
,
1139 CAPI_trace(ctx
, "capi_get_provname, index=%d\n", idx
);
1140 if (!CryptEnumProviders(idx
, NULL
, 0, ptype
, NULL
, &len
)) {
1141 err
= GetLastError();
1142 if (err
== ERROR_NO_MORE_ITEMS
)
1144 CAPIerr(CAPI_F_CAPI_GET_PROVNAME
, CAPI_R_CRYPTENUMPROVIDERS_ERROR
);
1148 name
= OPENSSL_malloc(len
);
1150 CAPIerr(CAPI_F_CAPI_GET_PROVNAME
, ERR_R_MALLOC_FAILURE
);
1153 if (!CryptEnumProviders(idx
, NULL
, 0, ptype
, name
, &len
)) {
1154 err
= GetLastError();
1156 if (err
== ERROR_NO_MORE_ITEMS
)
1158 CAPIerr(CAPI_F_CAPI_GET_PROVNAME
, CAPI_R_CRYPTENUMPROVIDERS_ERROR
);
1162 if (sizeof(TCHAR
) != sizeof(char)) {
1163 *pname
= wide_to_asc((WCHAR
*)name
);
1168 *pname
= (char *)name
;
1169 CAPI_trace(ctx
, "capi_get_provname, returned name=%s, type=%d\n", *pname
,
1175 static int capi_list_providers(CAPI_CTX
* ctx
, BIO
*out
)
1179 LPSTR provname
= NULL
;
1180 CAPI_trace(ctx
, "capi_list_providers\n");
1181 BIO_printf(out
, "Available CSPs:\n");
1182 for (idx
= 0;; idx
++) {
1183 ret
= capi_get_provname(ctx
, &provname
, &ptype
, idx
);
1188 BIO_printf(out
, "%lu. %s, type %lu\n", idx
, provname
, ptype
);
1189 OPENSSL_free(provname
);
1194 static int capi_list_containers(CAPI_CTX
* ctx
, BIO
*out
)
1198 DWORD err
, idx
, flags
, buflen
= 0, clen
;
1200 LPTSTR cspname
= NULL
;
1202 CAPI_trace(ctx
, "Listing containers CSP=%s, type = %d\n", ctx
->cspname
,
1204 if (ctx
->cspname
&& sizeof(TCHAR
) != sizeof(char)) {
1206 MultiByteToWideChar(CP_ACP
, 0, ctx
->cspname
, -1, NULL
, 0))) {
1207 cspname
= alloca(clen
* sizeof(WCHAR
));
1208 MultiByteToWideChar(CP_ACP
, 0, ctx
->cspname
, -1, (WCHAR
*)cspname
,
1212 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS
, ERR_R_MALLOC_FAILURE
);
1213 capi_addlasterror();
1217 cspname
= (TCHAR
*)ctx
->cspname
;
1218 if (!CryptAcquireContext
1219 (&hprov
, NULL
, cspname
, ctx
->csptype
, CRYPT_VERIFYCONTEXT
)) {
1220 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS
,
1221 CAPI_R_CRYPTACQUIRECONTEXT_ERROR
);
1222 capi_addlasterror();
1225 if (!CryptGetProvParam
1226 (hprov
, PP_ENUMCONTAINERS
, NULL
, &buflen
, CRYPT_FIRST
)) {
1227 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS
, CAPI_R_ENUMCONTAINERS_ERROR
);
1228 capi_addlasterror();
1229 CryptReleaseContext(hprov
, 0);
1232 CAPI_trace(ctx
, "Got max container len %d\n", buflen
);
1235 cname
= OPENSSL_malloc(buflen
);
1236 if (cname
== NULL
) {
1237 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS
, ERR_R_MALLOC_FAILURE
);
1241 for (idx
= 0;; idx
++) {
1246 flags
= CRYPT_FIRST
;
1249 if (!CryptGetProvParam
1250 (hprov
, PP_ENUMCONTAINERS
, (BYTE
*) cname
, &clen
, flags
)) {
1251 err
= GetLastError();
1252 if (err
== ERROR_NO_MORE_ITEMS
)
1254 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS
, CAPI_R_ENUMCONTAINERS_ERROR
);
1258 CAPI_trace(ctx
, "Container name %s, len=%d, index=%d, flags=%d\n",
1259 cname
, clen
, idx
, flags
);
1260 if (!cname
[0] && (clen
== buflen
)) {
1261 CAPI_trace(ctx
, "Enumerate bug: using workaround\n");
1264 BIO_printf(out
, "%lu. %s\n", idx
, cname
);
1271 OPENSSL_free(cname
);
1272 CryptReleaseContext(hprov
, 0);
1277 static CRYPT_KEY_PROV_INFO
*capi_get_prov_info(CAPI_CTX
* ctx
, PCCERT_CONTEXT cert
)
1280 CRYPT_KEY_PROV_INFO
*pinfo
;
1282 if (!CertGetCertificateContextProperty
1283 (cert
, CERT_KEY_PROV_INFO_PROP_ID
, NULL
, &len
))
1285 pinfo
= OPENSSL_malloc(len
);
1286 if (pinfo
== NULL
) {
1287 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO
, ERR_R_MALLOC_FAILURE
);
1290 if (!CertGetCertificateContextProperty
1291 (cert
, CERT_KEY_PROV_INFO_PROP_ID
, pinfo
, &len
)) {
1292 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO
,
1293 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO
);
1294 capi_addlasterror();
1295 OPENSSL_free(pinfo
);
1301 static void capi_dump_prov_info(CAPI_CTX
* ctx
, BIO
*out
,
1302 CRYPT_KEY_PROV_INFO
* pinfo
)
1304 char *provname
= NULL
, *contname
= NULL
;
1306 BIO_printf(out
, " No Private Key\n");
1309 provname
= wide_to_asc(pinfo
->pwszProvName
);
1310 contname
= wide_to_asc(pinfo
->pwszContainerName
);
1311 if (!provname
|| !contname
)
1314 BIO_printf(out
, " Private Key Info:\n");
1315 BIO_printf(out
, " Provider Name: %s, Provider Type %lu\n", provname
,
1317 BIO_printf(out
, " Container Name: %s, Key Type %lu\n", contname
,
1320 OPENSSL_free(provname
);
1321 OPENSSL_free(contname
);
1324 static char *capi_cert_get_fname(CAPI_CTX
* ctx
, PCCERT_CONTEXT cert
)
1329 CAPI_trace(ctx
, "capi_cert_get_fname\n");
1330 if (!CertGetCertificateContextProperty
1331 (cert
, CERT_FRIENDLY_NAME_PROP_ID
, NULL
, &dlen
))
1333 wfname
= OPENSSL_malloc(dlen
);
1336 if (CertGetCertificateContextProperty
1337 (cert
, CERT_FRIENDLY_NAME_PROP_ID
, wfname
, &dlen
)) {
1338 char *fname
= wide_to_asc(wfname
);
1339 OPENSSL_free(wfname
);
1342 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME
, CAPI_R_ERROR_GETTING_FRIENDLY_NAME
);
1343 capi_addlasterror();
1345 OPENSSL_free(wfname
);
1349 static void capi_dump_cert(CAPI_CTX
* ctx
, BIO
*out
, PCCERT_CONTEXT cert
)
1352 const unsigned char *p
;
1353 unsigned long flags
= ctx
->dump_flags
;
1354 if (flags
& CAPI_DMP_FNAME
) {
1356 fname
= capi_cert_get_fname(ctx
, cert
);
1358 BIO_printf(out
, " Friendly Name \"%s\"\n", fname
);
1359 OPENSSL_free(fname
);
1361 BIO_printf(out
, " <No Friendly Name>\n");
1364 p
= cert
->pbCertEncoded
;
1365 x
= d2i_X509(NULL
, &p
, cert
->cbCertEncoded
);
1367 BIO_printf(out
, " <Can't parse certificate>\n");
1368 if (flags
& CAPI_DMP_SUMMARY
) {
1369 BIO_printf(out
, " Subject: ");
1370 X509_NAME_print_ex(out
, X509_get_subject_name(x
), 0, XN_FLAG_ONELINE
);
1371 BIO_printf(out
, "\n Issuer: ");
1372 X509_NAME_print_ex(out
, X509_get_issuer_name(x
), 0, XN_FLAG_ONELINE
);
1373 BIO_printf(out
, "\n");
1375 if (flags
& CAPI_DMP_FULL
)
1376 X509_print_ex(out
, x
, XN_FLAG_ONELINE
, 0);
1378 if (flags
& CAPI_DMP_PKEYINFO
) {
1379 CRYPT_KEY_PROV_INFO
*pinfo
;
1380 pinfo
= capi_get_prov_info(ctx
, cert
);
1381 capi_dump_prov_info(ctx
, out
, pinfo
);
1382 OPENSSL_free(pinfo
);
1385 if (flags
& CAPI_DMP_PEM
)
1386 PEM_write_bio_X509(out
, x
);
1390 static HCERTSTORE
capi_open_store(CAPI_CTX
* ctx
, char *storename
)
1395 storename
= ctx
->storename
;
1398 CAPI_trace(ctx
, "Opening certificate store %s\n", storename
);
1400 hstore
= CertOpenStore(CERT_STORE_PROV_SYSTEM_A
, 0, 0,
1401 ctx
->store_flags
, storename
);
1403 CAPIerr(CAPI_F_CAPI_OPEN_STORE
, CAPI_R_ERROR_OPENING_STORE
);
1404 capi_addlasterror();
1409 int capi_list_certs(CAPI_CTX
* ctx
, BIO
*out
, char *id
)
1415 PCCERT_CONTEXT cert
= NULL
;
1417 storename
= ctx
->storename
;
1420 CAPI_trace(ctx
, "Listing certs for store %s\n", storename
);
1422 hstore
= capi_open_store(ctx
, storename
);
1426 cert
= capi_find_cert(ctx
, id
, hstore
);
1431 capi_dump_cert(ctx
, out
, cert
);
1432 CertFreeCertificateContext(cert
);
1434 for (idx
= 0;; idx
++) {
1435 cert
= CertEnumCertificatesInStore(hstore
, cert
);
1438 BIO_printf(out
, "Certificate %d\n", idx
);
1439 capi_dump_cert(ctx
, out
, cert
);
1443 CertCloseStore(hstore
, 0);
1447 static PCCERT_CONTEXT
capi_find_cert(CAPI_CTX
* ctx
, const char *id
,
1450 PCCERT_CONTEXT cert
= NULL
;
1453 switch (ctx
->lookup_method
) {
1454 case CAPI_LU_SUBSTR
:
1455 return CertFindCertificateInStore(hstore
,
1456 X509_ASN_ENCODING
, 0,
1457 CERT_FIND_SUBJECT_STR_A
, id
, NULL
);
1460 cert
= CertEnumCertificatesInStore(hstore
, cert
);
1463 fname
= capi_cert_get_fname(ctx
, cert
);
1465 if (strcmp(fname
, id
))
1469 OPENSSL_free(fname
);
1479 static CAPI_KEY
*capi_get_key(CAPI_CTX
* ctx
, const TCHAR
*contname
,
1480 TCHAR
*provname
, DWORD ptype
, DWORD keyspec
)
1483 CAPI_KEY
*key
= OPENSSL_malloc(sizeof(*key
));
1487 /* If PROV_RSA_AES supported use it instead */
1488 if (ptype
== PROV_RSA_FULL
&& use_aes_csp
) {
1490 ptype
= PROV_RSA_AES
;
1491 CAPI_trace(ctx
, "capi_get_key, contname=%s, RSA_AES_CSP\n", contname
);
1492 } else if (sizeof(TCHAR
) == sizeof(char)) {
1493 CAPI_trace(ctx
, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1494 contname
, provname
, ptype
);
1495 } else if (ctx
&& ctx
->debug_level
>= CAPI_DBG_TRACE
&& ctx
->debug_file
) {
1496 /* above 'if' is optimization to minimize malloc-ations */
1497 char *_contname
= wide_to_asc((WCHAR
*)contname
);
1498 char *_provname
= wide_to_asc((WCHAR
*)provname
);
1500 CAPI_trace(ctx
, "capi_get_key, contname=%s, provname=%s, type=%d\n",
1501 _contname
, _provname
, ptype
);
1502 OPENSSL_free(_provname
);
1503 OPENSSL_free(_contname
);
1505 if (ctx
->store_flags
& CERT_SYSTEM_STORE_LOCAL_MACHINE
)
1506 dwFlags
= CRYPT_MACHINE_KEYSET
;
1507 if (!CryptAcquireContext(&key
->hprov
, contname
, provname
, ptype
, dwFlags
)) {
1508 CAPIerr(CAPI_F_CAPI_GET_KEY
, CAPI_R_CRYPTACQUIRECONTEXT_ERROR
);
1509 capi_addlasterror();
1512 if (!CryptGetUserKey(key
->hprov
, keyspec
, &key
->key
)) {
1513 CAPIerr(CAPI_F_CAPI_GET_KEY
, CAPI_R_GETUSERKEY_ERROR
);
1514 capi_addlasterror();
1515 CryptReleaseContext(key
->hprov
, 0);
1518 key
->keyspec
= keyspec
;
1527 static CAPI_KEY
*capi_get_cert_key(CAPI_CTX
* ctx
, PCCERT_CONTEXT cert
)
1529 CAPI_KEY
*key
= NULL
;
1530 CRYPT_KEY_PROV_INFO
*pinfo
= NULL
;
1531 char *provname
= NULL
, *contname
= NULL
;
1532 pinfo
= capi_get_prov_info(ctx
, cert
);
1535 if (sizeof(TCHAR
) != sizeof(char))
1536 key
= capi_get_key(ctx
, (TCHAR
*)pinfo
->pwszContainerName
,
1537 (TCHAR
*)pinfo
->pwszProvName
,
1538 pinfo
->dwProvType
, pinfo
->dwKeySpec
);
1540 provname
= wide_to_asc(pinfo
->pwszProvName
);
1541 contname
= wide_to_asc(pinfo
->pwszContainerName
);
1542 if (!provname
|| !contname
)
1544 key
= capi_get_key(ctx
, (TCHAR
*)contname
, (TCHAR
*)provname
,
1545 pinfo
->dwProvType
, pinfo
->dwKeySpec
);
1549 OPENSSL_free(pinfo
);
1550 OPENSSL_free(provname
);
1551 OPENSSL_free(contname
);
1555 CAPI_KEY
*capi_find_key(CAPI_CTX
* ctx
, const char *id
)
1557 PCCERT_CONTEXT cert
;
1559 CAPI_KEY
*key
= NULL
;
1560 switch (ctx
->lookup_method
) {
1561 case CAPI_LU_SUBSTR
:
1563 hstore
= capi_open_store(ctx
, NULL
);
1566 cert
= capi_find_cert(ctx
, id
, hstore
);
1568 key
= capi_get_cert_key(ctx
, cert
);
1569 CertFreeCertificateContext(cert
);
1571 CertCloseStore(hstore
, 0);
1574 case CAPI_LU_CONTNAME
:
1575 if (sizeof(TCHAR
) != sizeof(char)) {
1576 WCHAR
*contname
, *provname
;
1579 if ((len
= MultiByteToWideChar(CP_ACP
, 0, id
, -1, NULL
, 0)) &&
1580 (contname
= alloca(len
* sizeof(WCHAR
)),
1581 MultiByteToWideChar(CP_ACP
, 0, id
, -1, contname
, len
)) &&
1583 MultiByteToWideChar(CP_ACP
, 0, ctx
->cspname
, -1, NULL
, 0))
1585 alloca(len
* sizeof(WCHAR
)), MultiByteToWideChar(CP_ACP
,
1592 capi_get_key(ctx
, (TCHAR
*)contname
, (TCHAR
*)provname
,
1593 ctx
->csptype
, ctx
->keytype
);
1595 key
= capi_get_key(ctx
, (TCHAR
*)id
,
1596 (TCHAR
*)ctx
->cspname
,
1597 ctx
->csptype
, ctx
->keytype
);
1604 void capi_free_key(CAPI_KEY
* key
)
1608 CryptDestroyKey(key
->key
);
1609 CryptReleaseContext(key
->hprov
, 0);
1611 CertFreeCertificateContext(key
->pcert
);
1615 /* Initialize a CAPI_CTX structure */
1617 static CAPI_CTX
*capi_ctx_new(void)
1619 CAPI_CTX
*ctx
= OPENSSL_zalloc(sizeof(*ctx
));
1622 CAPIerr(CAPI_F_CAPI_CTX_NEW
, ERR_R_MALLOC_FAILURE
);
1625 ctx
->csptype
= PROV_RSA_FULL
;
1626 ctx
->dump_flags
= CAPI_DMP_SUMMARY
| CAPI_DMP_FNAME
;
1627 ctx
->keytype
= AT_KEYEXCHANGE
;
1628 ctx
->store_flags
= CERT_STORE_OPEN_EXISTING_FLAG
|
1629 CERT_STORE_READONLY_FLAG
| CERT_SYSTEM_STORE_CURRENT_USER
;
1630 ctx
->lookup_method
= CAPI_LU_SUBSTR
;
1631 ctx
->client_cert_select
= cert_select_simple
;
1635 static void capi_ctx_free(CAPI_CTX
* ctx
)
1637 CAPI_trace(ctx
, "Calling capi_ctx_free with %lx\n", ctx
);
1640 OPENSSL_free(ctx
->cspname
);
1641 OPENSSL_free(ctx
->debug_file
);
1642 OPENSSL_free(ctx
->storename
);
1643 OPENSSL_free(ctx
->ssl_client_store
);
1647 static int capi_ctx_set_provname(CAPI_CTX
* ctx
, LPSTR pname
, DWORD type
,
1650 CAPI_trace(ctx
, "capi_ctx_set_provname, name=%s, type=%d\n", pname
, type
);
1655 if (sizeof(TCHAR
) != sizeof(char)) {
1657 if ((len
= MultiByteToWideChar(CP_ACP
, 0, pname
, -1, NULL
, 0))) {
1658 name
= alloca(len
* sizeof(WCHAR
));
1659 MultiByteToWideChar(CP_ACP
, 0, pname
, -1, (WCHAR
*)name
, len
);
1662 name
= (TCHAR
*)pname
;
1664 if (!name
|| !CryptAcquireContext(&hprov
, NULL
, name
, type
,
1665 CRYPT_VERIFYCONTEXT
)) {
1666 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME
,
1667 CAPI_R_CRYPTACQUIRECONTEXT_ERROR
);
1668 capi_addlasterror();
1671 CryptReleaseContext(hprov
, 0);
1673 OPENSSL_free(ctx
->cspname
);
1674 ctx
->cspname
= OPENSSL_strdup(pname
);
1675 ctx
->csptype
= type
;
1679 static int capi_ctx_set_provname_idx(CAPI_CTX
* ctx
, int idx
)
1684 if (capi_get_provname(ctx
, &pname
, &type
, idx
) != 1)
1686 res
= capi_ctx_set_provname(ctx
, pname
, type
, 0);
1687 OPENSSL_free(pname
);
1691 static int cert_issuer_match(STACK_OF(X509_NAME
) *ca_dn
, X509
*x
)
1695 /* Special case: empty list: match anything */
1696 if (sk_X509_NAME_num(ca_dn
) <= 0)
1698 for (i
= 0; i
< sk_X509_NAME_num(ca_dn
); i
++) {
1699 nm
= sk_X509_NAME_value(ca_dn
, i
);
1700 if (!X509_NAME_cmp(nm
, X509_get_issuer_name(x
)))
1706 static int capi_load_ssl_client_cert(ENGINE
*e
, SSL
*ssl
,
1707 STACK_OF(X509_NAME
) *ca_dn
, X509
**pcert
,
1708 EVP_PKEY
**pkey
, STACK_OF(X509
) **pother
,
1709 UI_METHOD
*ui_method
,
1710 void *callback_data
)
1712 STACK_OF(X509
) *certs
= NULL
;
1715 const unsigned char *p
;
1716 int i
, client_cert_idx
;
1718 PCCERT_CONTEXT cert
= NULL
, excert
= NULL
;
1721 ctx
= ENGINE_get_ex_data(e
, capi_idx
);
1726 storename
= ctx
->ssl_client_store
;
1730 hstore
= capi_open_store(ctx
, storename
);
1733 /* Enumerate all certificates collect any matches */
1735 cert
= CertEnumCertificatesInStore(hstore
, cert
);
1738 p
= cert
->pbCertEncoded
;
1739 x
= d2i_X509(NULL
, &p
, cert
->cbCertEncoded
);
1741 CAPI_trace(ctx
, "Can't Parse Certificate %d\n", i
);
1744 if (cert_issuer_match(ca_dn
, x
)
1745 && X509_check_purpose(x
, X509_PURPOSE_SSL_CLIENT
, 0)) {
1746 key
= capi_get_cert_key(ctx
, cert
);
1752 * Match found: attach extra data to it so we can retrieve the
1755 excert
= CertDuplicateCertificateContext(cert
);
1756 key
->pcert
= excert
;
1757 X509_set_ex_data(x
, cert_capi_idx
, key
);
1760 certs
= sk_X509_new_null();
1762 sk_X509_push(certs
, x
);
1769 CertFreeCertificateContext(cert
);
1771 CertCloseStore(hstore
, 0);
1776 /* Select the appropriate certificate */
1778 client_cert_idx
= ctx
->client_cert_select(e
, ssl
, certs
);
1780 /* Set the selected certificate and free the rest */
1782 for (i
= 0; i
< sk_X509_num(certs
); i
++) {
1783 x
= sk_X509_value(certs
, i
);
1784 if (i
== client_cert_idx
)
1787 key
= X509_get_ex_data(x
, cert_capi_idx
);
1793 sk_X509_free(certs
);
1798 /* Setup key for selected certificate */
1800 key
= X509_get_ex_data(*pcert
, cert_capi_idx
);
1801 *pkey
= capi_get_pkey(e
, key
);
1802 X509_set_ex_data(*pcert
, cert_capi_idx
, NULL
);
1808 /* Simple client cert selection function: always select first */
1810 static int cert_select_simple(ENGINE
*e
, SSL
*ssl
, STACK_OF(X509
) *certs
)
1815 # ifdef OPENSSL_CAPIENG_DIALOG
1818 * More complex cert selection function, using standard function
1819 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1823 * Definitions which are in cryptuiapi.h but this is not present in older
1824 * versions of headers.
1827 # ifndef CRYPTUI_SELECT_LOCATION_COLUMN
1828 # define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010
1829 # define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004
1832 # define dlg_title L"OpenSSL Application SSL Client Certificate Selection"
1833 # define dlg_prompt L"Select a certificate to use for authentication"
1834 # define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \
1835 |CRYPTUI_SELECT_INTENDEDUSE_COLUMN
1837 static int cert_select_dialog(ENGINE
*e
, SSL
*ssl
, STACK_OF(X509
) *certs
)
1841 PCCERT_CONTEXT cert
;
1846 if (sk_X509_num(certs
) == 1)
1848 ctx
= ENGINE_get_ex_data(e
, capi_idx
);
1849 /* Create an in memory store of certificates */
1850 dstore
= CertOpenStore(CERT_STORE_PROV_MEMORY
, 0, 0,
1851 CERT_STORE_CREATE_NEW_FLAG
, NULL
);
1853 CAPIerr(CAPI_F_CERT_SELECT_DIALOG
, CAPI_R_ERROR_CREATING_STORE
);
1854 capi_addlasterror();
1857 /* Add all certificates to store */
1858 for (i
= 0; i
< sk_X509_num(certs
); i
++) {
1859 x
= sk_X509_value(certs
, i
);
1860 key
= X509_get_ex_data(x
, cert_capi_idx
);
1862 if (!CertAddCertificateContextToStore(dstore
, key
->pcert
,
1863 CERT_STORE_ADD_NEW
, NULL
)) {
1864 CAPIerr(CAPI_F_CERT_SELECT_DIALOG
, CAPI_R_ERROR_ADDING_CERT
);
1865 capi_addlasterror();
1870 hwnd
= GetForegroundWindow();
1872 hwnd
= GetActiveWindow();
1873 if (!hwnd
&& ctx
->getconswindow
)
1874 hwnd
= ctx
->getconswindow();
1875 /* Call dialog to select one */
1876 cert
= ctx
->certselectdlg(dstore
, hwnd
, dlg_title
, dlg_prompt
,
1877 dlg_columns
, 0, NULL
);
1879 /* Find matching cert from list */
1881 for (i
= 0; i
< sk_X509_num(certs
); i
++) {
1882 x
= sk_X509_value(certs
, i
);
1883 key
= X509_get_ex_data(x
, cert_capi_idx
);
1884 if (CertCompareCertificate
1885 (X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, cert
->pCertInfo
,
1886 key
->pcert
->pCertInfo
)) {
1895 CertCloseStore(dstore
, 0);
1901 #else /* !__COMPILE_CAPIENG */
1902 # include <openssl/engine.h>
1903 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
1905 int bind_engine(ENGINE
*e
, const char *id
, const dynamic_fns
*fns
);
1907 int bind_engine(ENGINE
*e
, const char *id
, const dynamic_fns
*fns
)
1912 IMPLEMENT_DYNAMIC_CHECK_FN()
1914 void int_engine_load_capi(void);
1915 void int_engine_load_capi(void)