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