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