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