Initial DSA public key loading support in CryptoAPI ENGINE.
[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                         fprintf(stderr, "Invalid blob Magic %x\n",
531                                                 rp->magic);
532                         goto err;
533                         }
534                 rsa_modulus = (unsigned char *)(rp + 1);
535                 rkey = RSA_new_method(eng);
536                 if (!rkey)
537                         goto memerr;
538
539                 rkey->e = BN_new();
540                 rkey->n = BN_new();
541
542                 if (!rkey->e || !rkey->n)
543                         goto memerr;
544
545                 if (!BN_set_word(rkey->e, rp->pubexp))
546                         goto memerr;
547
548                 rsa_modlen = rp->bitlen / 8;
549                 if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
550                         goto memerr;
551
552                 RSA_set_ex_data(rkey, rsa_capi_idx, key);
553
554                 if (!(ret = EVP_PKEY_new()))
555                         goto memerr;
556
557                 EVP_PKEY_assign_RSA(ret, rkey);
558                 rkey = NULL;
559
560                 }
561         else if (bh->aiKeyAlg == CALG_DSS_SIGN)
562                 {
563                 DSSPUBKEY *dp;
564                 DWORD dsa_plen;
565                 unsigned char *btmp;
566                 dp = (DSSPUBKEY *)(bh + 1);
567                 if (dp->magic != 0x31535344)
568                         {
569                         fprintf(stderr, "Invalid blob Magic %x\n",
570                                                 dp->magic);
571                         goto err;
572                         }
573                 dsa_plen = dp->bitlen / 8;
574                 btmp = (unsigned char *)(dp + 1);
575                 dkey = DSA_new();
576                 if (!dkey)
577                         goto memerr;
578                 dkey->p = BN_new();
579                 dkey->q = BN_new();
580                 dkey->g = BN_new();
581                 dkey->pub_key = BN_new();
582                 if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key)
583                         goto memerr;
584                 if (!lend_tobn(dkey->p, btmp, dsa_plen))
585                         goto memerr;
586                 btmp += dsa_plen;
587                 if (!lend_tobn(dkey->q, btmp, 20))
588                         goto memerr;
589                 btmp += 20;
590                 if (!lend_tobn(dkey->g, btmp, dsa_plen))
591                         goto memerr;
592                 btmp += dsa_plen;
593                 if (!lend_tobn(dkey->pub_key, btmp, dsa_plen))
594                         goto memerr;
595                 btmp += dsa_plen;
596
597                 DSA_set_ex_data(dkey, dsa_capi_idx, key);
598
599                 if (!(ret = EVP_PKEY_new()))
600                         goto memerr;
601
602                 EVP_PKEY_assign_DSA(ret, dkey);
603                 dkey = NULL;
604                 }
605         else
606                 {
607 BIO_dump_fp(stderr, pubkey, len);
608                 CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
609                 goto err;
610                 }
611
612         err:
613         if (pubkey)
614                 OPENSSL_free(pubkey);
615         if (!ret)
616                 {
617                 if (rkey)
618                         RSA_free(rkey);
619                 if (dkey)
620                         DSA_free(dkey);
621                 if (key)
622                         capi_free_key(key);
623                 }
624
625         return ret;
626
627 memerr:
628         CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, ERR_R_MALLOC_FAILURE);
629         goto err;
630
631         }
632
633 /* CryptoAPI RSA operations */
634
635 int capi_rsa_priv_enc(int flen, const unsigned char *from,
636                 unsigned char *to, RSA *rsa, int padding)
637         {
638         CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED);
639         return -1;
640         }
641
642 int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
643              unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
644         {
645         ALG_ID alg;
646         HCRYPTHASH hash;
647         DWORD slen;
648         unsigned int i;
649         int ret = -1;
650         CAPI_KEY *capi_key;
651         CAPI_CTX *ctx;
652
653         ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
654
655         CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
656
657         capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
658         if (!capi_key)
659                 {
660                 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
661                 return -1;
662                 }
663 /* Convert the signature type to a CryptoAPI algorithm ID */
664         switch(dtype) {
665         case NID_sha1:
666                 alg = CALG_SHA1;
667                 break;
668
669         case NID_md5:
670                 alg = CALG_MD5;
671                 break;
672
673         case NID_md5_sha1:
674                 alg = CALG_SSL3_SHAMD5;
675                 break;
676         default:
677                 {
678                 char algstr[10];
679                 sprintf(algstr, "%lx", dtype);
680                 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
681                 ERR_add_error_data(2, "NID=0x", algstr);
682                 return -1;
683                 }
684         }
685
686
687
688 /* Create the hash object */
689         if(!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
690                 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
691                 capi_addlasterror();
692                 return -1;
693         }
694 /* Set the hash value to the value passed */
695
696         if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
697                 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
698                 capi_addlasterror();
699                 goto err;
700         }
701
702
703 /* Finally sign it */
704         slen = RSA_size(rsa);
705         if(!CryptSignHash(hash, AT_KEYEXCHANGE, NULL, 0, sigret, &slen)) {
706                 CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
707                 capi_addlasterror();
708                 goto err;
709         } else {
710                 ret = 1;
711                 /* Inplace byte reversal of signature */
712                 for(i = 0; i < slen / 2; i++) {
713                         unsigned char c;
714                         c = sigret[i];
715                         sigret[i] = sigret[slen - i - 1];
716                         sigret[slen - i - 1] = c;
717                 }
718                 *siglen = slen;
719         }
720
721
722         /* Now cleanup */
723
724 err:
725         CryptDestroyHash(hash);
726
727         return ret;
728 }
729
730 int capi_rsa_priv_dec(int flen, const unsigned char *from,
731                 unsigned char *to, RSA *rsa, int padding)
732 {
733         int i;
734         unsigned char *tmpbuf;
735         CAPI_KEY *capi_key;
736         CAPI_CTX *ctx;
737         ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
738
739         CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
740
741
742         capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
743         if (!capi_key)
744                 {
745                 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY);
746                 return -1;
747                 }
748
749         if(padding != RSA_PKCS1_PADDING)
750                 {
751                 char errstr[10];
752                 sprintf(errstr, "%d", padding);
753                 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
754                 ERR_add_error_data(2, "padding=", errstr);
755                 return -1;
756                 }
757
758         /* Create temp reverse order version of input */
759         if(!(tmpbuf = OPENSSL_malloc(flen)) ) 
760                 {
761                 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
762                 return -1;
763                 }
764         for(i = 0; i < flen; i++) tmpbuf[flen - i - 1] = from[i];
765         
766         /* Finally decrypt it */
767         if(!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen))
768                 {
769                 CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
770                 capi_addlasterror();
771                 OPENSSL_free(tmpbuf);
772                 return -1;
773                 } 
774         else memcpy(to, tmpbuf, flen);
775
776         OPENSSL_free(tmpbuf);
777
778         return flen;
779 }
780
781 static int capi_rsa_free(RSA *rsa)
782         {
783         CAPI_KEY *capi_key;
784         capi_key = RSA_get_ex_data(rsa, rsa_capi_idx);
785         capi_free_key(capi_key);
786         RSA_set_ex_data(rsa, rsa_capi_idx, 0);
787         return 1;
788         }
789
790 static void capi_vtrace(CAPI_CTX *ctx, int level, char *format, va_list argptr)
791         {
792         BIO *out;
793
794         if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file))
795                 return;
796         out = BIO_new_file(ctx->debug_file, "a+");
797         BIO_vprintf(out, format, argptr);
798         BIO_free(out);
799         }
800
801 static void CAPI_trace(CAPI_CTX *ctx, char *format, ...)
802         {
803         va_list args;
804         va_start(args, format);
805         capi_vtrace(ctx, CAPI_DBG_TRACE, format, args);
806         va_end(args);
807         }
808
809 static void capi_addlasterror(void)
810         {
811         capi_adderror(GetLastError());
812         }
813
814 static void capi_adderror(DWORD err)
815         {
816         char errstr[10];
817         sprintf(errstr, "%lX", err);
818         ERR_add_error_data(2, "Error code= 0x", errstr);
819         }
820
821 static char *wide_to_asc(LPWSTR wstr)
822         {
823         char *str;
824         if (!wstr)
825                 return NULL;
826         str = OPENSSL_malloc(wcslen(wstr) + 1);
827         if (!str)
828                 {
829                 CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
830                 return NULL;
831                 }
832         sprintf(str, "%S", wstr);
833         return str;
834         }
835
836 static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype, DWORD idx)
837         {
838         LPSTR name;
839         DWORD len, err;
840         CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx);
841         if (!CryptEnumProviders(idx, NULL, 0, ptype, NULL, &len))
842                 {
843                 err = GetLastError();
844                 if (err == ERROR_NO_MORE_ITEMS)
845                         return 2;
846                 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
847                 capi_adderror(err);
848                 return 0;
849                 }
850         name = OPENSSL_malloc(len);
851                 if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len))
852                 {
853                 err = GetLastError();
854                 if (err == ERROR_NO_MORE_ITEMS)
855                         return 2;
856                 CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR);
857                 capi_adderror(err);
858                 return 0;
859                 }
860         *pname = name;
861         CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", name, *ptype);
862
863         return 1;
864         }
865
866 static int capi_list_providers(CAPI_CTX *ctx, BIO *out)
867         {
868         DWORD idx, ptype;
869         int ret;
870         LPTSTR provname = NULL;
871         CAPI_trace(ctx, "capi_list_providers\n");
872         BIO_printf(out, "Available CSPs:\n");
873         for(idx = 0; ; idx++)
874                 {
875                 ret = capi_get_provname(ctx, &provname, &ptype, idx);
876                 if (ret == 2)
877                         break;
878                 if (ret == 0)
879                         break;
880                 BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
881                 OPENSSL_free(provname);
882                 }
883         return 1;
884         }
885
886 static int capi_list_containers(CAPI_CTX *ctx, BIO *out)
887         {
888         int ret = 1;
889         HCRYPTPROV hprov;
890         DWORD err, idx, flags, buflen = 0, clen;
891         LPSTR cname;
892         CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname, ctx->csptype);
893         if (!CryptAcquireContext(&hprov, NULL, ctx->cspname, ctx->csptype, CRYPT_VERIFYCONTEXT))
894                 {
895                 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
896                 capi_addlasterror();
897                 return 0;
898                 }
899         if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST))
900                 {
901                 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
902                 capi_addlasterror();
903                 return 0;
904                 }
905         CAPI_trace(ctx, "Got max container len %d\n", buflen);
906         if (buflen == 0)
907                 buflen = 1024;
908         cname = OPENSSL_malloc(buflen);
909         if (!cname)
910                 {
911                 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
912                 goto err;
913                 }
914
915         for (idx = 0;;idx++)
916                 {
917                         clen = buflen;
918                         cname[0] = 0;
919
920                         if (idx == 0)
921                                 flags = CRYPT_FIRST;
922                         else
923                                 flags = 0;
924                         if(!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, cname, &clen, flags))
925                                 {
926                                 err = GetLastError();
927                                 if (err == ERROR_NO_MORE_ITEMS)
928                                         goto done;
929                                 CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
930                                 capi_adderror(err);
931                                 goto err;
932                                 }
933                         CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n", cname, clen, idx, flags);
934                         if (!cname[0] && (clen == buflen))
935                                 {
936                                 CAPI_trace(ctx, "Enumerate bug: using workaround\n");
937                                 goto done;
938                                 }
939                         BIO_printf(out, "%d. %s\n", idx, cname);
940                 }
941         err:
942
943         ret = 0;
944
945         done:
946         if (cname)
947                 OPENSSL_free(cname);
948         CryptReleaseContext(hprov, 0);
949
950         return ret;
951         }
952
953 CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
954         {
955         DWORD len;
956         CRYPT_KEY_PROV_INFO *pinfo;
957         
958         if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
959                 return NULL;
960         pinfo = OPENSSL_malloc(len);
961         if (!pinfo)
962                 {
963                 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
964                 return NULL;
965                 }
966         if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len))
967                 {
968                 CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
969                 capi_addlasterror();
970                 OPENSSL_free(pinfo);
971                 return NULL;
972                 }
973         return pinfo;
974         }
975
976 static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out, CRYPT_KEY_PROV_INFO *pinfo)
977         {
978         char *provname = NULL, *contname = NULL;
979         if (!pinfo)
980                 {
981                 BIO_printf(out, "  No Private Key\n");
982                 return;
983                 }
984         provname = wide_to_asc(pinfo->pwszProvName);
985         contname = wide_to_asc(pinfo->pwszContainerName);
986         if (!provname || !contname)
987                 goto err;
988
989         BIO_printf(out, "  Private Key Info:\n");
990         BIO_printf(out, "    Provider Name:  %s, Provider Type %d\n", provname, pinfo->dwProvType);
991         BIO_printf(out, "    Container Name: %s, Key Type %d\n", contname, pinfo->dwKeySpec);
992         err:
993         if (provname)
994                 OPENSSL_free(provname);
995         if (contname)
996                 OPENSSL_free(contname);
997         }
998
999 char * capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1000         {
1001         LPWSTR wfname;
1002         DWORD dlen;
1003
1004         CAPI_trace(ctx, "capi_cert_get_fname\n");
1005         if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
1006                 return NULL;
1007         wfname = OPENSSL_malloc(dlen);
1008         if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen))
1009                 {
1010                 char *fname = wide_to_asc(wfname);
1011                 OPENSSL_free(wfname);
1012                 return fname;
1013                 }
1014         CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME);
1015         capi_addlasterror();
1016
1017         OPENSSL_free(wfname);
1018         return NULL;
1019         }
1020
1021
1022 void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert)
1023         {
1024         X509 *x;
1025         unsigned char *p;
1026         unsigned long flags = ctx->dump_flags;
1027         if (flags & CAPI_DMP_FNAME)
1028                 {
1029                 char *fname;
1030                 fname = capi_cert_get_fname(ctx, cert);
1031                 if (fname)
1032                         {
1033                         BIO_printf(out, "  Friendly Name \"%s\"\n", fname);
1034                         OPENSSL_free(fname);
1035                         }
1036                 else
1037                         BIO_printf(out, "  <No Friendly Name>\n");
1038                 }
1039
1040         p = cert->pbCertEncoded;
1041         x = d2i_X509(NULL, &p, cert->cbCertEncoded);
1042         if (!x)
1043                 BIO_printf(out, "  <Can't parse certificate>\n");
1044         if (flags & CAPI_DMP_SUMMARY)
1045                 {
1046                 BIO_printf(out, "  Subject: ");
1047                 X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
1048                 BIO_printf(out, "\n  Issuer: ");
1049                 X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
1050                 BIO_printf(out, "\n");
1051                 }
1052         if (flags & CAPI_DMP_FULL)
1053                 X509_print_ex(out, x, XN_FLAG_ONELINE,0);
1054
1055         if (flags & CAPI_DMP_PKEYINFO)
1056                 {
1057                 CRYPT_KEY_PROV_INFO *pinfo;
1058                 pinfo = capi_get_prov_info(ctx, cert);
1059                 capi_dump_prov_info(ctx, out, pinfo);
1060                 if (pinfo)
1061                         OPENSSL_free(pinfo);
1062                 }
1063
1064         if (flags & CAPI_DMP_PEM)
1065                 PEM_write_bio_X509(out, x);
1066         X509_free(x);
1067         }
1068
1069 HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename)
1070         {
1071         HCERTSTORE hstore;
1072
1073         if (!storename)
1074                 storename = ctx->storename;
1075         if (!storename)
1076                 storename = "MY";
1077         CAPI_trace(ctx, "Opening certificate store %s\n", storename);
1078
1079         hstore = CertOpenSystemStore(0, storename);
1080         if (!hstore)
1081                 {
1082                 CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE);
1083                 capi_addlasterror();
1084                 }
1085         return hstore;
1086         }
1087
1088 int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id)
1089         {
1090         char *storename;
1091         int idx;
1092         int ret = 1;
1093         HCERTSTORE hstore;
1094         PCCERT_CONTEXT cert = NULL;
1095
1096         storename = ctx->storename;
1097         if (!storename)
1098                 storename = "MY";
1099         CAPI_trace(ctx, "Listing certs for store %s\n", storename);
1100
1101         hstore = capi_open_store(ctx, storename);
1102         if (!hstore)
1103                 return 0;
1104         if (id)
1105                 {
1106                 cert = capi_find_cert(ctx, id, hstore);
1107                 if (!cert)
1108                         {
1109                         ret = 0;
1110                         goto err;
1111                         }
1112                 capi_dump_cert(ctx, out, cert);
1113                 CertFreeCertificateContext(cert);
1114                 }
1115         else
1116                 {
1117                 for(idx = 0;;idx++)
1118                         {
1119                         LPWSTR fname = NULL;
1120                         cert = CertEnumCertificatesInStore(hstore, cert);
1121                         if (!cert)
1122                                 break;
1123                         BIO_printf(out, "Certificate %d\n", idx);
1124                         capi_dump_cert(ctx, out, cert);
1125                         }
1126                 }
1127         err:
1128         CertCloseStore(hstore, 0);
1129         return ret;
1130         }
1131
1132 static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore)
1133         {
1134         PCCERT_CONTEXT cert = NULL;
1135         char *fname = NULL;
1136         int match;
1137         switch(ctx->lookup_method)
1138                 {
1139                 case CAPI_LU_SUBSTR:
1140                         return CertFindCertificateInStore(hstore, X509_ASN_ENCODING, 0, 
1141                                                                                         CERT_FIND_SUBJECT_STR_A, id, NULL);
1142                 case CAPI_LU_FNAME:
1143                         for(;;)
1144                                 {
1145                                 cert = CertEnumCertificatesInStore(hstore, cert);
1146                                 if (!cert)
1147                                         return NULL;
1148                                 fname = capi_cert_get_fname(ctx, cert);
1149                                 if (fname)
1150                                         {
1151                                         if (strcmp(fname, id))
1152                                                 match = 0;
1153                                         else
1154                                                 match = 1;
1155                                         OPENSSL_free(fname);
1156                                         if (match)
1157                                                 return cert;
1158                                         }
1159                                 }
1160                 default:
1161                         return NULL;
1162                 }
1163         }
1164
1165 static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const char *contname, char *provname, DWORD ptype, DWORD keyspec)
1166         {
1167         CAPI_KEY *key;
1168         key = OPENSSL_malloc(sizeof(CAPI_KEY));
1169         CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n", 
1170                                                                                                                         contname, provname, ptype);
1171         if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, 0))
1172                 {
1173                 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1174                 capi_addlasterror();
1175                 goto err;
1176                 }
1177         if (!CryptGetUserKey(key->hprov, keyspec, &key->key))
1178                 {
1179                 CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR);
1180                 capi_addlasterror();
1181                 CryptReleaseContext(key->hprov, 0);
1182                 goto err;
1183                 }
1184         return key;
1185
1186         err:
1187         OPENSSL_free(key);
1188         return NULL;
1189         }
1190
1191 static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
1192         {
1193         CAPI_KEY *key;
1194         CRYPT_KEY_PROV_INFO *pinfo = NULL;
1195         char *provname = NULL, *contname = NULL;
1196         pinfo = capi_get_prov_info(ctx, cert);
1197         if (!pinfo)
1198                 goto err;
1199         provname = wide_to_asc(pinfo->pwszProvName);
1200         contname = wide_to_asc(pinfo->pwszContainerName);
1201         if (!provname || !contname)
1202                 return 0;
1203
1204         key = capi_get_key(ctx, contname, provname, pinfo->dwProvType, pinfo->dwKeySpec);
1205
1206         err:
1207         if (pinfo)
1208                 OPENSSL_free(pinfo);
1209         if (provname)
1210                 OPENSSL_free(provname);
1211         if (contname)
1212                 OPENSSL_free(contname);
1213         return key;
1214         }
1215
1216 CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id)
1217         {
1218         PCCERT_CONTEXT cert;
1219         HCERTSTORE hstore;
1220         CAPI_KEY *key = NULL;
1221         switch (ctx->lookup_method)
1222                 {
1223                 case CAPI_LU_SUBSTR:
1224                 case CAPI_LU_FNAME:
1225                 hstore = capi_open_store(ctx, NULL);
1226                 if (!hstore)
1227                         return NULL;
1228                 cert = capi_find_cert(ctx, id, hstore);
1229                 if (cert)
1230                         {
1231                         key = capi_get_cert_key(ctx, cert);
1232                         CertFreeCertificateContext(cert);
1233                         }
1234                 CertCloseStore(hstore, 0);
1235                 break;
1236
1237                 case CAPI_LU_CONTNAME:
1238                 key = capi_get_key(ctx, id, ctx->cspname, ctx->csptype, ctx->keytype);
1239                 break;
1240                 }
1241
1242         return key;
1243         }
1244
1245 void capi_free_key(CAPI_KEY *key)
1246         {
1247         if (!key)
1248                 return;
1249         CryptDestroyKey(key->key);
1250         CryptReleaseContext(key->hprov, 0);
1251         OPENSSL_free(key);
1252         }
1253
1254
1255 /* Initialize a CAPI_CTX structure */
1256
1257 static CAPI_CTX *capi_ctx_new()
1258         {
1259         CAPI_CTX *ctx;
1260         ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
1261         if (!ctx)
1262                 {
1263                 CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
1264                 return NULL;
1265                 }
1266         ctx->cspname = NULL;
1267         ctx->csptype = PROV_RSA_FULL;
1268         ctx->dump_flags = CAPI_DMP_SUMMARY|CAPI_DMP_FNAME;
1269         ctx->keytype = AT_KEYEXCHANGE;
1270         ctx->storename = NULL;
1271         ctx->lookup_method = CAPI_LU_SUBSTR;
1272         ctx->debug_level = 0;
1273         ctx->debug_file = NULL;
1274         return ctx;
1275         }
1276
1277 static void capi_ctx_free(CAPI_CTX *ctx)
1278         {
1279         CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
1280         if (!ctx)
1281                 return;
1282         if (ctx->cspname)
1283                 OPENSSL_free(ctx->cspname);
1284         if (ctx->debug_file)
1285                 OPENSSL_free(ctx->debug_file);
1286         if (ctx->storename)
1287                 OPENSSL_free(ctx->storename);
1288         OPENSSL_free(ctx);
1289         }
1290
1291 static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check)
1292         {
1293         CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
1294         if (check)
1295                 {
1296                 HCRYPTPROV hprov;
1297                 if (!CryptAcquireContext(&hprov, NULL, pname, type, CRYPT_VERIFYCONTEXT))
1298                         {
1299                         CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
1300                         capi_addlasterror();
1301                         return 0;
1302                         }
1303                 CryptReleaseContext(hprov, 0);
1304                 }
1305         ctx->cspname = BUF_strdup(pname);
1306         ctx->csptype = type;
1307         return 1;
1308         }
1309
1310 static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx)
1311         {
1312         LPSTR pname;
1313         DWORD type;
1314         if (capi_get_provname(ctx, &pname, &type, idx) != 1)
1315                 return 0;
1316         return capi_ctx_set_provname(ctx, pname, type, 0);
1317         }
1318
1319 #endif
1320 #endif