add missing entries for "-multivalue-rdn" and "-utf8" in ca.pod and req.pod
[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         aep_dso = NULL;
483                 
484         p_AEP_OpenConnection    = NULL;
485         p_AEP_ModExp            = NULL;
486         p_AEP_ModExpCrt         = NULL;
487 #ifdef AEPRAND
488         p_AEP_GenRandom         = NULL;
489 #endif
490         p_AEP_Initialize        = NULL;
491         p_AEP_Finalize          = NULL;
492         p_AEP_SetBNCallBacks    = NULL;
493         p_AEP_CloseConnection   = NULL;
494
495         return to_return;
496         }
497
498 /* Destructor (complements the "ENGINE_aep()" constructor) */
499 static int aep_destroy(ENGINE *e)
500         {
501         free_AEP_LIBNAME();
502         ERR_unload_AEPHK_strings();
503         return 1;
504         }
505
506 static int aep_finish(ENGINE *e)
507         {
508         int to_return = 0, in_use;
509         AEP_RV rv;
510
511         if(aep_dso == NULL)
512                 {
513                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_NOT_LOADED);
514                 goto err;
515                 }
516
517         rv = aep_close_all_connections(0, &in_use);
518         if (rv != AEP_R_OK)
519                 {
520                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_CLOSE_HANDLES_FAILED);
521                 goto err;
522                 }
523         if (in_use)
524                 {
525                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_CONNECTIONS_IN_USE);
526                 goto err;
527                 }
528
529         rv = p_AEP_Finalize();
530         if (rv != AEP_R_OK)
531                 {
532                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_FINALIZE_FAILED);
533                 goto err;
534                 }
535
536         if(!DSO_free(aep_dso))
537                 {
538                 AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_UNIT_FAILURE);
539                 goto err;
540                 }
541
542         aep_dso = NULL;
543         p_AEP_CloseConnection   = NULL;
544         p_AEP_OpenConnection    = NULL;
545         p_AEP_ModExp            = NULL;
546         p_AEP_ModExpCrt         = NULL;
547 #ifdef AEPRAND
548         p_AEP_GenRandom         = NULL;
549 #endif
550         p_AEP_Initialize        = NULL;
551         p_AEP_Finalize          = NULL;
552         p_AEP_SetBNCallBacks    = NULL;
553
554         to_return = 1;
555  err:
556         return to_return;
557         }
558
559 static int aep_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
560         {
561         int initialised = ((aep_dso == NULL) ? 0 : 1);
562         switch(cmd)
563                 {
564         case AEP_CMD_SO_PATH:
565                 if(p == NULL)
566                         {
567                         AEPHKerr(AEPHK_F_AEP_CTRL,
568                                 ERR_R_PASSED_NULL_PARAMETER);
569                         return 0;
570                         }
571                 if(initialised)
572                         {
573                         AEPHKerr(AEPHK_F_AEP_CTRL,
574                                 AEPHK_R_ALREADY_LOADED);
575                         return 0;
576                         }
577                 return set_AEP_LIBNAME((const char*)p);
578         default:
579                 break;
580                 }
581         AEPHKerr(AEPHK_F_AEP_CTRL,AEPHK_R_CTRL_COMMAND_NOT_IMPLEMENTED);
582         return 0;
583         }
584
585 static int aep_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
586         const BIGNUM *m, BN_CTX *ctx)
587         {
588         int to_return = 0;
589         int     r_len = 0;
590         AEP_CONNECTION_HNDL hConnection;
591         AEP_RV rv;
592         
593         r_len = BN_num_bits(m);
594
595         /* Perform in software if modulus is too large for hardware. */
596
597         if (r_len > max_key_len){
598                 AEPHKerr(AEPHK_F_AEP_MOD_EXP, AEPHK_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
599                 return BN_mod_exp(r, a, p, m, ctx);
600         } 
601
602         /*Grab a connection from the pool*/
603         rv = aep_get_connection(&hConnection);
604         if (rv != AEP_R_OK)
605                 {     
606                 AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_GET_HANDLE_FAILED);
607                 return BN_mod_exp(r, a, p, m, ctx);
608                 }
609
610         /*To the card with the mod exp*/
611         rv = p_AEP_ModExp(hConnection,(void*)a, (void*)p,(void*)m, (void*)r,NULL);
612
613         if (rv !=  AEP_R_OK)
614                 {
615                 AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_MOD_EXP_FAILED);
616                 rv = aep_close_connection(hConnection);
617                 return BN_mod_exp(r, a, p, m, ctx);
618                 }
619
620         /*Return the connection to the pool*/
621         rv = aep_return_connection(hConnection);
622         if (rv != AEP_R_OK)
623                 {
624                 AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_RETURN_CONNECTION_FAILED); 
625                 goto err;
626                 }
627
628         to_return = 1;
629  err:
630         return to_return;
631         }
632         
633 static AEP_RV aep_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
634         const BIGNUM *q, const BIGNUM *dmp1,
635         const BIGNUM *dmq1,const BIGNUM *iqmp, BN_CTX *ctx)
636         {
637         AEP_RV rv = AEP_R_OK;
638         AEP_CONNECTION_HNDL hConnection;
639
640         /*Grab a connection from the pool*/
641         rv = aep_get_connection(&hConnection);
642         if (rv != AEP_R_OK)
643                 {
644                 AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_GET_HANDLE_FAILED);
645                 return FAIL_TO_SW;
646                 }
647
648         /*To the card with the mod exp*/
649         rv = p_AEP_ModExpCrt(hConnection,(void*)a, (void*)p, (void*)q, (void*)dmp1,(void*)dmq1,
650                 (void*)iqmp,(void*)r,NULL);
651         if (rv != AEP_R_OK)
652                 {
653                 AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_MOD_EXP_CRT_FAILED);
654                 rv = aep_close_connection(hConnection);
655                 return FAIL_TO_SW;
656                 }
657
658         /*Return the connection to the pool*/
659         rv = aep_return_connection(hConnection);
660         if (rv != AEP_R_OK)
661                 {
662                 AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_RETURN_CONNECTION_FAILED); 
663                 goto err;
664                 }
665  
666  err:
667         return rv;
668         }
669         
670
671 #ifdef AEPRAND
672 static int aep_rand(unsigned char *buf,int len )
673         {
674         AEP_RV rv = AEP_R_OK;
675         AEP_CONNECTION_HNDL hConnection;
676
677         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
678
679         /*Can the request be serviced with what's already in the buffer?*/
680         if (len <= rand_block_bytes)
681                 {
682                 memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len);
683                 rand_block_bytes -= len;
684                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
685                 }
686         else
687                 /*If not the get another block of random bytes*/
688                 {
689                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
690
691                 rv = aep_get_connection(&hConnection);
692                 if (rv !=  AEP_R_OK)
693                         { 
694                         AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_HANDLE_FAILED);             
695                         goto err_nounlock;
696                         }
697
698                 if (len > RAND_BLK_SIZE)
699                         {
700                         rv = p_AEP_GenRandom(hConnection, len, 2, buf, NULL);
701                         if (rv !=  AEP_R_OK)
702                                 {  
703                                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_RANDOM_FAILED); 
704                                 goto err_nounlock;
705                                 }
706                         }
707                 else
708                         {
709                         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
710
711                         rv = p_AEP_GenRandom(hConnection, RAND_BLK_SIZE, 2, &rand_block[0], NULL);
712                         if (rv !=  AEP_R_OK)
713                                 {       
714                                 AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_RANDOM_FAILED); 
715               
716                                 goto err;
717                                 }
718
719                         rand_block_bytes = RAND_BLK_SIZE;
720
721                         memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len);
722                         rand_block_bytes -= len;
723
724                         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
725                         }
726
727                 rv = aep_return_connection(hConnection);
728                 if (rv != AEP_R_OK)
729                         {
730                         AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_RETURN_CONNECTION_FAILED); 
731           
732                         goto err_nounlock;
733                         }
734                 }
735   
736         return 1;
737  err:
738         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
739  err_nounlock:
740         return 0;
741         }
742         
743 static int aep_rand_status(void)
744 {
745         return 1;
746 }
747 #endif
748
749 #ifndef OPENSSL_NO_RSA
750 static int aep_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
751         {
752         int to_return = 0;
753         AEP_RV rv = AEP_R_OK;
754
755         if (!aep_dso)
756                 {
757                 AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_NOT_LOADED);
758                 goto err;
759                 }
760
761         /*See if we have all the necessary bits for a crt*/
762         if (rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp)
763                 {
764                 rv =  aep_mod_exp_crt(r0,I,rsa->p,rsa->q, rsa->dmp1,rsa->dmq1,rsa->iqmp,ctx);
765
766                 if (rv == FAIL_TO_SW){
767                         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
768                         to_return = (*meth->rsa_mod_exp)(r0, I, rsa, ctx);
769                         goto err;
770                 }
771                 else if (rv != AEP_R_OK)
772                         goto err;
773                 }
774         else
775                 {
776                 if (!rsa->d || !rsa->n)
777                         {
778                         AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_MISSING_KEY_COMPONENTS);
779                         goto err;
780                         }
781  
782                 rv = aep_mod_exp(r0,I,rsa->d,rsa->n,ctx);
783                 if  (rv != AEP_R_OK)
784                         goto err;
785         
786                 }
787
788         to_return = 1;
789
790  err:
791         return to_return;
792 }
793 #endif
794
795 #ifndef OPENSSL_NO_DSA
796 static int aep_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
797         BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
798         BN_CTX *ctx, BN_MONT_CTX *in_mont)
799         {
800         BIGNUM t;
801         int to_return = 0;
802         BN_init(&t);
803
804         /* let rr = a1 ^ p1 mod m */
805         if (!aep_mod_exp(rr,a1,p1,m,ctx)) goto end;
806         /* let t = a2 ^ p2 mod m */
807         if (!aep_mod_exp(&t,a2,p2,m,ctx)) goto end;
808         /* let rr = rr * t mod m */
809         if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end;
810         to_return = 1;
811  end: 
812         BN_free(&t);
813         return to_return;
814         }
815
816 static int aep_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
817         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
818         BN_MONT_CTX *m_ctx)
819         {  
820         return aep_mod_exp(r, a, p, m, ctx); 
821         }
822 #endif
823
824 /* This function is aliased to mod_exp (with the mont stuff dropped). */
825 static int aep_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
826         const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
827         {
828         return aep_mod_exp(r, a, p, m, ctx);
829         }
830
831 #ifndef OPENSSL_NO_DH
832 /* This function is aliased to mod_exp (with the dh and mont dropped). */
833 static int aep_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
834         const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
835         BN_MONT_CTX *m_ctx)
836         {
837         return aep_mod_exp(r, a, p, m, ctx);
838         }
839 #endif
840
841 static AEP_RV aep_get_connection(AEP_CONNECTION_HNDL_PTR phConnection)
842         {
843         int count;
844         AEP_RV rv = AEP_R_OK;
845
846         /*Get the current process id*/
847         pid_t curr_pid;
848
849         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
850
851 #ifndef NETWARE_CLIB
852         curr_pid = getpid();
853 #else
854         curr_pid = GetThreadID();
855 #endif
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 */