Oops, do not unlock CRYPTO_LOCK_DYNLOCK when we locked
[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         AEP_RV rv;
403  
404         if(aep_dso != NULL)
405                 {
406                 AEPHKerr(AEPHK_F_AEP_INIT,AEPHK_R_ALREADY_LOADED);
407                 goto err;
408                 }
409         /* Attempt to load libaep.so. */
410
411         aep_dso = DSO_load(NULL, AEP_LIBNAME, NULL, 0);
412   
413         if(aep_dso == NULL)
414                 {
415                 AEPHKerr(AEPHK_F_AEP_INIT,AEPHK_R_NOT_LOADED);
416                 goto err;
417                 }
418
419         if(     !(p1 = (t_AEP_ModExp *)     DSO_bind_func( aep_dso,AEP_F1))  ||
420                 !(p2 = (t_AEP_ModExpCrt*)   DSO_bind_func( aep_dso,AEP_F2))  ||
421 #ifdef AEPRAND
422                 !(p3 = (t_AEP_GenRandom*)   DSO_bind_func( aep_dso,AEP_F3))  ||
423 #endif
424                 !(p4 = (t_AEP_Finalize*)    DSO_bind_func( aep_dso,AEP_F4))  ||
425                 !(p5 = (t_AEP_Initialize*)  DSO_bind_func( aep_dso,AEP_F5))  ||
426                 !(p6 = (t_AEP_OpenConnection*) DSO_bind_func( aep_dso,AEP_F6))  ||
427                 !(p7 = (t_AEP_SetBNCallBacks*) DSO_bind_func( aep_dso,AEP_F7))  ||
428                 !(p8 = (t_AEP_CloseConnection*) DSO_bind_func( aep_dso,AEP_F8)))
429                 {
430                 AEPHKerr(AEPHK_F_AEP_INIT,AEPHK_R_NOT_LOADED);
431                 goto err;
432                 }
433
434         /* Copy the pointers */
435   
436         p_AEP_ModExp           = p1;
437         p_AEP_ModExpCrt        = p2;
438 #ifdef AEPRAND
439         p_AEP_GenRandom        = p3;
440 #endif
441         p_AEP_Finalize         = p4;
442         p_AEP_Initialize       = p5;
443         p_AEP_OpenConnection   = p6;
444         p_AEP_SetBNCallBacks   = p7;
445         p_AEP_CloseConnection  = p8;
446  
447         to_return = 1;
448  
449         return to_return;
450
451  err: 
452
453         if(aep_dso)
454                 DSO_free(aep_dso);
455                 
456         p_AEP_OpenConnection    = NULL;
457         p_AEP_ModExp            = NULL;
458         p_AEP_ModExpCrt         = NULL;
459 #ifdef AEPRAND
460         p_AEP_GenRandom         = NULL;
461 #endif
462         p_AEP_Initialize        = NULL;
463         p_AEP_Finalize          = NULL;
464         p_AEP_SetBNCallBacks    = NULL;
465         p_AEP_CloseConnection   = NULL;
466
467         return to_return;
468         }
469
470 /* Destructor (complements the "ENGINE_aep()" constructor) */
471 static int aep_destroy(ENGINE *e)
472         {
473         ERR_unload_AEPHK_strings();
474         return 1;
475         }
476
477 static int aep_finish(ENGINE *e)
478         {
479         int to_return = 0, in_use;
480         AEP_RV rv;
481
482         if(aep_dso == NULL)
483                 {
484                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_NOT_LOADED);
485                 goto err;
486                 }
487
488         rv = aep_close_all_connections(0, &in_use);
489         if (rv != AEP_R_OK)
490                 {
491                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_CLOSE_HANDLES_FAILED);
492                 goto err;
493                 }
494         if (in_use)
495                 {
496                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_CONNECTIONS_IN_USE);
497                 goto err;
498                 }
499
500         rv = p_AEP_Finalize();
501         if (rv != AEP_R_OK)
502                 {
503                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_FINALIZE_FAILED);
504                 goto err;
505                 }
506
507         if(!DSO_free(aep_dso))
508                 {
509                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_UNIT_FAILURE);
510                 goto err;
511                 }
512
513         aep_dso = NULL;
514         p_AEP_CloseConnection   = NULL;
515         p_AEP_OpenConnection    = NULL;
516         p_AEP_ModExp            = NULL;
517         p_AEP_ModExpCrt         = NULL;
518 #ifdef AEPRAND
519         p_AEP_GenRandom         = NULL;
520 #endif
521         p_AEP_Initialize        = NULL;
522         p_AEP_Finalize          = NULL;
523         p_AEP_SetBNCallBacks    = NULL;
524
525         to_return = 1;
526  err:
527         return to_return;
528         }
529
530 static int aep_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
531         {
532         int initialised = ((aep_dso == NULL) ? 0 : 1);
533         switch(cmd)
534                 {
535         case AEP_CMD_SO_PATH:
536                 if(p == NULL)
537                         {
538                         AEPHKerr(AEPHK_F_AEP_CTRL,
539                                 ERR_R_PASSED_NULL_PARAMETER);
540                         return 0;
541                         }
542                 if(initialised)
543                         {
544                         AEPHKerr(AEPHK_F_AEP_CTRL,
545                                 AEPHK_R_ALREADY_LOADED);
546                         return 0;
547                         }
548                 AEP_LIBNAME = (const char *)p;
549                 return 1;
550         default:
551                 break;
552                 }
553         AEPHKerr(AEPHK_F_AEP_CTRL,AEPHK_R_CTRL_COMMAND_NOT_IMPLEMENTED);
554         return 0;
555         }
556
557 static int aep_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
558         const BIGNUM *m, BN_CTX *ctx)
559         {
560         int to_return = 0;
561         AEP_CONNECTION_HNDL hConnection;
562         AEP_RV rv;
563
564         /*Grab a connection from the pool*/
565         rv = aep_get_connection(&hConnection);
566         if (rv != AEP_R_OK)
567                 {     
568                 AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_GET_HANDLE_FAILED);
569                 goto err;
570                 }
571
572         /*To the card with the mod exp*/
573         rv = p_AEP_ModExp(hConnection,(void*)a, (void*)p,(void*)m, (void*)r,NULL);
574
575         if (rv !=  AEP_R_OK)
576                 {
577                 AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_MOD_EXP_FAILED);
578                 rv = aep_return_connection(hConnection);
579                 goto err;
580                 }
581
582         /*Return the connection to the pool*/
583         rv = aep_return_connection(hConnection);
584         if (rv != AEP_R_OK)
585                 {
586                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_RETURN_CONNECTION_FAILED); 
587                 goto err;
588                 }
589
590         to_return = 1;
591  err:
592         return to_return;
593         }
594         
595 static AEP_RV aep_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
596         const BIGNUM *q, const BIGNUM *dmp1,
597         const BIGNUM *dmq1,const BIGNUM *iqmp, BN_CTX *ctx)
598         {
599         AEP_RV rv = AEP_R_OK;
600         AEP_CONNECTION_HNDL hConnection;
601
602         /*Grab a connection from the pool*/
603         rv = aep_get_connection(&hConnection);
604         if (rv != AEP_R_OK)
605                 {
606                 AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_GET_HANDLE_FAILED);
607                 goto err;
608                 }
609
610         /*To the card with the mod exp*/
611         rv = p_AEP_ModExpCrt(hConnection,(void*)a, (void*)p, (void*)q, (void*)dmp1,(void*)dmq1,
612                 (void*)iqmp,(void*)r,NULL);
613         if (rv != AEP_R_OK)
614                 {
615                 AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_MOD_EXP_CRT_FAILED);
616                 rv = aep_return_connection(hConnection);
617                 goto err;
618                 }
619
620         /*Return the connection to the pool*/
621         rv = aep_return_connection(hConnection);
622         if (rv != AEP_R_OK)
623                 {
624                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_RETURN_CONNECTION_FAILED); 
625                 goto err;
626                 }
627  
628  err:
629         return rv;
630         }
631         
632
633 #ifdef AEPRAND
634 static int aep_rand(unsigned char *buf,int len )
635         {
636         AEP_RV rv = AEP_R_OK;
637         AEP_CONNECTION_HNDL hConnection;
638
639         int to_return = 0;
640
641   
642         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
643
644         /*Can the request be serviced with what's already in the buffer?*/
645         if (len <= rand_block_bytes)
646                 {
647                 memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len);
648                 rand_block_bytes -= len;
649                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
650                 }
651         else
652                 /*If not the get another block of random bytes*/
653                 {
654                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
655
656                 rv = aep_get_connection(&hConnection);
657                 if (rv !=  AEP_R_OK)
658                         { 
659                         AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_HANDLE_FAILED);             
660                         goto err_nounlock;
661                         }
662
663                 if (len > RAND_BLK_SIZE)
664                         {
665                         rv = p_AEP_GenRandom(hConnection, len, 2, buf, NULL);
666                         if (rv !=  AEP_R_OK)
667                                 {  
668                                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_RANDOM_FAILED); 
669                                 goto err_nounlock;
670                                 }
671                         }
672                 else
673                         {
674                         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
675
676                         rv = p_AEP_GenRandom(hConnection, RAND_BLK_SIZE, 2, &rand_block[0], NULL);
677                         if (rv !=  AEP_R_OK)
678                                 {       
679                                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_RANDOM_FAILED); 
680               
681                                 goto err;
682                                 }
683
684                         rand_block_bytes = RAND_BLK_SIZE;
685
686                         memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len);
687                         rand_block_bytes -= len;
688
689                         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
690                         }
691
692                 rv = aep_return_connection(hConnection);
693                 if (rv != AEP_R_OK)
694                         {
695                         AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_RETURN_CONNECTION_FAILED); 
696           
697                         goto err_nounlock;
698                         }
699                 }
700   
701         return 1;
702  err:
703         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
704  err_nounlock:
705         return 0;
706         }
707         
708 static int aep_rand_status(void)
709 {
710         return 1;
711 }
712 #endif
713
714 #ifndef OPENSSL_NO_RSA
715 static int aep_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa)
716         {
717         BN_CTX *ctx = NULL;
718         int to_return = 0;
719         AEP_RV rv = AEP_R_OK;
720
721         if ((ctx = BN_CTX_new()) == NULL)
722                 goto err;
723
724         if (!aep_dso)
725                 {
726                 AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_NOT_LOADED);
727                 goto err;
728                 }
729
730         /*See if we have all the necessary bits for a crt*/
731         if (rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp)
732                 {
733                 rv =  aep_mod_exp_crt(r0,I,rsa->p,rsa->q, rsa->dmp1,rsa->dmq1,rsa->iqmp,ctx);
734                 if (rv != AEP_R_OK)
735                         goto err;
736                 }
737         else
738                 {
739                 if (!rsa->d || !rsa->n)
740                         {
741                         AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_MISSING_KEY_COMPONENTS);
742                         goto err;
743                         }
744  
745                 rv = aep_mod_exp(r0,I,rsa->d,rsa->n,ctx);
746                 if  (rv != AEP_R_OK)
747                         goto err;
748         
749                 }
750
751         to_return = 1;
752
753  err:
754         if(ctx)
755                 BN_CTX_free(ctx);
756         return to_return;
757 }
758 #endif
759
760 #ifndef OPENSSL_NO_DSA
761 static int aep_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
762         BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
763         BN_CTX *ctx, BN_MONT_CTX *in_mont)
764         {
765         BIGNUM t;
766         int to_return = 0;
767         BN_init(&t);
768
769         /* let rr = a1 ^ p1 mod m */
770         if (!aep_mod_exp(rr,a1,p1,m,ctx)) goto end;
771         /* let t = a2 ^ p2 mod m */
772         if (!aep_mod_exp(&t,a2,p2,m,ctx)) goto end;
773         /* let rr = rr * t mod m */
774         if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end;
775         to_return = 1;
776  end: 
777         BN_free(&t);
778         return to_return;
779         }
780
781 static int aep_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
782         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
783         BN_MONT_CTX *m_ctx)
784         {  
785         return aep_mod_exp(r, a, p, m, ctx); 
786         }
787 #endif
788
789 /* This function is aliased to mod_exp (with the mont stuff dropped). */
790 static int aep_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
791         const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
792         {
793         return aep_mod_exp(r, a, p, m, ctx);
794         }
795
796 #ifndef OPENSSL_NO_DH
797 /* This function is aliased to mod_exp (with the dh and mont dropped). */
798 static int aep_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
799         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
800         BN_MONT_CTX *m_ctx)
801         {
802         return aep_mod_exp(r, a, p, m, ctx);
803         }
804 #endif
805
806 static AEP_RV aep_get_connection(AEP_CONNECTION_HNDL_PTR phConnection)
807         {
808         int count;
809         AEP_RV rv = AEP_R_OK;
810
811         /*Get the current process id*/
812         pid_t curr_pid;
813
814         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
815
816         curr_pid = getpid();
817
818         /*Check if this is the first time this is being called from the current
819           process*/
820         if (recorded_pid != curr_pid)
821                 {
822                 /*Remember our pid so we can check if we're in a new process*/
823                 recorded_pid = curr_pid;
824
825                 /*Call Finalize to make sure we have not inherited some data
826                   from a parent process*/
827                 p_AEP_Finalize();
828      
829                 /*Initialise the AEP API*/
830                 rv = p_AEP_Initialize(NULL);
831
832                 if (rv != AEP_R_OK)
833                         {
834                         AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_INIT_FAILURE);
835                         recorded_pid = 0;
836                         goto end;
837                         }
838
839                 /*Set the AEP big num call back functions*/
840                 rv = p_AEP_SetBNCallBacks(&GetBigNumSize, &MakeAEPBigNum,
841                         &ConvertAEPBigNum);
842
843                 if (rv != AEP_R_OK)
844                         {
845                         AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_SETBNCALLBACK_FAILURE);
846                         recorded_pid = 0;
847                         goto end;
848                         }
849
850 #ifdef AEPRAND
851                 /*Reset the rand byte count*/
852                 rand_block_bytes = 0;
853 #endif
854
855                 /*Init the structures*/
856                 for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
857                         {
858                         aep_app_conn_table[count].conn_state = NotConnected;
859                         aep_app_conn_table[count].conn_hndl  = 0;
860                         }
861
862                 /*Open a connection*/
863                 rv = p_AEP_OpenConnection(phConnection);
864
865                 if (rv != AEP_R_OK)
866                         {
867                         AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_UNIT_FAILURE);
868                         recorded_pid = 0;
869                         goto end;
870                         }
871
872                 aep_app_conn_table[0].conn_state = InUse;
873                 aep_app_conn_table[0].conn_hndl = *phConnection;
874                 goto end;
875                 }
876         /*Check the existing connections to see if we can find a free one*/
877         for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
878                 {
879                 if (aep_app_conn_table[count].conn_state == Connected)
880                         {
881                         aep_app_conn_table[count].conn_state = InUse;
882                         *phConnection = aep_app_conn_table[count].conn_hndl;
883                         goto end;
884                         }
885                 }
886         /*If no connections available, we're going to have to try
887           to open a new one*/
888         for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
889                 {
890                 if (aep_app_conn_table[count].conn_state == NotConnected)
891                         {
892                         /*Open a connection*/
893                         rv = p_AEP_OpenConnection(phConnection);
894
895                         if (rv != AEP_R_OK)
896                                 {             
897                                 AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_UNIT_FAILURE);
898                                 goto end;
899                                 }
900
901                         aep_app_conn_table[count].conn_state = InUse;
902                         aep_app_conn_table[count].conn_hndl = *phConnection;
903                         goto end;
904                         }
905                 }
906         rv = AEP_R_GENERAL_ERROR;
907  end:
908         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
909         return rv;
910         }
911
912
913 static AEP_RV aep_return_connection(AEP_CONNECTION_HNDL hConnection)
914         {
915         int count;
916
917         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
918
919         /*Find the connection item that matches this connection handle*/
920         for(count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
921                 {
922                 if (aep_app_conn_table[count].conn_hndl == hConnection)
923                         {
924                         aep_app_conn_table[count].conn_state = Connected;
925                         break;
926                         }
927                 }
928
929         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
930
931         return AEP_R_OK;
932         }
933
934 static AEP_RV aep_close_all_connections(int use_engine_lock, int *in_use)
935         {
936         int count;
937         AEP_RV rv;
938
939         *in_use = 0;
940         if (use_engine_lock) CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
941         for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
942                 {
943                 switch (aep_app_conn_table[count].conn_state)
944                         {
945                 case Connected:
946                         rv = p_AEP_CloseConnection(aep_app_conn_table[count].conn_hndl);
947                         if (rv != AEP_R_OK)
948                                 return rv;
949                         aep_app_conn_table[count].conn_state = NotConnected;
950                         aep_app_conn_table[count].conn_hndl  = 0;
951                         break;
952                 case InUse:
953                         (*in_use)++;
954                         break;
955                 case NotConnected:
956                         break;
957                         }
958                 }
959         if (use_engine_lock) CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
960         return AEP_R_OK;
961         }
962
963 /*BigNum call back functions, used to convert OpenSSL bignums into AEP bignums.
964   Note only 32bit Openssl build support*/
965
966 static AEP_RV GetBigNumSize(void* ArbBigNum, AEP_U32* BigNumSize)
967         {
968         BIGNUM* bn;
969
970         /*Cast the ArbBigNum pointer to our BIGNUM struct*/
971         bn = (BIGNUM*) ArbBigNum;
972
973 #ifdef SIXTY_FOUR_BIT_LONG
974         *BigNumSize = bn->top << 3;
975 #else
976         /*Size of the bignum in bytes is equal to the bn->top (no of 32 bit
977           words) multiplies by 4*/
978         *BigNumSize = bn->top << 2;
979 #endif
980
981         return AEP_R_OK;
982         }
983
984 static AEP_RV MakeAEPBigNum(void* ArbBigNum, AEP_U32 BigNumSize,
985         unsigned char* AEP_BigNum)
986         {
987         BIGNUM* bn;
988
989 #ifndef SIXTY_FOUR_BIT_LONG
990         unsigned char* buf;
991         int i;
992 #endif
993
994         /*Cast the ArbBigNum pointer to our BIGNUM struct*/
995         bn = (BIGNUM*) ArbBigNum;
996
997 #ifdef SIXTY_FOUR_BIT_LONG
998         memcpy(AEP_BigNum, bn->d, BigNumSize);
999 #else
1000         /*Must copy data into a (monotone) least significant byte first format
1001           performing endian conversion if necessary*/
1002         for(i=0;i<bn->top;i++)
1003                 {
1004                 buf = (unsigned char*)&bn->d[i];
1005
1006                 *((AEP_U32*)AEP_BigNum) =
1007                         (AEP_U32) ((unsigned) buf[1] << 8 | buf[0]) |
1008                         ((unsigned) buf[3] << 8 | buf[2])  << 16;
1009
1010                 AEP_BigNum += 4;
1011                 }
1012 #endif
1013
1014         return AEP_R_OK;
1015         }
1016
1017 /*Turn an AEP Big Num back to a user big num*/
1018 static AEP_RV ConvertAEPBigNum(void* ArbBigNum, AEP_U32 BigNumSize,
1019         unsigned char* AEP_BigNum)
1020         {
1021         BIGNUM* bn;
1022 #ifndef SIXTY_FOUR_BIT_LONG
1023         int i;
1024 #endif
1025
1026         bn = (BIGNUM*)ArbBigNum;
1027
1028         /*Expand the result bn so that it can hold our big num.
1029           Size is in bits*/
1030         bn_expand(bn, (int)(BigNumSize << 3));
1031
1032 #ifdef SIXTY_FOUR_BIT_LONG
1033         bn->top = BigNumSize >> 3;
1034         
1035         if((BigNumSize & 7) != 0)
1036                 bn->top++;
1037
1038         memset(bn->d, 0, bn->top << 3); 
1039
1040         memcpy(bn->d, AEP_BigNum, BigNumSize);
1041 #else
1042         bn->top = BigNumSize >> 2;
1043  
1044         for(i=0;i<bn->top;i++)
1045                 {
1046                 bn->d[i] = (AEP_U32)
1047                         ((unsigned) AEP_BigNum[3] << 8 | AEP_BigNum[2]) << 16 |
1048                         ((unsigned) AEP_BigNum[1] << 8 | AEP_BigNum[0]);
1049                 AEP_BigNum += 4;
1050                 }
1051 #endif
1052
1053         return AEP_R_OK;
1054 }       
1055         
1056 #endif /* !OPENSSL_NO_HW_AEP */
1057 #endif /* !OPENSSL_NO_HW */