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