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