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