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