By adding a BN_CTX parameter to the 'rsa_mod_exp' callback, private key
[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, BN_CTX *ctx);
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, BN_CTX *ctx)
749         {
750         int to_return = 0;
751         AEP_RV rv = AEP_R_OK;
752
753         if (!aep_dso)
754                 {
755                 AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_NOT_LOADED);
756                 goto err;
757                 }
758
759         /*See if we have all the necessary bits for a crt*/
760         if (rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp)
761                 {
762                 rv =  aep_mod_exp_crt(r0,I,rsa->p,rsa->q, rsa->dmp1,rsa->dmq1,rsa->iqmp,ctx);
763
764                 if (rv == FAIL_TO_SW){
765                         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
766                         to_return = (*meth->rsa_mod_exp)(r0, I, rsa, ctx);
767                         goto err;
768                 }
769                 else if (rv != AEP_R_OK)
770                         goto err;
771                 }
772         else
773                 {
774                 if (!rsa->d || !rsa->n)
775                         {
776                         AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_MISSING_KEY_COMPONENTS);
777                         goto err;
778                         }
779  
780                 rv = aep_mod_exp(r0,I,rsa->d,rsa->n,ctx);
781                 if  (rv != AEP_R_OK)
782                         goto err;
783         
784                 }
785
786         to_return = 1;
787
788  err:
789         return to_return;
790 }
791 #endif
792
793 #ifndef OPENSSL_NO_DSA
794 static int aep_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
795         BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
796         BN_CTX *ctx, BN_MONT_CTX *in_mont)
797         {
798         BIGNUM t;
799         int to_return = 0;
800         BN_init(&t);
801
802         /* let rr = a1 ^ p1 mod m */
803         if (!aep_mod_exp(rr,a1,p1,m,ctx)) goto end;
804         /* let t = a2 ^ p2 mod m */
805         if (!aep_mod_exp(&t,a2,p2,m,ctx)) goto end;
806         /* let rr = rr * t mod m */
807         if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end;
808         to_return = 1;
809  end: 
810         BN_free(&t);
811         return to_return;
812         }
813
814 static int aep_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
815         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
816         BN_MONT_CTX *m_ctx)
817         {  
818         return aep_mod_exp(r, a, p, m, ctx); 
819         }
820 #endif
821
822 /* This function is aliased to mod_exp (with the mont stuff dropped). */
823 static int aep_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
824         const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
825         {
826         return aep_mod_exp(r, a, p, m, ctx);
827         }
828
829 #ifndef OPENSSL_NO_DH
830 /* This function is aliased to mod_exp (with the dh and mont dropped). */
831 static int aep_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
832         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
833         BN_MONT_CTX *m_ctx)
834         {
835         return aep_mod_exp(r, a, p, m, ctx);
836         }
837 #endif
838
839 static AEP_RV aep_get_connection(AEP_CONNECTION_HNDL_PTR phConnection)
840         {
841         int count;
842         AEP_RV rv = AEP_R_OK;
843
844         /*Get the current process id*/
845         pid_t curr_pid;
846
847         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
848
849 #ifndef NETWARE_CLIB
850         curr_pid = getpid();
851 #else
852         curr_pid = GetThreadID();
853 #endif
854
855         /*Check if this is the first time this is being called from the current
856           process*/
857         if (recorded_pid != curr_pid)
858                 {
859                 /*Remember our pid so we can check if we're in a new process*/
860                 recorded_pid = curr_pid;
861
862                 /*Call Finalize to make sure we have not inherited some data
863                   from a parent process*/
864                 p_AEP_Finalize();
865      
866                 /*Initialise the AEP API*/
867                 rv = p_AEP_Initialize(NULL);
868
869                 if (rv != AEP_R_OK)
870                         {
871                         AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_INIT_FAILURE);
872                         recorded_pid = 0;
873                         goto end;
874                         }
875
876                 /*Set the AEP big num call back functions*/
877                 rv = p_AEP_SetBNCallBacks(&GetBigNumSize, &MakeAEPBigNum,
878                         &ConvertAEPBigNum);
879
880                 if (rv != AEP_R_OK)
881                         {
882                         AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_SETBNCALLBACK_FAILURE);
883                         recorded_pid = 0;
884                         goto end;
885                         }
886
887 #ifdef AEPRAND
888                 /*Reset the rand byte count*/
889                 rand_block_bytes = 0;
890 #endif
891
892                 /*Init the structures*/
893                 for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
894                         {
895                         aep_app_conn_table[count].conn_state = NotConnected;
896                         aep_app_conn_table[count].conn_hndl  = 0;
897                         }
898
899                 /*Open a connection*/
900                 rv = p_AEP_OpenConnection(phConnection);
901
902                 if (rv != AEP_R_OK)
903                         {
904                         AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_UNIT_FAILURE);
905                         recorded_pid = 0;
906                         goto end;
907                         }
908
909                 aep_app_conn_table[0].conn_state = InUse;
910                 aep_app_conn_table[0].conn_hndl = *phConnection;
911                 goto end;
912                 }
913         /*Check the existing connections to see if we can find a free one*/
914         for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
915                 {
916                 if (aep_app_conn_table[count].conn_state == Connected)
917                         {
918                         aep_app_conn_table[count].conn_state = InUse;
919                         *phConnection = aep_app_conn_table[count].conn_hndl;
920                         goto end;
921                         }
922                 }
923         /*If no connections available, we're going to have to try
924           to open a new one*/
925         for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
926                 {
927                 if (aep_app_conn_table[count].conn_state == NotConnected)
928                         {
929                         /*Open a connection*/
930                         rv = p_AEP_OpenConnection(phConnection);
931
932                         if (rv != AEP_R_OK)
933                                 {             
934                                 AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_UNIT_FAILURE);
935                                 goto end;
936                                 }
937
938                         aep_app_conn_table[count].conn_state = InUse;
939                         aep_app_conn_table[count].conn_hndl = *phConnection;
940                         goto end;
941                         }
942                 }
943         rv = AEP_R_GENERAL_ERROR;
944  end:
945         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
946         return rv;
947         }
948
949
950 static AEP_RV aep_return_connection(AEP_CONNECTION_HNDL hConnection)
951         {
952         int count;
953
954         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
955
956         /*Find the connection item that matches this connection handle*/
957         for(count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
958                 {
959                 if (aep_app_conn_table[count].conn_hndl == hConnection)
960                         {
961                         aep_app_conn_table[count].conn_state = Connected;
962                         break;
963                         }
964                 }
965
966         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
967
968         return AEP_R_OK;
969         }
970
971 static AEP_RV aep_close_connection(AEP_CONNECTION_HNDL hConnection)
972         {
973         int count;
974         AEP_RV rv = AEP_R_OK;
975
976         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
977
978         /*Find the connection item that matches this connection handle*/
979         for(count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
980                 {
981                 if (aep_app_conn_table[count].conn_hndl == hConnection)
982                         {
983                         rv = p_AEP_CloseConnection(aep_app_conn_table[count].conn_hndl);
984                         if (rv != AEP_R_OK)
985                                 goto end;
986                         aep_app_conn_table[count].conn_state = NotConnected;
987                         aep_app_conn_table[count].conn_hndl  = 0;
988                         break;
989                         }
990                 }
991
992  end:
993         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
994         return rv;
995         }
996
997 static AEP_RV aep_close_all_connections(int use_engine_lock, int *in_use)
998         {
999         int count;
1000         AEP_RV rv = AEP_R_OK;
1001
1002         *in_use = 0;
1003         if (use_engine_lock) CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
1004         for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++)
1005                 {
1006                 switch (aep_app_conn_table[count].conn_state)
1007                         {
1008                 case Connected:
1009                         rv = p_AEP_CloseConnection(aep_app_conn_table[count].conn_hndl);
1010                         if (rv != AEP_R_OK)
1011                                 goto end;
1012                         aep_app_conn_table[count].conn_state = NotConnected;
1013                         aep_app_conn_table[count].conn_hndl  = 0;
1014                         break;
1015                 case InUse:
1016                         (*in_use)++;
1017                         break;
1018                 case NotConnected:
1019                         break;
1020                         }
1021                 }
1022  end:
1023         if (use_engine_lock) CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
1024         return rv;
1025         }
1026
1027 /*BigNum call back functions, used to convert OpenSSL bignums into AEP bignums.
1028   Note only 32bit Openssl build support*/
1029
1030 static AEP_RV GetBigNumSize(AEP_VOID_PTR ArbBigNum, AEP_U32* BigNumSize)
1031         {
1032         BIGNUM* bn;
1033
1034         /*Cast the ArbBigNum pointer to our BIGNUM struct*/
1035         bn = (BIGNUM*) ArbBigNum;
1036
1037 #ifdef SIXTY_FOUR_BIT_LONG
1038         *BigNumSize = bn->top << 3;
1039 #else
1040         /*Size of the bignum in bytes is equal to the bn->top (no of 32 bit
1041           words) multiplies by 4*/
1042         *BigNumSize = bn->top << 2;
1043 #endif
1044
1045         return AEP_R_OK;
1046         }
1047
1048 static AEP_RV MakeAEPBigNum(AEP_VOID_PTR ArbBigNum, AEP_U32 BigNumSize,
1049         unsigned char* AEP_BigNum)
1050         {
1051         BIGNUM* bn;
1052
1053 #ifndef SIXTY_FOUR_BIT_LONG
1054         unsigned char* buf;
1055         int i;
1056 #endif
1057
1058         /*Cast the ArbBigNum pointer to our BIGNUM struct*/
1059         bn = (BIGNUM*) ArbBigNum;
1060
1061 #ifdef SIXTY_FOUR_BIT_LONG
1062         memcpy(AEP_BigNum, bn->d, BigNumSize);
1063 #else
1064         /*Must copy data into a (monotone) least significant byte first format
1065           performing endian conversion if necessary*/
1066         for(i=0;i<bn->top;i++)
1067                 {
1068                 buf = (unsigned char*)&bn->d[i];
1069
1070                 *((AEP_U32*)AEP_BigNum) = (AEP_U32)
1071                         ((unsigned) buf[1] << 8 | buf[0]) |
1072                         ((unsigned) buf[3] << 8 | buf[2])  << 16;
1073
1074                 AEP_BigNum += 4;
1075                 }
1076 #endif
1077
1078         return AEP_R_OK;
1079         }
1080
1081 /*Turn an AEP Big Num back to a user big num*/
1082 static AEP_RV ConvertAEPBigNum(void* ArbBigNum, AEP_U32 BigNumSize,
1083         unsigned char* AEP_BigNum)
1084         {
1085         BIGNUM* bn;
1086 #ifndef SIXTY_FOUR_BIT_LONG
1087         int i;
1088 #endif
1089
1090         bn = (BIGNUM*)ArbBigNum;
1091
1092         /*Expand the result bn so that it can hold our big num.
1093           Size is in bits*/
1094         bn_expand(bn, (int)(BigNumSize << 3));
1095
1096 #ifdef SIXTY_FOUR_BIT_LONG
1097         bn->top = BigNumSize >> 3;
1098         
1099         if((BigNumSize & 7) != 0)
1100                 bn->top++;
1101
1102         memset(bn->d, 0, bn->top << 3); 
1103
1104         memcpy(bn->d, AEP_BigNum, BigNumSize);
1105 #else
1106         bn->top = BigNumSize >> 2;
1107  
1108         for(i=0;i<bn->top;i++)
1109                 {
1110                 bn->d[i] = (AEP_U32)
1111                         ((unsigned) AEP_BigNum[3] << 8 | AEP_BigNum[2]) << 16 |
1112                         ((unsigned) AEP_BigNum[1] << 8 | AEP_BigNum[0]);
1113                 AEP_BigNum += 4;
1114                 }
1115 #endif
1116
1117         return AEP_R_OK;
1118 }       
1119         
1120 #endif /* !OPENSSL_NO_HW_AEP */
1121 #endif /* !OPENSSL_NO_HW */