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