]> git.ipfire.org Git - thirdparty/openssl.git/blame - engines/e_capi.c
Add support for Windoes dialog box based certificate selection.
[thirdparty/openssl.git] / engines / e_capi.c
CommitLineData
7a18ecb2
DSH
1/* engines/e_capi.c */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project.
4 */
5/* ====================================================================
6 * Copyright (c) 2008 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
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
18 * distribution.
19 *
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/)"
24 *
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.
29 *
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.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
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 * ====================================================================
52 */
53
54
55#include <stdio.h>
56#include <string.h>
57#include <openssl/crypto.h>
58#include <openssl/buffer.h>
59#include <openssl/engine.h>
60#include <openssl/rsa.h>
61#include <openssl/bn.h>
62#include <openssl/pem.h>
63
64#ifdef OPENSSL_SYS_WIN32
65#ifndef OPENSSL_NO_CAPIENG
66
67#ifndef _WIN32_WINNT
68#define _WIN32_WINNT 0x400
69#endif
70
f79262e9
BL
71#include <windows.h>
72#include <wincrypt.h>
7a18ecb2 73
37cf49a3
DSH
74#undef X509_NAME
75
7a18ecb2
DSH
76#include "e_capi_err.h"
77#include "e_capi_err.c"
78
79
80static const char *engine_capi_id = "capi";
81static const char *engine_capi_name = "CryptoAPI ENGINE";
82
83typedef struct CAPI_CTX_st CAPI_CTX;
84typedef struct CAPI_KEY_st CAPI_KEY;
85
86static void capi_addlasterror(void);
87static void capi_adderror(DWORD err);
88
89static void CAPI_trace(CAPI_CTX *ctx, char *format, ...);
90
91static int capi_list_providers(CAPI_CTX *ctx, BIO *out);
92static int capi_list_containers(CAPI_CTX *ctx, BIO *out);
93int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *storename);
94void capi_free_key(CAPI_KEY *key);
e0f7b872 95static int client_cert_select(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
7a18ecb2
DSH
96
97static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore);
98
99CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id);
100
101static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
102 UI_METHOD *ui_method, void *callback_data);
103static int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
104 unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
105static int capi_rsa_priv_enc(int flen, const unsigned char *from,
106 unsigned char *to, RSA *rsa, int padding);
107static int capi_rsa_priv_dec(int flen, const unsigned char *from,
108 unsigned char *to, RSA *rsa, int padding);
109static int capi_rsa_free(RSA *rsa);
110
111static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
112 DSA *dsa);
113static int capi_dsa_free(DSA *dsa);
b3c8dd4e
DSH
114
115static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
116 STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey,
117 STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data);
7a18ecb2
DSH
118
119/* This structure contains CAPI ENGINE specific data:
120 * it contains various global options and affects how
121 * other functions behave.
122 */
123
124#define CAPI_DBG_TRACE 2
125#define CAPI_DBG_ERROR 1
126
127struct CAPI_CTX_st {
128 int debug_level;
129 char *debug_file;
130 /* Parameters to use for container lookup */
131 DWORD keytype;
132 LPTSTR cspname;
133 DWORD csptype;
134 /* Certificate store name to use */
135 LPTSTR storename;
b3c8dd4e 136 LPTSTR ssl_client_store;
7a18ecb2
DSH
137
138/* Lookup string meanings in load_private_key */
139/* Substring of subject: uses "storename" */
140#define CAPI_LU_SUBSTR 0
141/* Friendly name: uses storename */
142#define CAPI_LU_FNAME 1
143/* Container name: uses cspname, keytype */
144#define CAPI_LU_CONTNAME 2
145 int lookup_method;
146/* Info to dump with dumpcerts option */
147/* Issuer and serial name strings */
148#define CAPI_DMP_SUMMARY 0x1
149/* Friendly name */
150#define CAPI_DMP_FNAME 0x2
151/* Full X509_print dump */
152#define CAPI_DMP_FULL 0x4
153/* Dump PEM format certificate */
154#define CAPI_DMP_PEM 0x8
155/* Dump pseudo key (if possible) */
156#define CAPI_DMP_PSKEY 0x10
157/* Dump key info (if possible) */
158#define CAPI_DMP_PKEYINFO 0x20
159
160 DWORD dump_flags;
161};
162
163
164static CAPI_CTX *capi_ctx_new();
165static void capi_ctx_free(CAPI_CTX *ctx);
166static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check);
167static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx);
168
b3c8dd4e 169#define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE
7a18ecb2
DSH
170#define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1)
171#define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2)
b3c8dd4e
DSH
172#define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3)
173#define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4)
174#define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5)
7a18ecb2
DSH
175#define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6)
176#define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7)
177#define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8)
178#define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9)
179#define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10)
180#define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11)
c621c7e4 181#define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12)
7a18ecb2
DSH
182
183static const ENGINE_CMD_DEFN capi_cmd_defns[] = {
184 {CAPI_CMD_LIST_CERTS,
185 "list_certs",
186 "List all certificates in store",
187 ENGINE_CMD_FLAG_NO_INPUT},
188 {CAPI_CMD_LOOKUP_CERT,
189 "lookup_cert",
190 "Lookup and output certificates",
191 ENGINE_CMD_FLAG_STRING},
192 {CAPI_CMD_DEBUG_LEVEL,
193 "debug_level",
194 "debug level (1=errors, 2=trace)",
195 ENGINE_CMD_FLAG_NUMERIC},
196 {CAPI_CMD_DEBUG_FILE,
197 "debug_file",
198 "debugging filename)",
199 ENGINE_CMD_FLAG_STRING},
200 {CAPI_CMD_KEYTYPE,
201 "key_type",
202 "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE",
203 ENGINE_CMD_FLAG_NUMERIC},
204 {CAPI_CMD_LIST_CSPS,
205 "list_csps",
206 "List all CSPs",
207 ENGINE_CMD_FLAG_NO_INPUT},
208 {CAPI_CMD_SET_CSP_IDX,
209 "csp_idx",
210 "Set CSP by index",
211 ENGINE_CMD_FLAG_NUMERIC},
212 {CAPI_CMD_SET_CSP_NAME,
213 "csp_name",
214 "Set CSP name, (default CSP used if not specified)",
215 ENGINE_CMD_FLAG_STRING},
216 {CAPI_CMD_SET_CSP_TYPE,
217 "csp_type",
218 "Set CSP type, (default RSA_PROV_FULL)",
219 ENGINE_CMD_FLAG_NUMERIC},
220 {CAPI_CMD_LIST_CONTAINERS,
221 "list_containers",
222 "list container names",
223 ENGINE_CMD_FLAG_NO_INPUT},
224 {CAPI_CMD_LIST_OPTIONS,
225 "list_options",
226 "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, "
227 "32=private key info)",
228 ENGINE_CMD_FLAG_NUMERIC},
229 {CAPI_CMD_LOOKUP_METHOD,
230 "lookup_method",
231 "Set key lookup method (1=substring, 2=friendlyname, 3=container name)",
232 ENGINE_CMD_FLAG_NUMERIC},
c621c7e4
DSH
233 {CAPI_CMD_STORE_NAME,
234 "store_name",
235 "certificate store name, default \"MY\"",
236 ENGINE_CMD_FLAG_STRING},
7a18ecb2
DSH
237
238 {0, NULL, NULL, 0}
239 };
240
241static int capi_idx = -1;
242static int rsa_capi_idx = -1;
243static int dsa_capi_idx = -1;
7d537d4f 244static int cert_capi_idx = -1;
7a18ecb2
DSH
245
246static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
2aa2a577 247 {
7a18ecb2
DSH
248 int ret = 1;
249 CAPI_CTX *ctx;
250 BIO *out;
251 if (capi_idx == -1)
252 {
253 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
254 return 0;
255 }
256 ctx = ENGINE_get_ex_data(e, capi_idx);
257 out = BIO_new_fp(stdout, BIO_NOCLOSE);
258 switch (cmd)
259 {
260 case CAPI_CMD_LIST_CSPS:
261 ret = capi_list_providers(ctx, out);
262 break;
263
264 case CAPI_CMD_LIST_CERTS:
265 ret = capi_list_certs(ctx, out, NULL);
266 break;
267
268 case CAPI_CMD_LOOKUP_CERT:
269 ret = capi_list_certs(ctx, out, p);
270 break;
271
272 case CAPI_CMD_LIST_CONTAINERS:
273 ret = capi_list_containers(ctx, out);
274 break;
275
c621c7e4 276 case CAPI_CMD_STORE_NAME:
953174f4
DSH
277 if (ctx->storename)
278 OPENSSL_free(ctx->storename);
c621c7e4
DSH
279 ctx->storename = BUF_strdup(p);
280 CAPI_trace(ctx, "Setting store name to %s\n", p);
281 break;
282
7a18ecb2
DSH
283 case CAPI_CMD_DEBUG_LEVEL:
284 ctx->debug_level = (int)i;
285 CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level);
286 break;
287
288 case CAPI_CMD_DEBUG_FILE:
289 ctx->debug_file = BUF_strdup(p);
290 CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
291 break;
292
293 case CAPI_CMD_KEYTYPE:
294 ctx->keytype = i;
295 CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype);
296 break;
297
298 case CAPI_CMD_SET_CSP_IDX:
299 ret = capi_ctx_set_provname_idx(ctx, i);
300 break;
301
302 case CAPI_CMD_LIST_OPTIONS:
303 ctx->dump_flags = i;
304 break;
305
306 case CAPI_CMD_LOOKUP_METHOD:
307 if (i < 1 || i > 3)
308 {
309 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD);
310 return 0;
311 }
312 ctx->lookup_method = i;
313 break;
314
315 case CAPI_CMD_SET_CSP_NAME:
316 ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1);
317 break;
318
319 case CAPI_CMD_SET_CSP_TYPE:
320 ctx->csptype = i;
321 break;
322
323 default:
324 CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND);
325 ret = 0;
326 }
327
328 BIO_free(out);
329 return ret;
330
2aa2a577 331 }
7a18ecb2
DSH
332
333static RSA_METHOD capi_rsa_method =
334 {
335 "CryptoAPI RSA method",
336 0, /* pub_enc */
337 0, /* pub_dec */
338 capi_rsa_priv_enc, /* priv_enc */
339 capi_rsa_priv_dec, /* priv_dec */
340 0, /* rsa_mod_exp */
341 0, /* bn_mod_exp */
342 0, /* init */
343 capi_rsa_free, /* finish */
344 RSA_FLAG_SIGN_VER, /* flags */
345 NULL, /* app_data */
346 capi_rsa_sign, /* rsa_sign */
347 0 /* rsa_verify */
348 };
349
350static DSA_METHOD capi_dsa_method =
351 {
352 "CryptoAPI DSA method",
353 capi_dsa_do_sign, /* dsa_do_sign */
354 0, /* dsa_sign_setup */
355 0, /* dsa_do_verify */
356 0, /* dsa_mod_exp */
357 0, /* bn_mod_exp */
358 0, /* init */
359 capi_dsa_free, /* finish */
360 0, /* flags */
361 NULL, /* app_data */
362 0, /* dsa_paramgen */
363 0 /* dsa_keygen */
364 };
365
366static int capi_init(ENGINE *e)
367 {
368 CAPI_CTX *ctx;
369 const RSA_METHOD *ossl_rsa_meth;
370 const DSA_METHOD *ossl_dsa_meth;
371 capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
7d537d4f 372 cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
7a18ecb2
DSH
373
374 ctx = capi_ctx_new();
375 if (!ctx || (capi_idx < 0))
376 goto memerr;
377
378 ENGINE_set_ex_data(e, capi_idx, ctx);
379 /* Setup RSA_METHOD */
380 rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
381 ossl_rsa_meth = RSA_PKCS1_SSLeay();
382 capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc;
383 capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec;
384 capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp;
385 capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp;
386
387 /* Setup DSA Method */
388 dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
389 ossl_dsa_meth = DSA_OpenSSL();
390 capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify;
391 capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp;
392 capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp;
393
394 return 1;
395
396 memerr:
397 CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
398 return 0;
399
400 return 1;
401 }
402
403static int capi_destroy(ENGINE *e)
404 {
7a18ecb2
DSH
405 ERR_unload_CAPI_strings();
406 return 1;
407 }
408
409static int capi_finish(ENGINE *e)
410 {
411 CAPI_CTX *ctx;
412 ctx = ENGINE_get_ex_data(e, capi_idx);
413 capi_ctx_free(ctx);
414 ENGINE_set_ex_data(e, capi_idx, NULL);
415 return 1;
416 }
417
418
419/* CryptoAPI key application data. This contains
420 * a handle to the private key container (for sign operations)
421 * and a handle to the key (for decrypt operations).
422 */
423
424struct CAPI_KEY_st
425 {
7d537d4f 426 /* Associated certificate context (if any) */
e0f7b872 427 PCCERT_CONTEXT pcert;
7a18ecb2
DSH
428 HCRYPTPROV hprov;
429 HCRYPTKEY key;
4be0a5d4 430 DWORD keyspec;
7a18ecb2
DSH
431 };
432
433static int bind_capi(ENGINE *e)
434 {
435 if (!ENGINE_set_id(e, engine_capi_id)
436 || !ENGINE_set_name(e, engine_capi_name)
437 || !ENGINE_set_init_function(e, capi_init)
438 || !ENGINE_set_finish_function(e, capi_finish)
439 || !ENGINE_set_destroy_function(e, capi_destroy)
440 || !ENGINE_set_RSA(e, &capi_rsa_method)
441 || !ENGINE_set_DSA(e, &capi_dsa_method)
442 || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
b3c8dd4e
DSH
443 || !ENGINE_set_load_ssl_client_cert_function(e,
444 capi_load_ssl_client_cert)
7a18ecb2
DSH
445 || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
446 || !ENGINE_set_ctrl_function(e, capi_ctrl))
447 return 0;
448 ERR_load_CAPI_strings();
449
450 return 1;
451
452 }
453
454#ifndef OPENSSL_NO_DYNAMIC_ENGINE
455static int bind_helper(ENGINE *e, const char *id)
456 {
457 if(id && (strcmp(id, engine_capi_id) != 0))
458 return 0;
459 if(!bind_capi(e))
460 return 0;
461 return 1;
462 }
463IMPLEMENT_DYNAMIC_CHECK_FN()
464IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
465#else
466static ENGINE *engine_capi(void)
467 {
468 ENGINE *ret = ENGINE_new();
469 if(!ret)
470 return NULL;
471 if(!bind_capi(ret))
472 {
473 ENGINE_free(ret);
474 return NULL;
475 }
476 return ret;
477 }
478
479void ENGINE_load_capi(void)
480 {
481 /* Copied from eng_[openssl|dyn].c */
482 ENGINE *toadd = engine_capi();
483 if(!toadd) return;
484 ENGINE_add(toadd);
485 ENGINE_free(toadd);
486 ERR_clear_error();
487 }
488#endif
489
490
491static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
492 {
493 int i;
494 /* Reverse buffer in place: since this is a keyblob structure
495 * that will be freed up after conversion anyway it doesn't
496 * matter if we change it.
497 */
498 for(i = 0; i < binlen / 2; i++)
499 {
500 unsigned char c;
501 c = bin[i];
502 bin[i] = bin[binlen - i - 1];
503 bin[binlen - i - 1] = c;
504 }
505
506 if (!BN_bin2bn(bin, binlen, bn))
507 return 0;
508 return 1;
509 }
510
b3c8dd4e
DSH
511/* Given a CAPI_KEY get an EVP_PKEY structure */
512
513static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY *key)
7a18ecb2 514 {
7a18ecb2
DSH
515 unsigned char *pubkey = NULL;
516 DWORD len;
517 BLOBHEADER *bh;
518 RSA *rkey = NULL;
519 DSA *dkey = NULL;
b3c8dd4e 520 EVP_PKEY *ret = NULL;
7a18ecb2
DSH
521 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len))
522 {
b3c8dd4e 523 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR);
7a18ecb2
DSH
524 capi_addlasterror();
525 return NULL;
526 }
527
528 pubkey = OPENSSL_malloc(len);
529
530 if (!pubkey)
531 goto memerr;
532
533 if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len))
534 {
b3c8dd4e 535 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
7a18ecb2
DSH
536 capi_addlasterror();
537 goto err;
538 }
539
540 bh = (BLOBHEADER *)pubkey;
541 if (bh->bType != PUBLICKEYBLOB)
542 {
b3c8dd4e 543 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB);
7a18ecb2
DSH
544 goto err;
545 }
546 if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX)
547 {
548 RSAPUBKEY *rp;
549 DWORD rsa_modlen;
550 unsigned char *rsa_modulus;
551 rp = (RSAPUBKEY *)(bh + 1);
552 if (rp->magic != 0x31415352)
553 {
554 char magstr[10];
555 BIO_snprintf(magstr, 10, "%lx", rp->magic);
b3c8dd4e 556 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
7a18ecb2
DSH
557 ERR_add_error_data(2, "magic=0x", magstr);
558 goto err;
559 }
560 rsa_modulus = (unsigned char *)(rp + 1);
561 rkey = RSA_new_method(eng);
562 if (!rkey)
563 goto memerr;
564
565 rkey->e = BN_new();
566 rkey->n = BN_new();
567
568 if (!rkey->e || !rkey->n)
569 goto memerr;
570
571 if (!BN_set_word(rkey->e, rp->pubexp))
572 goto memerr;
573
574 rsa_modlen = rp->bitlen / 8;
575 if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
576 goto memerr;
577
578 RSA_set_ex_data(rkey, rsa_capi_idx, key);
579
580 if (!(ret = EVP_PKEY_new()))
581 goto memerr;
582
583 EVP_PKEY_assign_RSA(ret, rkey);
584 rkey = NULL;
585
586 }
587 else if (bh->aiKeyAlg == CALG_DSS_SIGN)
588 {
589 DSSPUBKEY *dp;
590 DWORD dsa_plen;
591 unsigned char *btmp;
592 dp = (DSSPUBKEY *)(bh + 1);
593 if (dp->magic != 0x31535344)
594 {
595 char magstr[10];
596 BIO_snprintf(magstr, 10, "%lx", dp->magic);
b3c8dd4e 597 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER);
7a18ecb2
DSH
598 ERR_add_error_data(2, "magic=0x", magstr);
599 goto err;
600 }
601 dsa_plen = dp->bitlen / 8;
602 btmp = (unsigned char *)(dp + 1);
603 dkey = DSA_new_method(eng);
604 if (!dkey)
605 goto memerr;
606 dkey->p = BN_new();
607 dkey->q = BN_new();
608 dkey->g = BN_new();
609 dkey->pub_key = BN_new();
610 if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key)
611 goto memerr;
612 if (!lend_tobn(dkey->p, btmp, dsa_plen))
613 goto memerr;
614 btmp += dsa_plen;
615 if (!lend_tobn(dkey->q, btmp, 20))
616 goto memerr;
617 btmp += 20;
618 if (!lend_tobn(dkey->g, btmp, dsa_plen))
619 goto memerr;
620 btmp += dsa_plen;
621 if (!lend_tobn(dkey->pub_key, btmp, dsa_plen))
622 goto memerr;
623 btmp += dsa_plen;
624
625 DSA_set_ex_data(dkey, dsa_capi_idx, key);
626
627 if (!(ret = EVP_PKEY_new()))
628 goto memerr;
629
630 EVP_PKEY_assign_DSA(ret, dkey);
631 dkey = NULL;
632 }
633 else
634 {
635 char algstr[10];
636 BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg);
b3c8dd4e 637 CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
7a18ecb2
DSH
638 ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
639 goto err;
640 }
641
b3c8dd4e 642
7a18ecb2
DSH
643 err:
644 if (pubkey)
645 OPENSSL_free(pubkey);
646 if (!ret)
647 {
648 if (rkey)
649 RSA_free(rkey);
650 if (dkey)
651 DSA_free(dkey);
7a18ecb2
DSH
652 }
653
654 return ret;
655
656memerr:
657 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, ERR_R_MALLOC_FAILURE);
658 goto err;
659
660 }
661
b3c8dd4e
DSH
662static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
663 UI_METHOD *ui_method, void *callback_data)
664 {
665 CAPI_CTX *ctx;
666 CAPI_KEY *key;
667 EVP_PKEY *ret;
668 ctx = ENGINE_get_ex_data(eng, capi_idx);
669
670 if (!ctx)
671 {
672 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT);
673 return NULL;
674 }
675
676 key = capi_find_key(ctx, key_id);
677
678 if (!key)
679 return NULL;
680
681 ret = capi_get_pkey(eng, key);
682
683 if (!ret)
684 capi_free_key(key);
685 return ret;
686
687 }
688
7a18ecb2
DSH
689/* CryptoAPI RSA operations */
690
691int capi_rsa_priv_enc(int flen, const unsigned char *from,
692 unsigned char *to, RSA *rsa, int padding)
693 {
694 CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
695 return -1;
696 }
697
698int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
699 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
700 {
701 ALG_ID alg;
702 HCRYPTHASH hash;
703 DWORD slen;
704 unsigned int i;
705 int ret = -1;
706 CAPI_KEY *capi_key;
707 CAPI_CTX *ctx;
708
709 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
710
711 CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
712
713 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
714 if (!capi_key)
715 {
716 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
717 return -1;
718 }
719/* Convert the signature type to a CryptoAPI algorithm ID */
2aa2a577
DSH
720 switch(dtype)
721 {
7a18ecb2
DSH
722 case NID_sha1:
723 alg = CALG_SHA1;
724 break;
725
726 case NID_md5:
727 alg = CALG_MD5;
728 break;
729
730 case NID_md5_sha1:
731 alg = CALG_SSL3_SHAMD5;
732 break;
733 default:
734 {
735 char algstr[10];
736 BIO_snprintf(algstr, 10, "%lx", dtype);
737 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
738 ERR_add_error_data(2, "NID=0x", algstr);
739 return -1;
740 }
741 }
742
743
744
745/* Create the hash object */
2aa2a577
DSH
746 if(!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash))
747 {
7a18ecb2
DSH
748 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
749 capi_addlasterror();
750 return -1;
2aa2a577 751 }
7a18ecb2
DSH
752/* Set the hash value to the value passed */
753
2aa2a577
DSH
754 if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0))
755 {
7a18ecb2
DSH
756 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
757 capi_addlasterror();
758 goto err;
2aa2a577 759 }
7a18ecb2
DSH
760
761
762/* Finally sign it */
763 slen = RSA_size(rsa);
2aa2a577
DSH
764 if(!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen))
765 {
7a18ecb2
DSH
766 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
767 capi_addlasterror();
768 goto err;
2aa2a577
DSH
769 }
770 else
771 {
7a18ecb2
DSH
772 ret = 1;
773 /* Inplace byte reversal of signature */
2aa2a577
DSH
774 for(i = 0; i < slen / 2; i++)
775 {
7a18ecb2
DSH
776 unsigned char c;
777 c = sigret[i];
778 sigret[i] = sigret[slen - i - 1];
779 sigret[slen - i - 1] = c;
2aa2a577 780 }
7a18ecb2 781 *siglen = slen;
2aa2a577 782 }
7a18ecb2 783
7a18ecb2
DSH
784 /* Now cleanup */
785
786err:
787 CryptDestroyHash(hash);
788
789 return ret;
2aa2a577 790 }
7a18ecb2
DSH
791
792int capi_rsa_priv_dec(int flen, const unsigned char *from,
793 unsigned char *to, RSA *rsa, int padding)
2aa2a577 794 {
7a18ecb2
DSH
795 int i;
796 unsigned char *tmpbuf;
797 CAPI_KEY *capi_key;
798 CAPI_CTX *ctx;
799 ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
800
801 CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
802
803
804 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
805 if (!capi_key)
806 {
807 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
808 return -1;
809 }
810
811 if(padding != RSA_PKCS1_PADDING)
812 {
813 char errstr[10];
814 BIO_snprintf(errstr, 10, "%d", padding);
815 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
816 ERR_add_error_data(2, "padding=", errstr);
817 return -1;
818 }
819
820 /* Create temp reverse order version of input */
821 if(!(tmpbuf = OPENSSL_malloc(flen)) )
822 {
823 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
824 return -1;
825 }
826 for(i = 0; i < flen; i++)
827 tmpbuf[flen - i - 1] = from[i];
828
829 /* Finally decrypt it */
830 if(!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen))
831 {
832 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
833 capi_addlasterror();
834 OPENSSL_free(tmpbuf);
835 return -1;
836 }
837 else memcpy(to, tmpbuf, flen);
838
839 OPENSSL_free(tmpbuf);
840
841 return flen;
2aa2a577 842 }
7a18ecb2
DSH
843
844static int capi_rsa_free(RSA *rsa)
845 {
846 CAPI_KEY *capi_key;
847 capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
848 capi_free_key(capi_key);
849 RSA_set_ex_data(rsa, rsa_capi_idx, 0);
850 return 1;
851 }
852
853/* CryptoAPI DSA operations */
854
855static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
856 DSA *dsa)
857 {
858 HCRYPTHASH hash;
859 DWORD slen;
860 DSA_SIG *ret = NULL;
861 CAPI_KEY *capi_key;
862 CAPI_CTX *ctx;
863 unsigned char csigbuf[40];
864
865 ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
866
867 CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
868
869 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
870
871 if (!capi_key)
872 {
873 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY);
874 return NULL;
875 }
876
877 if (dlen != 20)
878 {
879 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH);
880 return NULL;
881 }
882
883 /* Create the hash object */
2aa2a577
DSH
884 if(!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash))
885 {
7a18ecb2
DSH
886 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
887 capi_addlasterror();
888 return NULL;
2aa2a577 889 }
7a18ecb2
DSH
890
891 /* Set the hash value to the value passed */
2aa2a577
DSH
892 if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0))
893 {
7a18ecb2
DSH
894 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
895 capi_addlasterror();
896 goto err;
2aa2a577 897 }
7a18ecb2
DSH
898
899
900 /* Finally sign it */
901 slen = sizeof(csigbuf);
2bbe8f91 902 if(!CryptSignHash(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen))
7a18ecb2
DSH
903 {
904 CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH);
905 capi_addlasterror();
906 goto err;
907 }
908 else
909 {
910 ret = DSA_SIG_new();
911 if (!ret)
912 goto err;
913 ret->r = BN_new();
914 ret->s = BN_new();
915 if (!ret->r || !ret->s)
916 goto err;
917 if (!lend_tobn(ret->r, csigbuf, 20)
918 || !lend_tobn(ret->s, csigbuf + 20, 20))
919 {
920 DSA_SIG_free(ret);
921 ret = NULL;
922 goto err;
923 }
924 }
925
926 /* Now cleanup */
927
928err:
929 OPENSSL_cleanse(csigbuf, 40);
930 CryptDestroyHash(hash);
931 return ret;
932 }
933
934static int capi_dsa_free(DSA *dsa)
935 {
936 CAPI_KEY *capi_key;
937 capi_key = DSA_get_ex_data(dsa, dsa_capi_idx);
938 capi_free_key(capi_key);
939 DSA_set_ex_data(dsa, dsa_capi_idx, 0);
940 return 1;
941 }
942
943static void capi_vtrace(CAPI_CTX *ctx, int level, char *format, va_list argptr)
944 {
945 BIO *out;
946
947 if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
948 return;
949 out = BIO_new_file(ctx->debug_file, "a+");
950 BIO_vprintf(out, format, argptr);
951 BIO_free(out);
952 }
953
954static void CAPI_trace(CAPI_CTX *ctx, char *format, ...)
955 {
956 va_list args;
957 va_start(args, format);
958 capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
959 va_end(args);
960 }
961
962static void capi_addlasterror(void)
963 {
964 capi_adderror(GetLastError());
965 }
966
967static void capi_adderror(DWORD err)
968 {
969 char errstr[10];
970 BIO_snprintf(errstr, 10, "%lX", err);
971 ERR_add_error_data(2, "Error code= 0x", errstr);
972 }
973
974static char *wide_to_asc(LPWSTR wstr)
975 {
976 char *str;
977 if (!wstr)
978 return NULL;
979 str = OPENSSL_malloc(wcslen(wstr) + 1);
980 if (!str)
981 {
982 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
983 return NULL;
984 }
985 sprintf(str, "%S", wstr);
986 return str;
987 }
988
989static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype, DWORD idx)
990 {
991 LPSTR name;
992 DWORD len, err;
993 CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
994 if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len))
995 {
996 err = GetLastError();
997 if (err == ERROR_NO_MORE_ITEMS)
998 return 2;
999 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1000 capi_adderror(err);
1001 return 0;
1002 }
1003 name = OPENSSL_malloc(len);
1004 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len))
1005 {
1006 err = GetLastError();
1007 if (err == ERROR_NO_MORE_ITEMS)
1008 return 2;
1009 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
1010 capi_adderror(err);
1011 return 0;
1012 }
1013 *pname = name;
1014 CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", name, *ptype);
1015
1016 return 1;
1017 }
1018
1019static int capi_list_providers(CAPI_CTX *ctx, BIO *out)
1020 {
1021 DWORD idx, ptype;
1022 int ret;
1023 LPTSTR provname = NULL;
1024 CAPI_trace(ctx, "capi_list_providers\n");
1025 BIO_printf(out, "Available CSPs:\n");
1026 for(idx = 0; ; idx++)
1027 {
1028 ret = capi_get_provname(ctx, &provname, &ptype, idx);
1029 if (ret == 2)
1030 break;
1031 if (ret == 0)
1032 break;
1033 BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
1034 OPENSSL_free(provname);
1035 }
1036 return 1;
1037 }
1038
1039static int capi_list_containers(CAPI_CTX *ctx, BIO *out)
1040 {
1041 int ret = 1;
1042 HCRYPTPROV hprov;
1043 DWORD err, idx, flags, buflen = 0, clen;
1044 LPSTR cname;
1045 CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname, ctx->csptype);
1046 if (!CryptAcquireContext(&hprov, NULL, ctx->cspname, ctx->csptype, CRYPT_VERIFYCONTEXT))
1047 {
1048 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1049 capi_addlasterror();
1050 return 0;
1051 }
1052 if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST))
1053 {
1054 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1055 capi_addlasterror();
1056 return 0;
1057 }
1058 CAPI_trace(ctx, "Got max container len %d\n", buflen);
1059 if (buflen == 0)
1060 buflen = 1024;
1061 cname = OPENSSL_malloc(buflen);
1062 if (!cname)
1063 {
1064 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
1065 goto err;
1066 }
1067
1068 for (idx = 0;;idx++)
1069 {
2aa2a577
DSH
1070 clen = buflen;
1071 cname[0] = 0;
1072
1073 if (idx == 0)
1074 flags = CRYPT_FIRST;
1075 else
1076 flags = 0;
1077 if(!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, cname, &clen, flags))
1078 {
1079 err = GetLastError();
1080 if (err == ERROR_NO_MORE_ITEMS)
7a18ecb2 1081 goto done;
2aa2a577
DSH
1082 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
1083 capi_adderror(err);
1084 goto err;
1085 }
1086 CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n", cname, clen, idx, flags);
1087 if (!cname[0] && (clen == buflen))
1088 {
1089 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
1090 goto done;
1091 }
1092 BIO_printf(out, "%d. %s\n", idx, cname);
7a18ecb2
DSH
1093 }
1094 err:
1095
1096 ret = 0;
1097
1098 done:
1099 if (cname)
1100 OPENSSL_free(cname);
1101 CryptReleaseContext(hprov, 0);
1102
1103 return ret;
1104 }
1105
1106CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1107 {
1108 DWORD len;
1109 CRYPT_KEY_PROV_INFO *pinfo;
1110
1111 if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
1112 return NULL;
1113 pinfo = OPENSSL_malloc(len);
1114 if (!pinfo)
1115 {
1116 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
1117 return NULL;
1118 }
1119 if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len))
1120 {
1121 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
1122 capi_addlasterror();
1123 OPENSSL_free(pinfo);
1124 return NULL;
1125 }
1126 return pinfo;
1127 }
1128
1129static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out, CRYPT_KEY_PROV_INFO *pinfo)
1130 {
1131 char *provname = NULL, *contname = NULL;
1132 if (!pinfo)
1133 {
1134 BIO_printf(out, " No Private Key\n");
1135 return;
1136 }
1137 provname = wide_to_asc(pinfo->pwszProvName);
1138 contname = wide_to_asc(pinfo->pwszContainerName);
1139 if (!provname || !contname)
1140 goto err;
1141
1142 BIO_printf(out, " Private Key Info:\n");
1143 BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname, pinfo->dwProvType);
1144 BIO_printf(out, " Container Name: %s, Key Type %d\n", contname, pinfo->dwKeySpec);
1145 err:
1146 if (provname)
1147 OPENSSL_free(provname);
1148 if (contname)
1149 OPENSSL_free(contname);
1150 }
1151
1152char * capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1153 {
1154 LPWSTR wfname;
1155 DWORD dlen;
1156
1157 CAPI_trace(ctx, "capi_cert_get_fname\n");
1158 if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1159 return NULL;
1160 wfname = OPENSSL_malloc(dlen);
1161 if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen))
1162 {
1163 char *fname = wide_to_asc(wfname);
1164 OPENSSL_free(wfname);
1165 return fname;
1166 }
1167 CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1168 capi_addlasterror();
1169
1170 OPENSSL_free(wfname);
1171 return NULL;
1172 }
1173
1174
1175void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert)
1176 {
1177 X509 *x;
1178 unsigned char *p;
1179 unsigned long flags = ctx->dump_flags;
1180 if (flags & CAPI_DMP_FNAME)
1181 {
1182 char *fname;
1183 fname = capi_cert_get_fname(ctx, cert);
1184 if (fname)
1185 {
1186 BIO_printf(out, " Friendly Name \"%s\"\n", fname);
1187 OPENSSL_free(fname);
1188 }
1189 else
1190 BIO_printf(out, " <No Friendly Name>\n");
1191 }
1192
1193 p = cert->pbCertEncoded;
1194 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1195 if (!x)
1196 BIO_printf(out, " <Can't parse certificate>\n");
1197 if (flags & CAPI_DMP_SUMMARY)
1198 {
1199 BIO_printf(out, " Subject: ");
1200 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1201 BIO_printf(out, "\n Issuer: ");
1202 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1203 BIO_printf(out, "\n");
1204 }
1205 if (flags & CAPI_DMP_FULL)
1206 X509_print_ex(out, x, XN_FLAG_ONELINE,0);
1207
1208 if (flags & CAPI_DMP_PKEYINFO)
1209 {
1210 CRYPT_KEY_PROV_INFO *pinfo;
1211 pinfo = capi_get_prov_info(ctx, cert);
1212 capi_dump_prov_info(ctx, out, pinfo);
1213 if (pinfo)
1214 OPENSSL_free(pinfo);
1215 }
1216
1217 if (flags & CAPI_DMP_PEM)
1218 PEM_write_bio_X509(out, x);
1219 X509_free(x);
1220 }
1221
1222HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename)
1223 {
1224 HCERTSTORE hstore;
1225
1226 if (!storename)
1227 storename = ctx->storename;
1228 if (!storename)
1229 storename = "MY";
1230 CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1231
1232 hstore = CertOpenSystemStore(0, storename);
1233 if (!hstore)
1234 {
1235 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1236 capi_addlasterror();
1237 }
1238 return hstore;
1239 }
1240
1241int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id)
1242 {
1243 char *storename;
1244 int idx;
1245 int ret = 1;
1246 HCERTSTORE hstore;
1247 PCCERT_CONTEXT cert = NULL;
1248
1249 storename = ctx->storename;
1250 if (!storename)
1251 storename = "MY";
1252 CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1253
1254 hstore = capi_open_store(ctx, storename);
1255 if (!hstore)
1256 return 0;
1257 if (id)
1258 {
1259 cert = capi_find_cert(ctx, id, hstore);
1260 if (!cert)
1261 {
1262 ret = 0;
1263 goto err;
1264 }
1265 capi_dump_cert(ctx, out, cert);
1266 CertFreeCertificateContext(cert);
1267 }
1268 else
1269 {
1270 for(idx = 0;;idx++)
1271 {
1272 LPWSTR fname = NULL;
1273 cert = CertEnumCertificatesInStore(hstore, cert);
1274 if (!cert)
1275 break;
1276 BIO_printf(out, "Certificate %d\n", idx);
1277 capi_dump_cert(ctx, out, cert);
1278 }
1279 }
1280 err:
1281 CertCloseStore(hstore, 0);
1282 return ret;
1283 }
1284
1285static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore)
1286 {
1287 PCCERT_CONTEXT cert = NULL;
1288 char *fname = NULL;
1289 int match;
1290 switch(ctx->lookup_method)
1291 {
1292 case CAPI_LU_SUBSTR:
2aa2a577
DSH
1293 return CertFindCertificateInStore(hstore,
1294 X509_ASN_ENCODING, 0,
1295 CERT_FIND_SUBJECT_STR_A, id, NULL);
7a18ecb2
DSH
1296 case CAPI_LU_FNAME:
1297 for(;;)
1298 {
1299 cert = CertEnumCertificatesInStore(hstore, cert);
1300 if (!cert)
1301 return NULL;
1302 fname = capi_cert_get_fname(ctx, cert);
1303 if (fname)
1304 {
1305 if (strcmp(fname, id))
1306 match = 0;
1307 else
1308 match = 1;
1309 OPENSSL_free(fname);
1310 if (match)
1311 return cert;
1312 }
1313 }
1314 default:
1315 return NULL;
1316 }
1317 }
1318
1319static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const char *contname, char *provname, DWORD ptype, DWORD keyspec)
1320 {
1321 CAPI_KEY *key;
1322 key = OPENSSL_malloc(sizeof(CAPI_KEY));
1323 CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
2aa2a577 1324 contname, provname, ptype);
7a18ecb2
DSH
1325 if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, 0))
1326 {
1327 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1328 capi_addlasterror();
1329 goto err;
1330 }
1331 if (!CryptGetUserKey(key->hprov, keyspec, &key->key))
1332 {
1333 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1334 capi_addlasterror();
1335 CryptReleaseContext(key->hprov, 0);
1336 goto err;
1337 }
4be0a5d4 1338 key->keyspec = keyspec;
7d537d4f 1339 key->pcert = NULL;
7a18ecb2
DSH
1340 return key;
1341
1342 err:
1343 OPENSSL_free(key);
1344 return NULL;
1345 }
1346
1347static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1348 {
1349 CAPI_KEY *key;
1350 CRYPT_KEY_PROV_INFO *pinfo = NULL;
1351 char *provname = NULL, *contname = NULL;
1352 pinfo = capi_get_prov_info(ctx, cert);
1353 if (!pinfo)
1354 goto err;
1355 provname = wide_to_asc(pinfo->pwszProvName);
1356 contname = wide_to_asc(pinfo->pwszContainerName);
1357 if (!provname || !contname)
1358 return 0;
1359
2aa2a577
DSH
1360 key = capi_get_key(ctx, contname, provname,
1361 pinfo->dwProvType, pinfo->dwKeySpec);
7a18ecb2
DSH
1362
1363 err:
1364 if (pinfo)
1365 OPENSSL_free(pinfo);
1366 if (provname)
1367 OPENSSL_free(provname);
1368 if (contname)
1369 OPENSSL_free(contname);
1370 return key;
1371 }
1372
1373CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id)
1374 {
1375 PCCERT_CONTEXT cert;
1376 HCERTSTORE hstore;
1377 CAPI_KEY *key = NULL;
1378 switch (ctx->lookup_method)
1379 {
1380 case CAPI_LU_SUBSTR:
1381 case CAPI_LU_FNAME:
1382 hstore = capi_open_store(ctx, NULL);
1383 if (!hstore)
1384 return NULL;
1385 cert = capi_find_cert(ctx, id, hstore);
1386 if (cert)
1387 {
1388 key = capi_get_cert_key(ctx, cert);
1389 CertFreeCertificateContext(cert);
1390 }
1391 CertCloseStore(hstore, 0);
1392 break;
1393
1394 case CAPI_LU_CONTNAME:
2aa2a577
DSH
1395 key = capi_get_key(ctx, id, ctx->cspname, ctx->csptype,
1396 ctx->keytype);
7a18ecb2
DSH
1397 break;
1398 }
1399
1400 return key;
1401 }
1402
1403void capi_free_key(CAPI_KEY *key)
1404 {
1405 if (!key)
1406 return;
1407 CryptDestroyKey(key->key);
1408 CryptReleaseContext(key->hprov, 0);
7d537d4f
DSH
1409 if (key->pcert)
1410 CertFreeCertificateContext(key->pcert);
7a18ecb2
DSH
1411 OPENSSL_free(key);
1412 }
1413
1414
1415/* Initialize a CAPI_CTX structure */
1416
1417static CAPI_CTX *capi_ctx_new()
1418 {
1419 CAPI_CTX *ctx;
1420 ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
1421 if (!ctx)
1422 {
1423 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1424 return NULL;
1425 }
1426 ctx->cspname = NULL;
1427 ctx->csptype = PROV_RSA_FULL;
1428 ctx->dump_flags = CAPI_DMP_SUMMARY|CAPI_DMP_FNAME;
1429 ctx->keytype = AT_KEYEXCHANGE;
1430 ctx->storename = NULL;
b3c8dd4e 1431 ctx->ssl_client_store = NULL;
7a18ecb2
DSH
1432 ctx->lookup_method = CAPI_LU_SUBSTR;
1433 ctx->debug_level = 0;
1434 ctx->debug_file = NULL;
1435 return ctx;
1436 }
1437
1438static void capi_ctx_free(CAPI_CTX *ctx)
1439 {
1440 CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1441 if (!ctx)
1442 return;
1443 if (ctx->cspname)
1444 OPENSSL_free(ctx->cspname);
1445 if (ctx->debug_file)
1446 OPENSSL_free(ctx->debug_file);
1447 if (ctx->storename)
1448 OPENSSL_free(ctx->storename);
b3c8dd4e
DSH
1449 if (ctx->ssl_client_store)
1450 OPENSSL_free(ctx->ssl_client_store);
7a18ecb2
DSH
1451 OPENSSL_free(ctx);
1452 }
1453
1454static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check)
1455 {
1456 CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1457 if (check)
1458 {
1459 HCRYPTPROV hprov;
2aa2a577
DSH
1460 if (!CryptAcquireContext(&hprov, NULL, pname, type,
1461 CRYPT_VERIFYCONTEXT))
7a18ecb2
DSH
1462 {
1463 CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1464 capi_addlasterror();
1465 return 0;
1466 }
1467 CryptReleaseContext(hprov, 0);
1468 }
1469 ctx->cspname = BUF_strdup(pname);
1470 ctx->csptype = type;
1471 return 1;
1472 }
1473
1474static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx)
1475 {
1476 LPSTR pname;
1477 DWORD type;
1478 if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1479 return 0;
1480 return capi_ctx_set_provname(ctx, pname, type, 0);
1481 }
1482
b3c8dd4e
DSH
1483static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x)
1484 {
1485 int i;
1486 X509_NAME *nm;
ca89fc1f
DSH
1487 /* Special case: empty list: match anything */
1488 if (sk_X509_NAME_num(ca_dn) <= 0)
1489 return 1;
b3c8dd4e
DSH
1490 for (i = 0; i < sk_X509_NAME_num(ca_dn); i++)
1491 {
1492 nm = sk_X509_NAME_value(ca_dn, i);
1493 if (!X509_NAME_cmp(nm, X509_get_issuer_name(x)))
1494 return 1;
1495 }
1496 return 0;
1497 }
1498
e0f7b872 1499
7d537d4f 1500
b3c8dd4e
DSH
1501static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
1502 STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey,
1503 STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data)
1504 {
b3c8dd4e 1505 STACK_OF(X509) *certs = NULL;
b3c8dd4e 1506 X509 *x;
b3c8dd4e
DSH
1507 char *storename;
1508 const char *p;
7d537d4f 1509 int i, client_cert_idx;
b3c8dd4e 1510 HCERTSTORE hstore;
7d537d4f 1511 PCCERT_CONTEXT cert = NULL, excert = NULL;
b3c8dd4e 1512 CAPI_CTX *ctx;
7d537d4f 1513 CAPI_KEY *key;
b3c8dd4e
DSH
1514 ctx = ENGINE_get_ex_data(e, capi_idx);
1515
1516 *pcert = NULL;
1517 *pkey = NULL;
1518
1519 storename = ctx->ssl_client_store;
1520 if (!storename)
1521 storename = "MY";
1522
1523 hstore = capi_open_store(ctx, storename);
1524 if (!hstore)
1525 return 0;
b814c01a 1526 /* Enumerate all certificates collect any matches */
7d537d4f 1527 for(i = 0;;i++)
b3c8dd4e
DSH
1528 {
1529 cert = CertEnumCertificatesInStore(hstore, cert);
1530 if (!cert)
1531 break;
1532 p = cert->pbCertEncoded;
1533 x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1534 if (!x)
1535 {
1536 CAPI_trace(ctx, "Can't Parse Certificate %d\n", i);
1537 continue;
1538 }
1539 if (cert_issuer_match(ca_dn, x))
1540 {
7d537d4f 1541 key = capi_get_cert_key(ctx, cert);
b3c8dd4e
DSH
1542 if (!key)
1543 continue;
b814c01a
DSH
1544 /* Match found: attach extra data to it so
1545 * we can retrieve the key later.
1546 */
7d537d4f 1547 excert = CertDuplicateCertificateContext(cert);
e0f7b872 1548 key->pcert = excert;
7d537d4f
DSH
1549 X509_set_ex_data(x, cert_capi_idx, key);
1550
1551 if (!certs)
1552 certs = sk_X509_new_null();
1553
1554 sk_X509_push(certs, x);
b3c8dd4e
DSH
1555 }
1556 else
1557 X509_free(x);
1558
1559 }
1560
1561 if (cert)
1562 CertFreeCertificateContext(cert);
e0f7b872
DSH
1563 if (hstore)
1564 CertCloseStore(hstore, 0);
b3c8dd4e 1565
7d537d4f 1566 if (!certs)
b3c8dd4e
DSH
1567 return 0;
1568
b814c01a
DSH
1569
1570 /* Select the appropriate certificate */
1571
7d537d4f
DSH
1572 client_cert_idx = client_cert_select(e, ssl, certs);
1573
b814c01a
DSH
1574 /* Set the selected certificate and free the rest */
1575
7d537d4f
DSH
1576 for(i = 0; i < sk_X509_num(certs); i++)
1577 {
1578 x = sk_X509_value(certs, i);
1579 if (i == client_cert_idx)
1580 *pcert = x;
1581 else
1582 {
1583 key = X509_get_ex_data(x, cert_capi_idx);
1584 capi_free_key(key);
1585 X509_free(x);
1586 }
1587 }
1588
1589 sk_X509_free(certs);
1590
1591 if (!*pcert)
1592 return 0;
1593
b814c01a
DSH
1594 /* Setup key for selected certificate */
1595
7d537d4f
DSH
1596 key = X509_get_ex_data(*pcert, cert_capi_idx);
1597 *pkey = capi_get_pkey(e, key);
1598 X509_set_ex_data(*pcert, cert_capi_idx, NULL);
1599
1600 return 1;
1601
b3c8dd4e
DSH
1602 }
1603
e0f7b872
DSH
1604#ifndef OPENSSL_CAPIENG_DIALOG
1605
1606/* Simple client cert selection function: always select first */
1607
1608static int client_cert_select(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1609 {
1610 return 0;
1611 }
1612
1613#else
1614
1615/* More complex cert selection function, using standard function
1616 * CryptUIDlgSelectCertificateFromStore() to produce a dialog box.
1617 */
1618
1619#include <cryptuiapi.h>
1620
1621static int client_cert_select(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs)
1622 {
1623 X509 *x;
1624 HCERTSTORE dstore;
1625 PCCERT_CONTEXT cert;
1626 CAPI_CTX *ctx;
1627 CAPI_KEY *key;
1628 int i, idx = -1;
1629 ctx = ENGINE_get_ex_data(e, capi_idx);
1630 /* Create an in memory store of certificates */
1631 dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1632 CERT_STORE_CREATE_NEW_FLAG, NULL);
1633 if (!dstore)
1634 {
1635 CAPIerr(CAPI_F_CLIENT_CERT_SELECT, CAPI_R_ERROR_CREATING_STORE);
1636 capi_addlasterror();
1637 goto err;
1638 }
1639 /* Add all certificates to store */
1640 for(i = 0; i < sk_X509_num(certs); i++)
1641 {
1642 x = sk_X509_value(certs, i);
1643 key = X509_get_ex_data(x, cert_capi_idx);
1644
1645 if (!CertAddCertificateContextToStore(dstore, key->pcert,
1646 CERT_STORE_ADD_NEW, NULL))
1647 {
1648 CAPIerr(CAPI_F_CLIENT_CERT_SELECT, CAPI_R_ERROR_ADDING_CERT);
1649 capi_addlasterror();
1650 goto err;
1651 }
1652
1653 }
1654 /* Call dialog to select one */
1655 cert = CryptUIDlgSelectCertificateFromStore(dstore, NULL,NULL, NULL,
1656 0, 0, NULL);
1657
1658 /* Find matching cert from list */
1659 if (cert)
1660 {
1661 for(i = 0; i < sk_X509_num(certs); i++)
1662 {
1663 x = sk_X509_value(certs, i);
1664 key = X509_get_ex_data(x, cert_capi_idx);
1665 if (CertCompareCertificate(
1666 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1667 cert->pCertInfo,
1668 key->pcert->pCertInfo))
1669 {
1670 idx = i;
1671 break;
1672 }
1673 }
1674 }
1675
1676 err:
1677 if (dstore)
1678 CertCloseStore(dstore, 0);
1679 return idx;
1680
1681 }
1682#endif
1683
7a18ecb2
DSH
1684#endif
1685#endif