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