Make reservations for FIPS code in HEAD branch, so that the moment FIPS
[openssl.git] / engines / e_sureware.c
1 /* Written by Corinne Dive-Reclus(cdive@baltimore.com)
2
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer. 
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in
13 *    the documentation and/or other materials provided with the
14 *    distribution.
15 *
16 * 3. All advertising materials mentioning features or use of this
17 *    software must display the following acknowledgment:
18 *    "This product includes software developed by the OpenSSL Project
19 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
20 *
21 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22 *    endorse or promote products derived from this software without
23 *    prior written permission. For written permission, please contact
24 *    licensing@OpenSSL.org.
25 *
26 * 5. Products derived from this software may not be called "OpenSSL"
27 *    nor may "OpenSSL" appear in their names without prior written
28 *    permission of the OpenSSL Project.
29 *
30 * 6. Redistributions of any form whatsoever must retain the following
31 *    acknowledgment:
32 *    "This product includes software developed by the OpenSSL Project
33 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
34 *
35 * Written by Corinne Dive-Reclus(cdive@baltimore.com)
36 *
37 * Copyright@2001 Baltimore Technologies Ltd.
38 * All right Reserved.
39 *                                                                                                                                                                                               *       
40 *               THIS FILE IS PROVIDED BY BALTIMORE TECHNOLOGIES ``AS IS'' AND                                                                                                                                                   *
41 *               ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE                                   * 
42 *               IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE                              *
43 *               ARE DISCLAIMED.  IN NO EVENT SHALL BALTIMORE TECHNOLOGIES BE LIABLE                                             *
44 *               FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL                              *
45 *               DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS                                 *
46 *               OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                                   *
47 *               HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT                              *
48 *               LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY                               *
49 *               OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF                                  *
50 *               SUCH DAMAGE.                                                                                                                                                    *
51 ====================================================================*/
52
53 #include <stdio.h>
54 #include <string.h>
55 #include <openssl/crypto.h>
56 #include <openssl/pem.h>
57 #include <openssl/dso.h>
58 #include <openssl/engine.h>
59 #include <openssl/rand.h>
60 #include <openssl/rsa.h>
61 #include <openssl/dsa.h>
62 #include <openssl/dh.h>
63
64 #ifndef OPENSSL_NO_HW
65 #ifndef OPENSSL_NO_HW_SUREWARE
66
67 #ifdef FLAT_INC
68 #include "sureware.h"
69 #else
70 #include "vendor_defns/sureware.h"
71 #endif
72
73 #define SUREWARE_LIB_NAME "sureware engine"
74 #include "e_sureware_err.c"
75
76 static int surewarehk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void));
77 static int surewarehk_destroy(ENGINE *e);
78 static int surewarehk_init(ENGINE *e);
79 static int surewarehk_finish(ENGINE *e);
80 static int surewarehk_modexp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
81         const BIGNUM *m, BN_CTX *ctx);
82
83 /* RSA stuff */
84 static int surewarehk_rsa_priv_dec(int flen,const unsigned char *from,unsigned char *to,
85                         RSA *rsa,int padding);
86 static int surewarehk_rsa_sign(int flen,const unsigned char *from,unsigned char *to,
87                             RSA *rsa,int padding);
88
89 /* RAND stuff */
90 static int surewarehk_rand_bytes(unsigned char *buf, int num);
91 static void surewarehk_rand_seed(const void *buf, int num);
92 static void surewarehk_rand_add(const void *buf, int num, double entropy);
93
94 /* KM stuff */
95 static EVP_PKEY *surewarehk_load_privkey(ENGINE *e, const char *key_id,
96         UI_METHOD *ui_method, void *callback_data);
97 static EVP_PKEY *surewarehk_load_pubkey(ENGINE *e, const char *key_id,
98         UI_METHOD *ui_method, void *callback_data);
99 static void surewarehk_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
100         int idx,long argl, void *argp);
101 #if 0
102 static void surewarehk_dh_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
103         int idx,long argl, void *argp);
104 #endif
105
106 #ifndef OPENSSL_NO_RSA
107 /* This function is aliased to mod_exp (with the mont stuff dropped). */
108 static int surewarehk_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
109                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
110 {
111         return surewarehk_modexp(r, a, p, m, ctx);
112 }
113
114 /* Our internal RSA_METHOD that we provide pointers to */
115 static RSA_METHOD surewarehk_rsa =
116         {
117         "SureWare RSA method",
118         NULL, /* pub_enc*/
119         NULL, /* pub_dec*/
120         surewarehk_rsa_sign, /* our rsa_sign is OpenSSL priv_enc*/
121         surewarehk_rsa_priv_dec, /* priv_dec*/
122         NULL, /*mod_exp*/
123         surewarehk_mod_exp_mont, /*mod_exp_mongomery*/
124         NULL, /* init*/
125         NULL, /* finish*/
126         0,      /* RSA flag*/
127         NULL, 
128         NULL, /* OpenSSL sign*/
129         NULL, /* OpenSSL verify*/
130         NULL  /* keygen */
131         };
132 #endif
133
134 #ifndef OPENSSL_NO_DH
135 /* Our internal DH_METHOD that we provide pointers to */
136 /* This function is aliased to mod_exp (with the dh and mont dropped). */
137 static int surewarehk_modexp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
138         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
139 {
140         return surewarehk_modexp(r, a, p, m, ctx);
141 }
142
143 static DH_METHOD surewarehk_dh =
144         {
145         "SureWare DH method",
146         NULL,/*gen_key*/
147         NULL,/*agree,*/
148         surewarehk_modexp_dh, /*dh mod exp*/
149         NULL, /* init*/
150         NULL, /* finish*/
151         0,    /* flags*/
152         NULL,
153         NULL
154         };
155 #endif
156
157 static RAND_METHOD surewarehk_rand =
158         {
159         /* "SureWare RAND method", */
160         surewarehk_rand_seed,
161         surewarehk_rand_bytes,
162         NULL,/*cleanup*/
163         surewarehk_rand_add,
164         surewarehk_rand_bytes,
165         NULL,/*rand_status*/
166         };
167
168 #ifndef OPENSSL_NO_DSA
169 /* DSA stuff */
170 static  DSA_SIG * surewarehk_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa);
171 static int surewarehk_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
172                 BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
173                 BN_CTX *ctx, BN_MONT_CTX *in_mont)
174 {
175         BIGNUM t;
176         int to_return = 0;
177         BN_init(&t);
178         /* let rr = a1 ^ p1 mod m */
179         if (!surewarehk_modexp(rr,a1,p1,m,ctx)) goto end;
180         /* let t = a2 ^ p2 mod m */
181         if (!surewarehk_modexp(&t,a2,p2,m,ctx)) goto end;
182         /* let rr = rr * t mod m */
183         if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end;
184         to_return = 1;
185 end:
186         BN_free(&t);
187         return to_return;
188 }
189
190 static DSA_METHOD surewarehk_dsa =
191         {
192          "SureWare DSA method", 
193         surewarehk_dsa_do_sign,
194         NULL,/*sign setup*/
195         NULL,/*verify,*/
196         surewarehk_dsa_mod_exp,/*mod exp*/
197         NULL,/*bn mod exp*/
198         NULL, /*init*/
199         NULL,/*finish*/
200         0,
201         NULL,
202         NULL,
203         NULL
204         };
205 #endif
206
207 static const char *engine_sureware_id = "sureware";
208 static const char *engine_sureware_name = "SureWare hardware engine support";
209
210 /* Now, to our own code */
211
212 /* As this is only ever called once, there's no need for locking
213  * (indeed - the lock will already be held by our caller!!!) */
214 static int bind_sureware(ENGINE *e)
215 {
216 #ifndef OPENSSL_NO_RSA
217         const RSA_METHOD *meth1;
218 #endif
219 #ifndef OPENSSL_NO_DSA
220         const DSA_METHOD *meth2;
221 #endif
222 #ifndef OPENSSL_NO_DH
223         const DH_METHOD *meth3;
224 #endif
225
226         if(!ENGINE_set_id(e, engine_sureware_id) ||
227            !ENGINE_set_name(e, engine_sureware_name) ||
228 #ifndef OPENSSL_NO_RSA
229            !ENGINE_set_RSA(e, &surewarehk_rsa) ||
230 #endif
231 #ifndef OPENSSL_NO_DSA
232            !ENGINE_set_DSA(e, &surewarehk_dsa) ||
233 #endif
234 #ifndef OPENSSL_NO_DH
235            !ENGINE_set_DH(e, &surewarehk_dh) ||
236 #endif
237            !ENGINE_set_RAND(e, &surewarehk_rand) ||
238            !ENGINE_set_destroy_function(e, surewarehk_destroy) ||
239            !ENGINE_set_init_function(e, surewarehk_init) ||
240            !ENGINE_set_finish_function(e, surewarehk_finish) ||
241            !ENGINE_set_ctrl_function(e, surewarehk_ctrl) ||
242            !ENGINE_set_load_privkey_function(e, surewarehk_load_privkey) ||
243            !ENGINE_set_load_pubkey_function(e, surewarehk_load_pubkey))
244           return 0;
245
246 #ifndef OPENSSL_NO_RSA
247         /* We know that the "PKCS1_SSLeay()" functions hook properly
248          * to the cswift-specific mod_exp and mod_exp_crt so we use
249          * those functions. NB: We don't use ENGINE_openssl() or
250          * anything "more generic" because something like the RSAref
251          * code may not hook properly, and if you own one of these
252          * cards then you have the right to do RSA operations on it
253          * anyway! */ 
254         meth1 = RSA_PKCS1_SSLeay();
255         if (meth1)
256         {
257                 surewarehk_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
258                 surewarehk_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
259         }
260 #endif
261
262 #ifndef OPENSSL_NO_DSA
263         /* Use the DSA_OpenSSL() method and just hook the mod_exp-ish
264          * bits. */
265         meth2 = DSA_OpenSSL();
266         if (meth2)
267         {
268                 surewarehk_dsa.dsa_do_verify = meth2->dsa_do_verify;
269         }
270 #endif
271
272 #ifndef OPENSSL_NO_DH
273         /* Much the same for Diffie-Hellman */
274         meth3 = DH_OpenSSL();
275         if (meth3)
276         {
277                 surewarehk_dh.generate_key = meth3->generate_key;
278                 surewarehk_dh.compute_key = meth3->compute_key;
279         }
280 #endif
281
282         /* Ensure the sureware error handling is set up */
283         ERR_load_SUREWARE_strings();
284         return 1;
285 }
286
287 #ifndef OPENSSL_NO_DYNAMIC_ENGINE
288 static int bind_helper(ENGINE *e, const char *id)
289         {
290         if(id && (strcmp(id, engine_sureware_id) != 0))
291                 return 0;
292         if(!bind_sureware(e))
293                 return 0;
294         return 1;
295         }       
296 IMPLEMENT_DYNAMIC_CHECK_FN()
297 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
298 #else
299 static ENGINE *engine_sureware(void)
300         {
301         ENGINE *ret = ENGINE_new();
302         if(!ret)
303                 return NULL;
304         if(!bind_sureware(ret))
305                 {
306                 ENGINE_free(ret);
307                 return NULL;
308                 }
309         return ret;
310         }
311
312 void ENGINE_load_sureware(void)
313         {
314         /* Copied from eng_[openssl|dyn].c */
315         ENGINE *toadd = engine_sureware();
316         if(!toadd) return;
317         ENGINE_add(toadd);
318         ENGINE_free(toadd);
319         ERR_clear_error();
320         }
321 #endif
322
323 /* This is a process-global DSO handle used for loading and unloading
324  * the SureWareHook library. NB: This is only set (or unset) during an
325  * init() or finish() call (reference counts permitting) and they're
326  * operating with global locks, so this should be thread-safe
327  * implicitly. */
328 static DSO *surewarehk_dso = NULL;
329 #ifndef OPENSSL_NO_RSA
330 static int rsaHndidx = -1;      /* Index for KM handle.  Not really used yet. */
331 #endif
332 #ifndef OPENSSL_NO_DSA
333 static int dsaHndidx = -1;      /* Index for KM handle.  Not really used yet. */
334 #endif
335
336 /* These are the function pointers that are (un)set when the library has
337  * successfully (un)loaded. */
338 static SureWareHook_Init_t *p_surewarehk_Init = NULL;
339 static SureWareHook_Finish_t *p_surewarehk_Finish = NULL;
340 static SureWareHook_Rand_Bytes_t *p_surewarehk_Rand_Bytes = NULL;
341 static SureWareHook_Rand_Seed_t *p_surewarehk_Rand_Seed = NULL;
342 static SureWareHook_Load_Privkey_t *p_surewarehk_Load_Privkey = NULL;
343 static SureWareHook_Info_Pubkey_t *p_surewarehk_Info_Pubkey = NULL;
344 static SureWareHook_Load_Rsa_Pubkey_t *p_surewarehk_Load_Rsa_Pubkey = NULL;
345 static SureWareHook_Load_Dsa_Pubkey_t *p_surewarehk_Load_Dsa_Pubkey = NULL;
346 static SureWareHook_Free_t *p_surewarehk_Free=NULL;
347 static SureWareHook_Rsa_Priv_Dec_t *p_surewarehk_Rsa_Priv_Dec=NULL;
348 static SureWareHook_Rsa_Sign_t *p_surewarehk_Rsa_Sign=NULL;
349 static SureWareHook_Dsa_Sign_t *p_surewarehk_Dsa_Sign=NULL;
350 static SureWareHook_Mod_Exp_t *p_surewarehk_Mod_Exp=NULL;
351
352 /* Used in the DSO operations. */
353 static const char *surewarehk_LIBNAME = "SureWareHook";
354 static const char *n_surewarehk_Init = "SureWareHook_Init";
355 static const char *n_surewarehk_Finish = "SureWareHook_Finish";
356 static const char *n_surewarehk_Rand_Bytes="SureWareHook_Rand_Bytes";
357 static const char *n_surewarehk_Rand_Seed="SureWareHook_Rand_Seed";
358 static const char *n_surewarehk_Load_Privkey="SureWareHook_Load_Privkey";
359 static const char *n_surewarehk_Info_Pubkey="SureWareHook_Info_Pubkey";
360 static const char *n_surewarehk_Load_Rsa_Pubkey="SureWareHook_Load_Rsa_Pubkey";
361 static const char *n_surewarehk_Load_Dsa_Pubkey="SureWareHook_Load_Dsa_Pubkey";
362 static const char *n_surewarehk_Free="SureWareHook_Free";
363 static const char *n_surewarehk_Rsa_Priv_Dec="SureWareHook_Rsa_Priv_Dec";
364 static const char *n_surewarehk_Rsa_Sign="SureWareHook_Rsa_Sign";
365 static const char *n_surewarehk_Dsa_Sign="SureWareHook_Dsa_Sign";
366 static const char *n_surewarehk_Mod_Exp="SureWareHook_Mod_Exp";
367 static BIO *logstream = NULL;
368
369 /* SureWareHook library functions and mechanics - these are used by the
370  * higher-level functions further down. NB: As and where there's no
371  * error checking, take a look lower down where these functions are
372  * called, the checking and error handling is probably down there. 
373 */
374 static int threadsafe=1;
375 static int surewarehk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
376 {
377         int to_return = 1;
378
379         switch(cmd)
380         {
381                 case ENGINE_CTRL_SET_LOGSTREAM:
382                 {
383                         BIO *bio = (BIO *)p;
384                         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
385                         if (logstream)
386                         {
387                                 BIO_free(logstream);
388                                 logstream = NULL;
389                         }
390                         if (CRYPTO_add(&bio->references,1,CRYPTO_LOCK_BIO) > 1)
391                                 logstream = bio;
392                         else
393                                 SUREWAREerr(SUREWARE_F_SUREWAREHK_CTRL,SUREWARE_R_BIO_WAS_FREED);
394                 }
395                 CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
396                 break;
397         /* This will prevent the initialisation function from "installing"
398          * the mutex-handling callbacks, even if they are available from
399          * within the library (or were provided to the library from the
400          * calling application). This is to remove any baggage for
401          * applications not using multithreading. */
402         case ENGINE_CTRL_CHIL_NO_LOCKING:
403                 CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
404                 threadsafe = 0;
405                 CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
406                 break;
407
408         /* The command isn't understood by this engine */
409         default:
410                 SUREWAREerr(SUREWARE_F_SUREWAREHK_CTRL,
411                         ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED);
412                 to_return = 0;
413                 break;
414                 }
415
416         return to_return;
417 }
418
419 /* Destructor (complements the "ENGINE_surewarehk()" constructor) */
420 static int surewarehk_destroy(ENGINE *e)
421 {
422         ERR_unload_SUREWARE_strings();
423         return 1;
424 }
425
426 /* (de)initialisation functions. */
427 static int surewarehk_init(ENGINE *e)
428 {
429         char msg[64]="ENGINE_init";
430         SureWareHook_Init_t *p1=NULL;
431         SureWareHook_Finish_t *p2=NULL;
432         SureWareHook_Rand_Bytes_t *p3=NULL;
433         SureWareHook_Rand_Seed_t *p4=NULL;
434         SureWareHook_Load_Privkey_t *p5=NULL;
435         SureWareHook_Load_Rsa_Pubkey_t *p6=NULL;
436         SureWareHook_Free_t *p7=NULL;
437         SureWareHook_Rsa_Priv_Dec_t *p8=NULL;
438         SureWareHook_Rsa_Sign_t *p9=NULL;
439         SureWareHook_Dsa_Sign_t *p12=NULL;
440         SureWareHook_Info_Pubkey_t *p13=NULL;
441         SureWareHook_Load_Dsa_Pubkey_t *p14=NULL;
442         SureWareHook_Mod_Exp_t *p15=NULL;
443
444         if(surewarehk_dso != NULL)
445         {
446                 SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,ENGINE_R_ALREADY_LOADED);
447                 goto err;
448         }
449         /* Attempt to load libsurewarehk.so/surewarehk.dll/whatever. */
450         surewarehk_dso = DSO_load(NULL, surewarehk_LIBNAME, NULL, 0);
451         if(surewarehk_dso == NULL)
452         {
453                 SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,ENGINE_R_DSO_FAILURE);
454                 goto err;
455         }
456         if(!(p1=(SureWareHook_Init_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Init)) ||
457            !(p2=(SureWareHook_Finish_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Finish)) ||
458            !(p3=(SureWareHook_Rand_Bytes_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rand_Bytes)) ||
459            !(p4=(SureWareHook_Rand_Seed_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rand_Seed)) ||
460            !(p5=(SureWareHook_Load_Privkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Load_Privkey)) ||
461            !(p6=(SureWareHook_Load_Rsa_Pubkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Load_Rsa_Pubkey)) ||
462            !(p7=(SureWareHook_Free_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Free)) ||
463            !(p8=(SureWareHook_Rsa_Priv_Dec_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rsa_Priv_Dec)) ||
464            !(p9=(SureWareHook_Rsa_Sign_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rsa_Sign)) ||
465            !(p12=(SureWareHook_Dsa_Sign_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Dsa_Sign)) ||
466            !(p13=(SureWareHook_Info_Pubkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Info_Pubkey)) ||
467            !(p14=(SureWareHook_Load_Dsa_Pubkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Load_Dsa_Pubkey)) ||
468            !(p15=(SureWareHook_Mod_Exp_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Mod_Exp)))
469         {
470                 SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,ENGINE_R_DSO_FAILURE);
471                 goto err;
472         }
473         /* Copy the pointers */
474         p_surewarehk_Init = p1;
475         p_surewarehk_Finish = p2;
476         p_surewarehk_Rand_Bytes = p3;
477         p_surewarehk_Rand_Seed = p4;
478         p_surewarehk_Load_Privkey = p5;
479         p_surewarehk_Load_Rsa_Pubkey = p6;
480         p_surewarehk_Free = p7;
481         p_surewarehk_Rsa_Priv_Dec = p8;
482         p_surewarehk_Rsa_Sign = p9;
483         p_surewarehk_Dsa_Sign = p12;
484         p_surewarehk_Info_Pubkey = p13;
485         p_surewarehk_Load_Dsa_Pubkey = p14;
486         p_surewarehk_Mod_Exp = p15;
487         /* Contact the hardware and initialises it. */
488         if(p_surewarehk_Init(msg,threadsafe)==SUREWAREHOOK_ERROR_UNIT_FAILURE)
489         {
490                 SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,SUREWARE_R_UNIT_FAILURE);
491                 goto err;
492         }
493         if(p_surewarehk_Init(msg,threadsafe)==SUREWAREHOOK_ERROR_UNIT_FAILURE)
494         {
495                 SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,SUREWARE_R_UNIT_FAILURE);
496                 goto err;
497         }
498         /* try to load the default private key, if failed does not return a failure but
499            wait for an explicit ENGINE_load_privakey */
500         surewarehk_load_privkey(e,NULL,NULL,NULL);
501
502         /* Everything's fine. */
503 #ifndef OPENSSL_NO_RSA
504         if (rsaHndidx == -1)
505                 rsaHndidx = RSA_get_ex_new_index(0,
506                                                 "SureWareHook RSA key handle",
507                                                 NULL, NULL, surewarehk_ex_free);
508 #endif
509 #ifndef OPENSSL_NO_DSA
510         if (dsaHndidx == -1)
511                 dsaHndidx = DSA_get_ex_new_index(0,
512                                                 "SureWareHook DSA key handle",
513                                                 NULL, NULL, surewarehk_ex_free);
514 #endif
515
516         return 1;
517 err:
518         if(surewarehk_dso)
519                 DSO_free(surewarehk_dso);
520         surewarehk_dso = NULL;
521         p_surewarehk_Init = NULL;
522         p_surewarehk_Finish = NULL;
523         p_surewarehk_Rand_Bytes = NULL;
524         p_surewarehk_Rand_Seed = NULL;
525         p_surewarehk_Load_Privkey = NULL;
526         p_surewarehk_Load_Rsa_Pubkey = NULL;
527         p_surewarehk_Free = NULL;
528         p_surewarehk_Rsa_Priv_Dec = NULL;
529         p_surewarehk_Rsa_Sign = NULL;
530         p_surewarehk_Dsa_Sign = NULL;
531         p_surewarehk_Info_Pubkey = NULL;
532         p_surewarehk_Load_Dsa_Pubkey = NULL;
533         p_surewarehk_Mod_Exp = NULL;
534         return 0;
535 }
536
537 static int surewarehk_finish(ENGINE *e)
538 {
539         int to_return = 1;
540         if(surewarehk_dso == NULL)
541                 {
542                 SUREWAREerr(SUREWARE_F_SUREWAREHK_FINISH,ENGINE_R_NOT_LOADED);
543                 to_return = 0;
544                 goto err;
545                 }
546         p_surewarehk_Finish();
547         if(!DSO_free(surewarehk_dso))
548                 {
549                 SUREWAREerr(SUREWARE_F_SUREWAREHK_FINISH,ENGINE_R_DSO_FAILURE);
550                 to_return = 0;
551                 goto err;
552                 }
553  err:
554         if (logstream)
555                 BIO_free(logstream);
556         surewarehk_dso = NULL;
557         p_surewarehk_Init = NULL;
558         p_surewarehk_Finish = NULL;
559         p_surewarehk_Rand_Bytes = NULL;
560         p_surewarehk_Rand_Seed = NULL;
561         p_surewarehk_Load_Privkey = NULL;
562         p_surewarehk_Load_Rsa_Pubkey = NULL;
563         p_surewarehk_Free = NULL;
564         p_surewarehk_Rsa_Priv_Dec = NULL;
565         p_surewarehk_Rsa_Sign = NULL;
566         p_surewarehk_Dsa_Sign = NULL;
567         p_surewarehk_Info_Pubkey = NULL;
568         p_surewarehk_Load_Dsa_Pubkey = NULL;
569         p_surewarehk_Mod_Exp = NULL;
570         return to_return;
571 }
572
573 static void surewarehk_error_handling(char *const msg,int func,int ret)
574 {
575         switch (ret)
576         {
577                 case SUREWAREHOOK_ERROR_UNIT_FAILURE:
578                         ENGINEerr(func,SUREWARE_R_UNIT_FAILURE);
579                         break;
580                 case SUREWAREHOOK_ERROR_FALLBACK:
581                         ENGINEerr(func,SUREWARE_R_REQUEST_FALLBACK);
582                         break;
583                 case SUREWAREHOOK_ERROR_DATA_SIZE:
584                         ENGINEerr(func,SUREWARE_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
585                         break;
586                 case SUREWAREHOOK_ERROR_INVALID_PAD:
587                         ENGINEerr(func,RSA_R_PADDING_CHECK_FAILED);
588                         break;
589                 default:
590                         ENGINEerr(func,SUREWARE_R_REQUEST_FAILED);
591                         break;
592                 case 1:/*nothing*/
593                         msg[0]='\0';
594         }
595         if (*msg)
596         {
597                 ERR_add_error_data(1,msg);
598                 if (logstream)
599                 {
600                         CRYPTO_w_lock(CRYPTO_LOCK_BIO);
601                         BIO_write(logstream, msg, strlen(msg));
602                         CRYPTO_w_unlock(CRYPTO_LOCK_BIO);
603                 }
604         }
605 }
606
607 static int surewarehk_rand_bytes(unsigned char *buf, int num)
608 {
609         int ret=0;
610         char msg[64]="ENGINE_rand_bytes";
611         if(!p_surewarehk_Rand_Bytes)
612         {
613                 SUREWAREerr(SUREWARE_F_SUREWAREHK_RAND_BYTES,ENGINE_R_NOT_INITIALISED);
614         }
615         else
616         {
617                 ret = p_surewarehk_Rand_Bytes(msg,buf, num);
618                 surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RAND_BYTES,ret);
619         }
620         return ret==1 ? 1 : 0;
621 }
622
623 static void surewarehk_rand_seed(const void *buf, int num)
624 {
625         int ret=0;
626         char msg[64]="ENGINE_rand_seed";
627         if(!p_surewarehk_Rand_Seed)
628         {
629                 SUREWAREerr(SUREWARE_F_SUREWAREHK_RAND_SEED,ENGINE_R_NOT_INITIALISED);
630         }
631         else
632         {
633                 ret = p_surewarehk_Rand_Seed(msg,buf, num);
634                 surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RAND_SEED,ret);
635         }
636 }
637
638 static void surewarehk_rand_add(const void *buf, int num, double entropy)
639 {
640         surewarehk_rand_seed(buf,num);
641 }
642
643 static EVP_PKEY* sureware_load_public(ENGINE *e,const char *key_id,char *hptr,unsigned long el,char keytype)
644 {
645         EVP_PKEY *res = NULL;
646 #ifndef OPENSSL_NO_RSA
647         RSA *rsatmp = NULL;
648 #endif
649 #ifndef OPENSSL_NO_DSA
650         DSA *dsatmp=NULL;
651 #endif
652         char msg[64]="sureware_load_public";
653         int ret=0;
654         if(!p_surewarehk_Load_Rsa_Pubkey || !p_surewarehk_Load_Dsa_Pubkey)
655         {
656                 SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PUBLIC_KEY,ENGINE_R_NOT_INITIALISED);
657                 goto err;
658         }
659         switch (keytype)
660         {
661 #ifndef OPENSSL_NO_RSA
662         case 1: /*RSA*/
663                 /* set private external reference */
664                 rsatmp = RSA_new_method(e);
665                 RSA_set_ex_data(rsatmp,rsaHndidx,hptr);
666                 rsatmp->flags |= RSA_FLAG_EXT_PKEY;
667
668                 /* set public big nums*/
669                 rsatmp->e = BN_new();
670                 rsatmp->n = BN_new();
671                 bn_expand2(rsatmp->e, el/sizeof(BN_ULONG));
672                 bn_expand2(rsatmp->n, el/sizeof(BN_ULONG));
673                 if (!rsatmp->e || rsatmp->e->dmax!=(int)(el/sizeof(BN_ULONG))|| 
674                         !rsatmp->n || rsatmp->n->dmax!=(int)(el/sizeof(BN_ULONG)))
675                         goto err;
676                 ret=p_surewarehk_Load_Rsa_Pubkey(msg,key_id,el,
677                                                  (unsigned long *)rsatmp->n->d,
678                                                  (unsigned long *)rsatmp->e->d);
679                 surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_LOAD_PUBLIC_KEY,ret);
680                 if (ret!=1)
681                 {
682                         SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PRIVATE_KEY,ENGINE_R_FAILED_LOADING_PUBLIC_KEY);
683                         goto err;
684                 }
685                 /* normalise pub e and pub n */
686                 rsatmp->e->top=el/sizeof(BN_ULONG);
687                 bn_fix_top(rsatmp->e);
688                 rsatmp->n->top=el/sizeof(BN_ULONG);
689                 bn_fix_top(rsatmp->n);
690                 /* create an EVP object: engine + rsa key */
691                 res = EVP_PKEY_new();
692                 EVP_PKEY_assign_RSA(res, rsatmp);
693                 break;
694 #endif
695
696 #ifndef OPENSSL_NO_DSA
697         case 2:/*DSA*/
698                 /* set private/public external reference */
699                 dsatmp = DSA_new_method(e);
700                 DSA_set_ex_data(dsatmp,dsaHndidx,hptr);
701                 /*dsatmp->flags |= DSA_FLAG_EXT_PKEY;*/
702
703                 /* set public key*/
704                 dsatmp->pub_key = BN_new();
705                 dsatmp->p = BN_new();
706                 dsatmp->q = BN_new();
707                 dsatmp->g = BN_new();
708                 bn_expand2(dsatmp->pub_key, el/sizeof(BN_ULONG));
709                 bn_expand2(dsatmp->p, el/sizeof(BN_ULONG));
710                 bn_expand2(dsatmp->q, 20/sizeof(BN_ULONG));
711                 bn_expand2(dsatmp->g, el/sizeof(BN_ULONG));
712                 if (!dsatmp->pub_key || dsatmp->pub_key->dmax!=(int)(el/sizeof(BN_ULONG))|| 
713                         !dsatmp->p || dsatmp->p->dmax!=(int)(el/sizeof(BN_ULONG)) ||
714                         !dsatmp->q || dsatmp->q->dmax!=20/sizeof(BN_ULONG) ||
715                         !dsatmp->g || dsatmp->g->dmax!=(int)(el/sizeof(BN_ULONG)))
716                         goto err;
717
718                 ret=p_surewarehk_Load_Dsa_Pubkey(msg,key_id,el,
719                                                  (unsigned long *)dsatmp->pub_key->d, 
720                                                  (unsigned long *)dsatmp->p->d,
721                                                  (unsigned long *)dsatmp->q->d,
722                                                  (unsigned long *)dsatmp->g->d);
723                 surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_LOAD_PUBLIC_KEY,ret);
724                 if (ret!=1)
725                 {
726                         SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PRIVATE_KEY,ENGINE_R_FAILED_LOADING_PUBLIC_KEY);
727                         goto err;
728                 }
729                 /* set parameters */
730                 /* normalise pubkey and parameters in case of */
731                 dsatmp->pub_key->top=el/sizeof(BN_ULONG);
732                 bn_fix_top(dsatmp->pub_key);
733                 dsatmp->p->top=el/sizeof(BN_ULONG);
734                 bn_fix_top(dsatmp->p);
735                 dsatmp->q->top=20/sizeof(BN_ULONG);
736                 bn_fix_top(dsatmp->q);
737                 dsatmp->g->top=el/sizeof(BN_ULONG);
738                 bn_fix_top(dsatmp->g);
739
740                 /* create an EVP object: engine + rsa key */
741                 res = EVP_PKEY_new();
742                 EVP_PKEY_assign_DSA(res, dsatmp);
743                 break;
744 #endif
745
746         default:
747                 SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PRIVATE_KEY,ENGINE_R_FAILED_LOADING_PRIVATE_KEY);
748                 goto err;
749         }
750         return res;
751  err:
752         if (res)
753                 EVP_PKEY_free(res);
754 #ifndef OPENSSL_NO_RSA
755         if (rsatmp)
756                 RSA_free(rsatmp);
757 #endif
758 #ifndef OPENSSL_NO_DSA
759         if (dsatmp)
760                 DSA_free(dsatmp);
761 #endif
762         return NULL;
763 }
764
765 static EVP_PKEY *surewarehk_load_privkey(ENGINE *e, const char *key_id,
766                                          UI_METHOD *ui_method, void *callback_data)
767 {
768         EVP_PKEY *res = NULL;
769         int ret=0;
770         unsigned long el=0;
771         char *hptr=NULL;
772         char keytype=0;
773         char msg[64]="ENGINE_load_privkey";
774
775         if(!p_surewarehk_Load_Privkey)
776         {
777                 SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PRIVATE_KEY,ENGINE_R_NOT_INITIALISED);
778         }
779         else
780         {
781                 ret=p_surewarehk_Load_Privkey(msg,key_id,&hptr,&el,&keytype);
782                 if (ret!=1)
783                 {
784                         SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PRIVATE_KEY,ENGINE_R_FAILED_LOADING_PRIVATE_KEY);
785                         ERR_add_error_data(1,msg);              
786                 }
787                 else
788                         res=sureware_load_public(e,key_id,hptr,el,keytype);
789         }
790         return res;
791 }
792
793 static EVP_PKEY *surewarehk_load_pubkey(ENGINE *e, const char *key_id,
794                                          UI_METHOD *ui_method, void *callback_data)
795 {
796         EVP_PKEY *res = NULL;
797         int ret=0;
798         unsigned long el=0;
799         char *hptr=NULL;
800         char keytype=0;
801         char msg[64]="ENGINE_load_pubkey";
802
803         if(!p_surewarehk_Info_Pubkey)
804         {
805                 SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PUBLIC_KEY,ENGINE_R_NOT_INITIALISED);
806         }
807         else
808         {
809                 /* call once to identify if DSA or RSA */
810                 ret=p_surewarehk_Info_Pubkey(msg,key_id,&el,&keytype);
811                 if (ret!=1)
812                 {
813                         SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PUBLIC_KEY,ENGINE_R_FAILED_LOADING_PUBLIC_KEY);
814                         ERR_add_error_data(1,msg);
815                 }
816                 else
817                         res=sureware_load_public(e,key_id,hptr,el,keytype);
818         }
819         return res;
820 }
821
822 /* This cleans up an RSA/DSA KM key(do not destroy the key into the hardware)
823 , called when ex_data is freed */
824 static void surewarehk_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
825         int idx,long argl, void *argp)
826 {
827         if(!p_surewarehk_Free)
828         {
829                 SUREWAREerr(SUREWARE_F_SUREWAREHK_EX_FREE,ENGINE_R_NOT_INITIALISED);
830         }
831         else
832                 p_surewarehk_Free((char *)item,0);
833 }
834
835 #if 0
836 /* not currently used (bug?) */
837 /* This cleans up an DH KM key (destroys the key into hardware), 
838 called when ex_data is freed */
839 static void surewarehk_dh_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
840         int idx,long argl, void *argp)
841 {
842         if(!p_surewarehk_Free)
843         {
844                 SUREWAREerr(SUREWARE_F_SUREWAREHK_EX_FREE,ENGINE_R_NOT_INITIALISED);
845         }
846         else
847                 p_surewarehk_Free((char *)item,1);
848 }
849 #endif
850
851 /*
852 * return number of decrypted bytes
853 */
854 #ifndef OPENSSL_NO_RSA
855 static int surewarehk_rsa_priv_dec(int flen,const unsigned char *from,unsigned char *to,
856                         RSA *rsa,int padding)
857 {
858         int ret=0,tlen;
859         char *buf=NULL,*hptr=NULL;
860         char msg[64]="ENGINE_rsa_priv_dec";
861         if (!p_surewarehk_Rsa_Priv_Dec)
862         {
863                 SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ENGINE_R_NOT_INITIALISED);
864         }
865         /* extract ref to private key */
866         else if (!(hptr=RSA_get_ex_data(rsa, rsaHndidx)))
867         {
868                 SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,SUREWARE_R_MISSING_KEY_COMPONENTS);
869                 goto err;
870         }
871         /* analyse what padding we can do into the hardware */
872         if (padding==RSA_PKCS1_PADDING)
873         {
874                 /* do it one shot */
875                 ret=p_surewarehk_Rsa_Priv_Dec(msg,flen,(unsigned char *)from,&tlen,to,hptr,SUREWARE_PKCS1_PAD);
876                 surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ret);
877                 if (ret!=1)
878                         goto err;
879                 ret=tlen;
880         }
881         else /* do with no padding into hardware */
882         {
883                 ret=p_surewarehk_Rsa_Priv_Dec(msg,flen,(unsigned char *)from,&tlen,to,hptr,SUREWARE_NO_PAD);
884                 surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ret);
885                 if (ret!=1)
886                         goto err;
887                 /* intermediate buffer for padding */
888                 if ((buf=OPENSSL_malloc(tlen)) == NULL)
889                 {
890                         RSAerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ERR_R_MALLOC_FAILURE);
891                         goto err;
892                 }
893                 memcpy(buf,to,tlen);/* transfert to into buf */
894                 switch (padding) /* check padding in software */
895                 {
896 #ifndef OPENSSL_NO_SHA
897                 case RSA_PKCS1_OAEP_PADDING:
898                         ret=RSA_padding_check_PKCS1_OAEP(to,tlen,(unsigned char *)buf,tlen,tlen,NULL,0);
899                         break;
900 #endif
901                 case RSA_SSLV23_PADDING:
902                         ret=RSA_padding_check_SSLv23(to,tlen,(unsigned char *)buf,flen,tlen);
903                         break;
904                 case RSA_NO_PADDING:
905                         ret=RSA_padding_check_none(to,tlen,(unsigned char *)buf,flen,tlen);
906                         break;
907                 default:
908                         RSAerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,RSA_R_UNKNOWN_PADDING_TYPE);
909                         goto err;
910                 }
911                 if (ret < 0)
912                         RSAerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,RSA_R_PADDING_CHECK_FAILED);
913         }
914 err:
915         if (buf)
916         {
917                 OPENSSL_cleanse(buf,tlen);
918                 OPENSSL_free(buf);
919         }
920         return ret;
921 }
922
923 /*
924 * Does what OpenSSL rsa_priv_enc does.
925 */
926 static int surewarehk_rsa_sign(int flen,const unsigned char *from,unsigned char *to,
927                             RSA *rsa,int padding)
928 {
929         int ret=0,tlen;
930         char *hptr=NULL;
931         char msg[64]="ENGINE_rsa_sign";
932         if (!p_surewarehk_Rsa_Sign)
933         {
934                 SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_ENC,ENGINE_R_NOT_INITIALISED);
935         }
936         /* extract ref to private key */
937         else if (!(hptr=RSA_get_ex_data(rsa, rsaHndidx)))
938         {
939                 SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_ENC,SUREWARE_R_MISSING_KEY_COMPONENTS);
940         }
941         else
942         {
943                 switch (padding)
944                 {
945                 case RSA_PKCS1_PADDING: /* do it in one shot */
946                         ret=p_surewarehk_Rsa_Sign(msg,flen,(unsigned char *)from,&tlen,to,hptr,SUREWARE_PKCS1_PAD);
947                         surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RSA_PRIV_ENC,ret);
948                         break;
949                 case RSA_NO_PADDING:
950                 default:
951                         RSAerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_ENC,RSA_R_UNKNOWN_PADDING_TYPE);
952                 }
953         }
954         return ret==1 ? tlen : ret;
955 }
956
957 #endif
958
959 #ifndef OPENSSL_NO_DSA
960 /* DSA sign and verify */
961 static  DSA_SIG * surewarehk_dsa_do_sign(const unsigned char *from, int flen, DSA *dsa)
962 {
963         int ret=0;
964         char *hptr=NULL;
965         DSA_SIG *psign=NULL;
966         char msg[64]="ENGINE_dsa_do_sign";
967         if (!p_surewarehk_Dsa_Sign)
968         {
969                 SUREWAREerr(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,ENGINE_R_NOT_INITIALISED);
970         }
971         /* extract ref to private key */
972         else if (!(hptr=DSA_get_ex_data(dsa, dsaHndidx)))
973         {
974                 SUREWAREerr(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,SUREWARE_R_MISSING_KEY_COMPONENTS);
975         }
976         else
977         {
978                 if((psign = DSA_SIG_new()) == NULL)
979                 {
980                         SUREWAREerr(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,ERR_R_MALLOC_FAILURE);
981                         goto err;
982                 }
983                 psign->r=BN_new();
984                 psign->s=BN_new();
985                 bn_expand2(psign->r, 20/sizeof(BN_ULONG));
986                 bn_expand2(psign->s, 20/sizeof(BN_ULONG));
987                 if (!psign->r || psign->r->dmax!=20/sizeof(BN_ULONG) ||
988                         !psign->s || psign->s->dmax!=20/sizeof(BN_ULONG))
989                         goto err;
990                 ret=p_surewarehk_Dsa_Sign(msg,flen,from,
991                                           (unsigned long *)psign->r->d,
992                                           (unsigned long *)psign->s->d,
993                                           hptr);
994                 surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,ret);
995         }
996         psign->r->top=20/sizeof(BN_ULONG);
997         bn_fix_top(psign->r);
998         psign->s->top=20/sizeof(BN_ULONG);
999         bn_fix_top(psign->s);
1000
1001 err:    
1002         if (psign)
1003         {
1004                 DSA_SIG_free(psign);
1005                 psign=NULL;
1006         }
1007         return psign;
1008 }
1009 #endif
1010
1011 static int surewarehk_modexp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1012                              const BIGNUM *m, BN_CTX *ctx)
1013 {
1014         int ret=0;
1015         char msg[64]="ENGINE_modexp";
1016         if (!p_surewarehk_Mod_Exp)
1017         {
1018                 SUREWAREerr(SUREWARE_F_SUREWAREHK_MOD_EXP,ENGINE_R_NOT_INITIALISED);
1019         }
1020         else
1021         {
1022                 bn_expand2(r,m->top);
1023                 if (r && r->dmax==m->top)
1024                 {
1025                         /* do it*/
1026                         ret=p_surewarehk_Mod_Exp(msg,
1027                                                  m->top*sizeof(BN_ULONG),
1028                                                  (unsigned long *)m->d,
1029                                                  p->top*sizeof(BN_ULONG),
1030                                                  (unsigned long *)p->d,
1031                                                  a->top*sizeof(BN_ULONG),
1032                                                  (unsigned long *)a->d,
1033                                                  (unsigned long *)r->d);
1034                         surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_MOD_EXP,ret);
1035                         if (ret==1)
1036                         {
1037                                 /* normalise result */
1038                                 r->top=m->top;
1039                                 bn_fix_top(r);
1040                         }
1041                 }
1042         }
1043         return ret;
1044 }
1045 #endif /* !OPENSSL_NO_HW_SureWare */
1046 #endif /* !OPENSSL_NO_HW */