Remove an unused variable.
[openssl.git] / crypto / engine / hw_aep.c
1 /* crypto/engine/hw_aep.c */
2 /*
3  */
4 /* ====================================================================
5  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer. 
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. All advertising materials mentioning features or use of this
20  *    software must display the following acknowledgment:
21  *    "This product includes software developed by the OpenSSL Project
22  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
23  *
24  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
25  *    endorse or promote products derived from this software without
26  *    prior written permission. For written permission, please contact
27  *    licensing@OpenSSL.org.
28  *
29  * 5. Products derived from this software may not be called "OpenSSL"
30  *    nor may "OpenSSL" appear in their names without prior written
31  *    permission of the OpenSSL Project.
32  *
33  * 6. Redistributions of any form whatsoever must retain the following
34  *    acknowledgment:
35  *    "This product includes software developed by the OpenSSL Project
36  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
39  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
41  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
42  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
44  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
45  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
47  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
49  * OF THE POSSIBILITY OF SUCH DAMAGE.
50  * ====================================================================
51  *
52  * This product includes cryptographic software written by Eric Young
53  * (eay@cryptsoft.com).  This product includes software written by Tim
54  * Hudson (tjh@cryptsoft.com).
55  *
56  */
57
58 #include <stdio.h>
59 #include <openssl/bn.h>
60 #include <string.h>
61
62 #include <openssl/e_os2.h>
63 #ifndef OPENSSL_SYS_MSDOS
64 #include <sys/types.h>
65 #include <unistd.h>
66 #else
67 #include <process.h>
68 typedef int pid_t;
69 #endif
70
71 #include <openssl/crypto.h>
72 #include <openssl/dso.h>
73 #include <openssl/engine.h>
74
75 #ifndef OPENSSL_NO_HW
76 #ifndef OPENSSL_NO_HW_AEP
77 #ifdef FLAT_INC
78 #include "aep.h"
79 #else
80 #include "vendor_defns/aep.h"
81 #endif
82
83 #define AEP_LIB_NAME "aep engine"
84 #include "hw_aep_err.c"
85
86 static int aep_init(ENGINE *e);
87 static int aep_finish(ENGINE *e);
88 static int aep_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
89 static int aep_destroy(ENGINE *e);
90
91 static AEP_RV aep_get_connection(AEP_CONNECTION_HNDL_PTR hConnection);
92 static AEP_RV aep_return_connection(AEP_CONNECTION_HNDL hConnection);
93 static AEP_RV aep_close_all_connections(int use_engine_lock, int *in_use);
94
95 /* BIGNUM stuff */
96 static int aep_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
97         const BIGNUM *m, BN_CTX *ctx);
98
99 static AEP_RV aep_mod_exp_crt(BIGNUM *r,const  BIGNUM *a, const BIGNUM *p,
100         const BIGNUM *q, const BIGNUM *dmp1,const BIGNUM *dmq1,
101         const BIGNUM *iqmp, BN_CTX *ctx);
102
103 /* RSA stuff */
104 #ifndef OPENSSL_NO_RSA
105 static int aep_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa);
106 #endif
107
108 /* This function is aliased to mod_exp (with the mont stuff dropped). */
109 static int aep_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
110         const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
111
112 /* DSA stuff */
113 #ifndef OPENSSL_NO_DSA
114 static int aep_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
115         BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
116         BN_CTX *ctx, BN_MONT_CTX *in_mont);
117
118 static int aep_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
119         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
120         BN_MONT_CTX *m_ctx);
121 #endif
122
123 /* DH stuff */
124 /* This function is aliased to mod_exp (with the DH and mont dropped). */
125 #ifndef OPENSSL_NO_DH
126 static int aep_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
127         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
128 #endif
129
130 /* rand stuff   */
131 #ifdef AEPRAND
132 static int aep_rand(unsigned char *buf, int num);
133 static int aep_rand_status(void);
134 #endif
135
136 /* Bignum conversion stuff */
137 static AEP_RV GetBigNumSize(void* ArbBigNum, AEP_U32* BigNumSize);
138 static AEP_RV MakeAEPBigNum(void* ArbBigNum, AEP_U32 BigNumSize,
139         unsigned char* AEP_BigNum);
140 static AEP_RV ConvertAEPBigNum(void* ArbBigNum, AEP_U32 BigNumSize,
141         unsigned char* AEP_BigNum);
142
143 /* The definitions for control commands specific to this engine */
144 #define AEP_CMD_SO_PATH         ENGINE_CMD_BASE
145 static const ENGINE_CMD_DEFN aep_cmd_defns[] =
146         {
147         { AEP_CMD_SO_PATH,
148           "SO_PATH",
149           "Specifies the path to the 'aep' shared library",
150           ENGINE_CMD_FLAG_STRING
151         },
152         {0, NULL, NULL, 0}
153         };
154
155 #ifndef OPENSSL_NO_RSA
156 /* Our internal RSA_METHOD that we provide pointers to */
157 static RSA_METHOD aep_rsa =
158         {
159         "Aep RSA method",
160         NULL,                /*rsa_pub_encrypt*/
161         NULL,                /*rsa_pub_decrypt*/
162         NULL,                /*rsa_priv_encrypt*/
163         NULL,                /*rsa_priv_encrypt*/
164         aep_rsa_mod_exp,     /*rsa_mod_exp*/
165         aep_mod_exp_mont,    /*bn_mod_exp*/
166         NULL,                /*init*/
167         NULL,                /*finish*/
168         0,                   /*flags*/
169         NULL,                /*app_data*/
170         NULL,                /*rsa_sign*/
171         NULL                 /*rsa_verify*/
172         };
173 #endif
174
175 #ifndef OPENSSL_NO_DSA
176 /* Our internal DSA_METHOD that we provide pointers to */
177 static DSA_METHOD aep_dsa =
178         {
179         "Aep DSA method",
180         NULL,                /* dsa_do_sign */
181         NULL,                /* dsa_sign_setup */
182         NULL,                /* dsa_do_verify */
183         aep_dsa_mod_exp,     /* dsa_mod_exp */
184         aep_mod_exp_dsa,     /* bn_mod_exp */
185         NULL,                /* init */
186         NULL,                /* finish */
187         0,                   /* flags */
188         NULL                 /* app_data */
189         };
190 #endif
191
192 #ifndef OPENSSL_NO_DH
193 /* Our internal DH_METHOD that we provide pointers to */
194 static DH_METHOD aep_dh =
195         {
196         "Aep DH method",
197         NULL,
198         NULL,
199         aep_mod_exp_dh,
200         NULL,
201         NULL,
202         0,
203         NULL
204         };
205 #endif
206
207 #ifdef AEPRAND
208 /* our internal RAND_method that we provide pointers to  */
209 static RAND_METHOD aep_random =
210         {
211         /*"AEP RAND method", */
212         NULL,
213         aep_rand,
214         NULL,
215         NULL,
216         aep_rand,
217         aep_rand_status,
218         };
219 #endif
220
221 /*Define an array of structures to hold connections*/
222 static AEP_CONNECTION_ENTRY aep_app_conn_table[MAX_PROCESS_CONNECTIONS];
223
224 /*Used to determine if this is a new process*/
225 static pid_t    recorded_pid = 0;
226
227 #ifdef AEPRAND
228 static AEP_U8   rand_block[RAND_BLK_SIZE];
229 static AEP_U32  rand_block_bytes = 0;
230 #endif
231
232 /* Constants used when creating the ENGINE */
233 static const char *engine_aep_id = "aep";
234 static const char *engine_aep_name = "Aep hardware engine support";
235
236
237 /* This internal function is used by ENGINE_aep() and possibly by the
238  * "dynamic" ENGINE support too */
239 static int bind_aep(ENGINE *e)
240         {
241 #ifndef OPENSSL_NO_RSA
242         const RSA_METHOD  *meth1;
243 #endif
244 #ifndef OPENSSL_NO_DSA
245         const DSA_METHOD  *meth2;
246 #endif
247 #ifndef OPENSSL_NO_DH
248         const DH_METHOD   *meth3;
249 #endif
250
251         if(!ENGINE_set_id(e, engine_aep_id) ||
252                 !ENGINE_set_name(e, engine_aep_name) ||
253 #ifndef OPENSSL_NO_RSA
254                 !ENGINE_set_RSA(e, &aep_rsa) ||
255 #endif
256 #ifndef OPENSSL_NO_DSA
257                 !ENGINE_set_DSA(e, &aep_dsa) ||
258 #endif
259 #ifndef OPENSSL_NO_DH
260                 !ENGINE_set_DH(e, &aep_dh) ||
261 #endif
262 #ifdef AEPRAND
263                 !ENGINE_set_RAND(e, &aep_random) ||
264 #endif
265                 !ENGINE_set_init_function(e, aep_init) ||
266                 !ENGINE_set_destroy_function(e, aep_destroy) ||
267                 !ENGINE_set_finish_function(e, aep_finish) ||
268                 !ENGINE_set_ctrl_function(e, aep_ctrl) ||
269                 !ENGINE_set_cmd_defns(e, aep_cmd_defns))
270                 return 0;
271
272 #ifndef OPENSSL_NO_RSA
273         /* We know that the "PKCS1_SSLeay()" functions hook properly
274          * to the aep-specific mod_exp and mod_exp_crt so we use
275          * those functions. NB: We don't use ENGINE_openssl() or
276          * anything "more generic" because something like the RSAref
277          * code may not hook properly, and if you own one of these
278          * cards then you have the right to do RSA operations on it
279          * anyway! */
280         meth1 = RSA_PKCS1_SSLeay();
281         aep_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
282         aep_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
283         aep_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
284         aep_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
285 #endif
286
287
288 #ifndef OPENSSL_NO_DSA
289         /* Use the DSA_OpenSSL() method and just hook the mod_exp-ish
290          * bits. */
291         meth2 = DSA_OpenSSL();
292         aep_dsa.dsa_do_sign    = meth2->dsa_do_sign;
293         aep_dsa.dsa_sign_setup = meth2->dsa_sign_setup;
294         aep_dsa.dsa_do_verify  = meth2->dsa_do_verify;
295
296         aep_dsa = *DSA_get_default_method(); 
297         aep_dsa.dsa_mod_exp = aep_dsa_mod_exp; 
298         aep_dsa.bn_mod_exp = aep_mod_exp_dsa;
299 #endif
300
301 #ifndef OPENSSL_NO_DH
302         /* Much the same for Diffie-Hellman */
303         meth3 = DH_OpenSSL();
304         aep_dh.generate_key = meth3->generate_key;
305         aep_dh.compute_key  = meth3->compute_key;
306         aep_dh.bn_mod_exp   = meth3->bn_mod_exp;
307 #endif
308
309         /* Ensure the aep error handling is set up */
310         ERR_load_AEPHK_strings();
311
312         return 1;
313 }
314
315 #ifdef ENGINE_DYNAMIC_SUPPORT
316 static int bind_helper(ENGINE *e, const char *id)
317         {
318         if(id && (strcmp(id, engine_aep_id) != 0))
319                 return 0;
320         if(!bind_aep(e))
321                 return 0;
322         return 1;
323         }       
324 IMPLEMENT_DYNAMIC_CHECK_FN()
325 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
326 #else
327 static ENGINE *engine_aep(void)
328         {
329         ENGINE *ret = ENGINE_new();
330         if(!ret)
331                 return NULL;
332         if(!bind_aep(ret))
333                 {
334                 ENGINE_free(ret);
335                 return NULL;
336                 }
337         return ret;
338         }
339
340 void ENGINE_load_aep(void)
341         {
342         /* Copied from eng_[openssl|dyn].c */
343         ENGINE *toadd = engine_aep();
344         if(!toadd) return;
345         ENGINE_add(toadd);
346         ENGINE_free(toadd);
347         ERR_clear_error();
348         }
349 #endif
350
351 /* This is a process-global DSO handle used for loading and unloading
352  * the Aep library. NB: This is only set (or unset) during an
353  * init() or finish() call (reference counts permitting) and they're
354  * operating with global locks, so this should be thread-safe
355  * implicitly. */
356 static DSO *aep_dso = NULL;
357
358 /* These are the static string constants for the DSO file name and the function
359  * symbol names to bind to. 
360 */
361 static const char *AEP_LIBNAME = "aep";
362
363 static const char *AEP_F1    = "AEP_ModExp";
364 static const char *AEP_F2    = "AEP_ModExpCrt";
365 #ifdef AEPRAND
366 static const char *AEP_F3    = "AEP_GenRandom";
367 #endif
368 static const char *AEP_F4    = "AEP_Finalize";
369 static const char *AEP_F5    = "AEP_Initialize";
370 static const char *AEP_F6    = "AEP_OpenConnection";
371 static const char *AEP_F7    = "AEP_SetBNCallBacks";
372 static const char *AEP_F8    = "AEP_CloseConnection";
373
374 /* These are the function pointers that are (un)set when the library has
375  * successfully (un)loaded. */
376 static t_AEP_OpenConnection    *p_AEP_OpenConnection  = NULL;
377 static t_AEP_CloseConnection   *p_AEP_CloseConnection = NULL;
378 static t_AEP_ModExp            *p_AEP_ModExp          = NULL;
379 static t_AEP_ModExpCrt         *p_AEP_ModExpCrt       = NULL;
380 #ifdef AEPRAND
381 static t_AEP_GenRandom         *p_AEP_GenRandom       = NULL;
382 #endif
383 static t_AEP_Initialize        *p_AEP_Initialize      = NULL;
384 static t_AEP_Finalize          *p_AEP_Finalize        = NULL;
385 static t_AEP_SetBNCallBacks    *p_AEP_SetBNCallBacks  = NULL;
386
387 /* (de)initialisation functions. */
388 static int aep_init(ENGINE *e)
389         {
390         t_AEP_ModExp          *p1;
391         t_AEP_ModExpCrt       *p2;
392 #ifdef AEPRAND
393         t_AEP_GenRandom       *p3;
394 #endif
395         t_AEP_Finalize        *p4;
396         t_AEP_Initialize      *p5;
397         t_AEP_OpenConnection  *p6;
398         t_AEP_SetBNCallBacks  *p7;
399         t_AEP_CloseConnection *p8;
400
401         int to_return = 0;
402  
403         if(aep_dso != NULL)
404                 {
405                 AEPHKerr(AEPHK_F_AEP_INIT,AEPHK_R_ALREADY_LOADED);
406                 goto err;
407                 }
408         /* Attempt to load libaep.so. */
409
410         aep_dso = DSO_load(NULL, AEP_LIBNAME, NULL, 0);
411   
412         if(aep_dso == NULL)
413                 {
414                 AEPHKerr(AEPHK_F_AEP_INIT,AEPHK_R_NOT_LOADED);
415                 goto err;
416                 }
417
418         if(     !(p1 = (t_AEP_ModExp *)     DSO_bind_func( aep_dso,AEP_F1))  ||
419                 !(p2 = (t_AEP_ModExpCrt*)   DSO_bind_func( aep_dso,AEP_F2))  ||
420 #ifdef AEPRAND
421                 !(p3 = (t_AEP_GenRandom*)   DSO_bind_func( aep_dso,AEP_F3))  ||
422 #endif
423                 !(p4 = (t_AEP_Finalize*)    DSO_bind_func( aep_dso,AEP_F4))  ||
424                 !(p5 = (t_AEP_Initialize*)  DSO_bind_func( aep_dso,AEP_F5))  ||
425                 !(p6 = (t_AEP_OpenConnection*) DSO_bind_func( aep_dso,AEP_F6))  ||
426                 !(p7 = (t_AEP_SetBNCallBacks*) DSO_bind_func( aep_dso,AEP_F7))  ||
427                 !(p8 = (t_AEP_CloseConnection*) DSO_bind_func( aep_dso,AEP_F8)))
428                 {
429                 AEPHKerr(AEPHK_F_AEP_INIT,AEPHK_R_NOT_LOADED);
430                 goto err;
431                 }
432
433         /* Copy the pointers */
434   
435         p_AEP_ModExp           = p1;
436         p_AEP_ModExpCrt        = p2;
437 #ifdef AEPRAND
438         p_AEP_GenRandom        = p3;
439 #endif
440         p_AEP_Finalize         = p4;
441         p_AEP_Initialize       = p5;
442         p_AEP_OpenConnection   = p6;
443         p_AEP_SetBNCallBacks   = p7;
444         p_AEP_CloseConnection  = p8;
445  
446         to_return = 1;
447  
448         return to_return;
449
450  err: 
451
452         if(aep_dso)
453                 DSO_free(aep_dso);
454                 
455         p_AEP_OpenConnection    = NULL;
456         p_AEP_ModExp            = NULL;
457         p_AEP_ModExpCrt         = NULL;
458 #ifdef AEPRAND
459         p_AEP_GenRandom         = NULL;
460 #endif
461         p_AEP_Initialize        = NULL;
462         p_AEP_Finalize          = NULL;
463         p_AEP_SetBNCallBacks    = NULL;
464         p_AEP_CloseConnection   = NULL;
465
466         return to_return;
467         }
468
469 /* Destructor (complements the "ENGINE_aep()" constructor) */
470 static int aep_destroy(ENGINE *e)
471         {
472         ERR_unload_AEPHK_strings();
473         return 1;
474         }
475
476 static int aep_finish(ENGINE *e)
477         {
478         int to_return = 0, in_use;
479         AEP_RV rv;
480
481         if(aep_dso == NULL)
482                 {
483                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_NOT_LOADED);
484                 goto err;
485                 }
486
487         rv = aep_close_all_connections(0, &in_use);
488         if (rv != AEP_R_OK)
489                 {
490                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_CLOSE_HANDLES_FAILED);
491                 goto err;
492                 }
493         if (in_use)
494                 {
495                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_CONNECTIONS_IN_USE);
496                 goto err;
497                 }
498
499         rv = p_AEP_Finalize();
500         if (rv != AEP_R_OK)
501                 {
502                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_FINALIZE_FAILED);
503                 goto err;
504                 }
505
506         if(!DSO_free(aep_dso))
507                 {
508                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_UNIT_FAILURE);
509                 goto err;
510                 }
511
512         aep_dso = NULL;
513         p_AEP_CloseConnection   = NULL;
514         p_AEP_OpenConnection    = NULL;
515         p_AEP_ModExp            = NULL;
516         p_AEP_ModExpCrt         = NULL;
517 #ifdef AEPRAND
518         p_AEP_GenRandom         = NULL;
519 #endif
520         p_AEP_Initialize        = NULL;
521         p_AEP_Finalize          = NULL;
522         p_AEP_SetBNCallBacks    = NULL;
523
524         to_return = 1;
525  err:
526         return to_return;
527         }
528
529 static int aep_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
530         {
531         int initialised = ((aep_dso == NULL) ? 0 : 1);
532         switch(cmd)
533                 {
534         case AEP_CMD_SO_PATH:
535                 if(p == NULL)
536                         {
537                         AEPHKerr(AEPHK_F_AEP_CTRL,
538                                 ERR_R_PASSED_NULL_PARAMETER);
539                         return 0;
540                         }
541                 if(initialised)
542                         {
543                         AEPHKerr(AEPHK_F_AEP_CTRL,
544                                 AEPHK_R_ALREADY_LOADED);
545                         return 0;
546                         }
547                 AEP_LIBNAME = (const char *)p;
548                 return 1;
549         default:
550                 break;
551                 }
552         AEPHKerr(AEPHK_F_AEP_CTRL,AEPHK_R_CTRL_COMMAND_NOT_IMPLEMENTED);
553         return 0;
554         }
555
556 static int aep_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
557         const BIGNUM *m, BN_CTX *ctx)
558         {
559         int to_return = 0;
560         AEP_CONNECTION_HNDL hConnection;
561         AEP_RV rv;
562
563         /*Grab a connection from the pool*/
564         rv = aep_get_connection(&hConnection);
565         if (rv != AEP_R_OK)
566                 {     
567                 AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_GET_HANDLE_FAILED);
568                 goto err;
569                 }
570
571         /*To the card with the mod exp*/
572         rv = p_AEP_ModExp(hConnection,(void*)a, (void*)p,(void*)m, (void*)r,NULL);
573
574         if (rv !=  AEP_R_OK)
575                 {
576                 AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_MOD_EXP_FAILED);
577                 rv = aep_return_connection(hConnection);
578                 goto err;
579                 }
580
581         /*Return the connection to the pool*/
582         rv = aep_return_connection(hConnection);
583         if (rv != AEP_R_OK)
584                 {
585                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_RETURN_CONNECTION_FAILED); 
586                 goto err;
587                 }
588
589         to_return = 1;
590  err:
591         return to_return;
592         }
593         
594 static AEP_RV aep_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
595         const BIGNUM *q, const BIGNUM *dmp1,
596         const BIGNUM *dmq1,const BIGNUM *iqmp, BN_CTX *ctx)
597         {
598         AEP_RV rv = AEP_R_OK;
599         AEP_CONNECTION_HNDL hConnection;
600
601         /*Grab a connection from the pool*/
602         rv = aep_get_connection(&hConnection);
603         if (rv != AEP_R_OK)
604                 {
605                 AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_GET_HANDLE_FAILED);
606                 goto err;
607                 }
608
609         /*To the card with the mod exp*/
610         rv = p_AEP_ModExpCrt(hConnection,(void*)a, (void*)p, (void*)q, (void*)dmp1,(void*)dmq1,
611                 (void*)iqmp,(void*)r,NULL);
612         if (rv != AEP_R_OK)
613                 {
614                 AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_MOD_EXP_CRT_FAILED);
615                 rv = aep_return_connection(hConnection);
616                 goto err;
617                 }
618
619         /*Return the connection to the pool*/
620         rv = aep_return_connection(hConnection);
621         if (rv != AEP_R_OK)
622                 {
623                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_RETURN_CONNECTION_FAILED); 
624                 goto err;
625                 }
626  
627  err:
628         return rv;
629         }
630         
631
632 #ifdef AEPRAND
633 static int aep_rand(unsigned char *buf,int len )
634         {
635         AEP_RV rv = AEP_R_OK;
636         AEP_CONNECTION_HNDL hConnection;
637
638         int to_return = 0;
639
640   
641         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
642
643         /*Can the request be serviced with what's already in the buffer?*/
644         if (len <= rand_block_bytes)
645                 {
646                 memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len);
647                 rand_block_bytes -= len;
648                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
649                 }
650         else
651                 /*If not the get another block of random bytes*/
652                 {
653                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
654
655                 rv = aep_get_connection(&hConnection);
656                 if (rv !=  AEP_R_OK)
657                         { 
658                         AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_HANDLE_FAILED);             
659                         goto err_nounlock;
660                         }
661
662                 if (len > RAND_BLK_SIZE)
663                         {
664                         rv = p_AEP_GenRandom(hConnection, len, 2, buf, NULL);
665                         if (rv !=  AEP_R_OK)
666                                 {  
667                                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_RANDOM_FAILED); 
668                                 goto err_nounlock;
669                                 }
670                         }
671                 else
672                         {
673                         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
674
675                         rv = p_AEP_GenRandom(hConnection, RAND_BLK_SIZE, 2, &rand_block[0], NULL);
676                         if (rv !=  AEP_R_OK)
677                                 {       
678                                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_RANDOM_FAILED); 
679               
680                                 goto err;
681                                 }
682
683                         rand_block_bytes = RAND_BLK_SIZE;
684
685                         memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len);
686                         rand_block_bytes -= len;
687
688                         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
689                         }
690
691                 rv = aep_return_connection(hConnection);
692                 if (rv != AEP_R_OK)
693                         {
694                         AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_RETURN_CONNECTION_FAILED); 
695           
696                         goto err_nounlock;
697                         }
698                 }
699   
700         return 1;
701  err:
702         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
703  err_nounlock:
704         return 0;
705         }
706         
707 static int aep_rand_status(void)
708 {
709         return 1;
710 }
711 #endif
712
713 #ifndef OPENSSL_NO_RSA
714 static int aep_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa)
715         {
716         BN_CTX *ctx = NULL;
717         int to_return = 0;
718         AEP_RV rv = AEP_R_OK;
719
720         if ((ctx = BN_CTX_new()) == NULL)
721                 goto err;
722
723         if (!aep_dso)
724                 {
725                 AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_NOT_LOADED);
726                 goto err;
727                 }
728
729         /*See if we have all the necessary bits for a crt*/
730         if (rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp)
731                 {
732                 rv =  aep_mod_exp_crt(r0,I,rsa->p,rsa->q, rsa->dmp1,rsa->dmq1,rsa->iqmp,ctx);
733                 if (rv != AEP_R_OK)
734                         goto err;
735                 }
736         else
737                 {
738                 if (!rsa->d || !rsa->n)
739                         {
740                         AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_MISSING_KEY_COMPONENTS);
741                         goto err;
742                         }
743  
744                 rv = aep_mod_exp(r0,I,rsa->d,rsa->n,ctx);
745                 if  (rv != AEP_R_OK)
746                         goto err;
747         
748                 }
749
750         to_return = 1;
751
752  err:
753         if(ctx)
754                 BN_CTX_free(ctx);
755         return to_return;
756 }
757 #endif
758
759 #ifndef OPENSSL_NO_DSA
760 static int aep_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
761         BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
762         BN_CTX *ctx, BN_MONT_CTX *in_mont)
763         {
764         BIGNUM t;
765         int to_return = 0;
766         BN_init(&t);
767
768         /* let rr = a1 ^ p1 mod m */
769         if (!aep_mod_exp(rr,a1,p1,m,ctx)) goto end;
770         /* let t = a2 ^ p2 mod m */
771         if (!aep_mod_exp(&t,a2,p2,m,ctx)) goto end;
772         /* let rr = rr * t mod m */
773         if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end;
774         to_return = 1;
775  end: 
776         BN_free(&t);
777         return to_return;
778         }
779
780 static int aep_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
781         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
782         BN_MONT_CTX *m_ctx)
783         {  
784         return aep_mod_exp(r, a, p, m, ctx); 
785         }
786 #endif
787
788 /* This function is aliased to mod_exp (with the mont stuff dropped). */
789 static int aep_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
790         const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
791         {
792         return aep_mod_exp(r, a, p, m, ctx);
793         }
794
795 #ifndef OPENSSL_NO_DH
796 /* This function is aliased to mod_exp (with the dh and mont dropped). */
797 static int aep_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
798         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
799         BN_MONT_CTX *m_ctx)
800         {
801         return aep_mod_exp(r, a, p, m, ctx);
802         }
803 #endif
804
805 static AEP_RV aep_get_connection(AEP_CONNECTION_HNDL_PTR phConnection)
806         {
807         int count;
808         AEP_RV rv = AEP_R_OK;
809
810         /*Get the current process id*/
811         pid_t curr_pid;
812
813         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
814
815         curr_pid = getpid();
816
817         /*Check if this is the first time this is being called from the current
818           process*/
819         if (recorded_pid != curr_pid)
820                 {
821                 /*Remember our pid so we can check if we're in a new process*/
822                 recorded_pid = curr_pid;
823
824                 /*Call Finalize to make sure we have not inherited some data
825                   from a parent process*/
826                 p_AEP_Finalize();
827      
828                 /*Initialise the AEP API*/
829                 rv = p_AEP_Initialize(NULL);
830
831                 if (rv != AEP_R_OK)
832                         {
833                         AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_INIT_FAILURE);
834                         recorded_pid = 0;
835                         goto end;
836                         }
837
838                 /*Set the AEP big num call back functions*/
839                 rv = p_AEP_SetBNCallBacks(&GetBigNumSize, &MakeAEPBigNum,
840                         &ConvertAEPBigNum);
841
842                 if (rv != AEP_R_OK)
843                         {
844                         AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_SETBNCALLBACK_FAILURE);
845                         recorded_pid = 0;
846                         goto end;
847                         }
848
849 #ifdef AEPRAND
850                 /*Reset the rand byte count*/
851                 rand_block_bytes = 0;
852 #endif
853
854                 /*Init the structures*/
855                 for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
856                         {
857                         aep_app_conn_table[count].conn_state = NotConnected;
858                         aep_app_conn_table[count].conn_hndl  = 0;
859                         }
860
861                 /*Open a connection*/
862                 rv = p_AEP_OpenConnection(phConnection);
863
864                 if (rv != AEP_R_OK)
865                         {
866                         AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_UNIT_FAILURE);
867                         recorded_pid = 0;
868                         goto end;
869                         }
870
871                 aep_app_conn_table[0].conn_state = InUse;
872                 aep_app_conn_table[0].conn_hndl = *phConnection;
873                 goto end;
874                 }
875         /*Check the existing connections to see if we can find a free one*/
876         for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
877                 {
878                 if (aep_app_conn_table[count].conn_state == Connected)
879                         {
880                         aep_app_conn_table[count].conn_state = InUse;
881                         *phConnection = aep_app_conn_table[count].conn_hndl;
882                         goto end;
883                         }
884                 }
885         /*If no connections available, we're going to have to try
886           to open a new one*/
887         for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
888                 {
889                 if (aep_app_conn_table[count].conn_state == NotConnected)
890                         {
891                         /*Open a connection*/
892                         rv = p_AEP_OpenConnection(phConnection);
893
894                         if (rv != AEP_R_OK)
895                                 {             
896                                 AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_UNIT_FAILURE);
897                                 goto end;
898                                 }
899
900                         aep_app_conn_table[count].conn_state = InUse;
901                         aep_app_conn_table[count].conn_hndl = *phConnection;
902                         goto end;
903                         }
904                 }
905         rv = AEP_R_GENERAL_ERROR;
906  end:
907         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
908         return rv;
909         }
910
911
912 static AEP_RV aep_return_connection(AEP_CONNECTION_HNDL hConnection)
913         {
914         int count;
915
916         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
917
918         /*Find the connection item that matches this connection handle*/
919         for(count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
920                 {
921                 if (aep_app_conn_table[count].conn_hndl == hConnection)
922                         {
923                         aep_app_conn_table[count].conn_state = Connected;
924                         break;
925                         }
926                 }
927
928         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
929
930         return AEP_R_OK;
931         }
932
933 static AEP_RV aep_close_all_connections(int use_engine_lock, int *in_use)
934         {
935         int count;
936         AEP_RV rv;
937
938         *in_use = 0;
939         if (use_engine_lock) CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
940         for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
941                 {
942                 switch (aep_app_conn_table[count].conn_state)
943                         {
944                 case Connected:
945                         rv = p_AEP_CloseConnection(aep_app_conn_table[count].conn_hndl);
946                         if (rv != AEP_R_OK)
947                                 return rv;
948                         aep_app_conn_table[count].conn_state = NotConnected;
949                         aep_app_conn_table[count].conn_hndl  = 0;
950                         break;
951                 case InUse:
952                         (*in_use)++;
953                         break;
954                 case NotConnected:
955                         break;
956                         }
957                 }
958         if (use_engine_lock) CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
959         return AEP_R_OK;
960         }
961
962 /*BigNum call back functions, used to convert OpenSSL bignums into AEP bignums.
963   Note only 32bit Openssl build support*/
964
965 static AEP_RV GetBigNumSize(void* ArbBigNum, AEP_U32* BigNumSize)
966         {
967         BIGNUM* bn;
968
969         /*Cast the ArbBigNum pointer to our BIGNUM struct*/
970         bn = (BIGNUM*) ArbBigNum;
971
972 #ifdef SIXTY_FOUR_BIT_LONG
973         *BigNumSize = bn->top << 3;
974 #else
975         /*Size of the bignum in bytes is equal to the bn->top (no of 32 bit
976           words) multiplies by 4*/
977         *BigNumSize = bn->top << 2;
978 #endif
979
980         return AEP_R_OK;
981         }
982
983 static AEP_RV MakeAEPBigNum(void* ArbBigNum, AEP_U32 BigNumSize,
984         unsigned char* AEP_BigNum)
985         {
986         BIGNUM* bn;
987
988 #ifndef SIXTY_FOUR_BIT_LONG
989         unsigned char* buf;
990         int i;
991 #endif
992
993         /*Cast the ArbBigNum pointer to our BIGNUM struct*/
994         bn = (BIGNUM*) ArbBigNum;
995
996 #ifdef SIXTY_FOUR_BIT_LONG
997         memcpy(AEP_BigNum, bn->d, BigNumSize);
998 #else
999         /*Must copy data into a (monotone) least significant byte first format
1000           performing endian conversion if necessary*/
1001         for(i=0;i<bn->top;i++)
1002                 {
1003                 buf = (unsigned char*)&bn->d[i];
1004
1005                 *((AEP_U32*)AEP_BigNum) =
1006                         (AEP_U32) ((unsigned) buf[1] << 8 | buf[0]) |
1007                         ((unsigned) buf[3] << 8 | buf[2])  << 16;
1008
1009                 AEP_BigNum += 4;
1010                 }
1011 #endif
1012
1013         return AEP_R_OK;
1014         }
1015
1016 /*Turn an AEP Big Num back to a user big num*/
1017 static AEP_RV ConvertAEPBigNum(void* ArbBigNum, AEP_U32 BigNumSize,
1018         unsigned char* AEP_BigNum)
1019         {
1020         BIGNUM* bn;
1021 #ifndef SIXTY_FOUR_BIT_LONG
1022         int i;
1023 #endif
1024
1025         bn = (BIGNUM*)ArbBigNum;
1026
1027         /*Expand the result bn so that it can hold our big num.
1028           Size is in bits*/
1029         bn_expand(bn, (int)(BigNumSize << 3));
1030
1031 #ifdef SIXTY_FOUR_BIT_LONG
1032         bn->top = BigNumSize >> 3;
1033         
1034         if((BigNumSize & 7) != 0)
1035                 bn->top++;
1036
1037         memset(bn->d, 0, bn->top << 3); 
1038
1039         memcpy(bn->d, AEP_BigNum, BigNumSize);
1040 #else
1041         bn->top = BigNumSize >> 2;
1042  
1043         for(i=0;i<bn->top;i++)
1044                 {
1045                 bn->d[i] = (AEP_U32)
1046                         ((unsigned) AEP_BigNum[3] << 8 | AEP_BigNum[2]) << 16 |
1047                         ((unsigned) AEP_BigNum[1] << 8 | AEP_BigNum[0]);
1048                 AEP_BigNum += 4;
1049                 }
1050 #endif
1051
1052         return AEP_R_OK;
1053 }       
1054         
1055 #endif /* !OPENSSL_NO_HW_AEP */
1056 #endif /* !OPENSSL_NO_HW */