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