4eab0fb76949bc594386b8fc087cd38690961e8c
[openssl.git] / crypto / engine / hw_cswift.c
1 /* crypto/engine/hw_cswift.c */
2 /* Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL
3  * project 2000.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer. 
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include <stdio.h>
60 #include <openssl/crypto.h>
61 #include "cryptlib.h"
62 #include <openssl/dso.h>
63 #include <openssl/engine.h>
64
65 #ifndef OPENSSL_NO_HW
66 #ifndef OPENSSL_NO_HW_CSWIFT
67
68 /* Attribution notice: Rainbow have generously allowed me to reproduce
69  * the necessary definitions here from their API. This means the support
70  * can build independently of whether application builders have the
71  * API or hardware. This will allow developers to easily produce software
72  * that has latent hardware support for any users that have accelerators
73  * installed, without the developers themselves needing anything extra.
74  *
75  * I have only clipped the parts from the CryptoSwift header files that
76  * are (or seem) relevant to the CryptoSwift support code. This is
77  * simply to keep the file sizes reasonable.
78  * [Geoff]
79  */
80 #ifdef FLAT_INC
81 #include "cswift.h"
82 #else
83 #include "vendor_defns/cswift.h"
84 #endif
85
86 static int cswift_init(ENGINE *e);
87 static int cswift_finish(ENGINE *e);
88 static int cswift_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
89
90 /* BIGNUM stuff */
91 static int cswift_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
92                 const BIGNUM *m, BN_CTX *ctx);
93 static int cswift_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
94                 const BIGNUM *q, const BIGNUM *dmp1, const BIGNUM *dmq1,
95                 const BIGNUM *iqmp, BN_CTX *ctx);
96
97 #ifndef OPENSSL_NO_RSA
98 /* RSA stuff */
99 static int cswift_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa);
100 #endif
101 /* This function is aliased to mod_exp (with the mont stuff dropped). */
102 static int cswift_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
103                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
104
105 #ifndef OPENSSL_NO_DSA
106 /* DSA stuff */
107 static DSA_SIG *cswift_dsa_sign(const unsigned char *dgst, int dlen, DSA *dsa);
108 static int cswift_dsa_verify(const unsigned char *dgst, int dgst_len,
109                                 DSA_SIG *sig, DSA *dsa);
110 #endif
111
112 #ifndef OPENSSL_NO_DH
113 /* DH stuff */
114 /* This function is alised to mod_exp (with the DH and mont dropped). */
115 static int cswift_mod_exp_dh(const DH *dh, BIGNUM *r,
116                 const BIGNUM *a, const BIGNUM *p,
117                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
118 #endif
119
120 /* The definitions for control commands specific to this engine */
121 #define CSWIFT_CMD_SO_PATH              ENGINE_CMD_BASE
122 static const ENGINE_CMD_DEFN cswift_cmd_defns[] = {
123         {CSWIFT_CMD_SO_PATH,
124                 "SO_PATH",
125                 "Specifies the path to the 'cswift' shared library",
126                 ENGINE_CMD_FLAG_STRING},
127         {0, NULL, NULL, 0}
128         };
129
130 #ifndef OPENSSL_NO_RSA
131 /* Our internal RSA_METHOD that we provide pointers to */
132 static RSA_METHOD cswift_rsa =
133         {
134         "CryptoSwift RSA method",
135         NULL,
136         NULL,
137         NULL,
138         NULL,
139         cswift_rsa_mod_exp,
140         cswift_mod_exp_mont,
141         NULL,
142         NULL,
143         0,
144         NULL,
145         NULL,
146         NULL
147         };
148 #endif
149
150 #ifndef OPENSSL_NO_DSA
151 /* Our internal DSA_METHOD that we provide pointers to */
152 static DSA_METHOD cswift_dsa =
153         {
154         "CryptoSwift DSA method",
155         cswift_dsa_sign,
156         NULL, /* dsa_sign_setup */
157         cswift_dsa_verify,
158         NULL, /* dsa_mod_exp */
159         NULL, /* bn_mod_exp */
160         NULL, /* init */
161         NULL, /* finish */
162         0, /* flags */
163         NULL /* app_data */
164         };
165 #endif
166
167 #ifndef OPENSSL_NO_DH
168 /* Our internal DH_METHOD that we provide pointers to */
169 static DH_METHOD cswift_dh =
170         {
171         "CryptoSwift DH method",
172         NULL,
173         NULL,
174         cswift_mod_exp_dh,
175         NULL,
176         NULL,
177         0,
178         NULL
179         };
180 #endif
181
182 #ifndef OPENSSL_NO_ERR
183 /* Error function codes for use in cswift operation */
184 #define CSWIFT_F_CSWIFT_INIT                    100
185 #define CSWIFT_F_CSWIFT_FINISH                  101
186 #define CSWIFT_F_CSWIFT_CTRL                    102
187 #define CSWIFT_F_CSWIFT_MOD_EXP                 103
188 #define CSWIFT_F_CSWIFT_MOD_EXP_CRT             104
189 #define CSWIFT_F_CSWIFT_RSA_MOD_EXP             105
190 #define CSWIFT_F_CSWIFT_DSA_SIGN                106
191 #define CSWIFT_F_CSWIFT_DSA_VERIFY              107
192 /* Error reason codes */
193 #define CSWIFT_R_ALREADY_LOADED                 108
194 #define CSWIFT_R_NOT_LOADED                     109
195 #define CSWIFT_R_UNIT_FAILURE                   110
196 #define CSWIFT_R_CTRL_COMMAND_NOT_IMPLEMENTED   113
197 #define CSWIFT_R_BN_CTX_FULL                    115
198 #define CSWIFT_R_BN_EXPAND_FAIL                 116
199 #define CSWIFT_R_BAD_KEY_SIZE                   117
200 #define CSWIFT_R_REQUEST_FAILED                 118
201 #define CSWIFT_R_MISSING_KEY_COMPONENTS         120
202 static ERR_STRING_DATA cswift_str_functs[] =
203         {
204         /* This first element is changed to match the dynamic 'lib' number */
205 {ERR_PACK(0,0,0),                               "cswift engine code"},
206 {ERR_PACK(0,CSWIFT_F_CSWIFT_INIT,0),            "cswift_init"},
207 {ERR_PACK(0,CSWIFT_F_CSWIFT_FINISH,0),          "cswift_finish"},
208 {ERR_PACK(0,CSWIFT_F_CSWIFT_CTRL,0),            "cswift_ctrl"},
209 {ERR_PACK(0,CSWIFT_F_CSWIFT_MOD_EXP,0),         "cswift_mod_exp"},
210 {ERR_PACK(0,CSWIFT_F_CSWIFT_MOD_EXP_CRT,0),     "cswift_mod_exp_crt"},
211 {ERR_PACK(0,CSWIFT_F_CSWIFT_RSA_MOD_EXP,0),     "cswift_rsa_mod_exp"},
212 {ERR_PACK(0,CSWIFT_F_CSWIFT_DSA_SIGN,0),        "cswift_dsa_sign"},
213 {ERR_PACK(0,CSWIFT_F_CSWIFT_DSA_VERIFY,0),      "cswift_dsa_verify"},
214 /* Error reason codes */
215 {CSWIFT_R_ALREADY_LOADED                 ,"already loaded"},
216 {CSWIFT_R_NOT_LOADED                     ,"not loaded"},
217 {CSWIFT_R_UNIT_FAILURE                   ,"unit failure"},
218 {CSWIFT_R_CTRL_COMMAND_NOT_IMPLEMENTED   ,"ctrl command not implemented"},
219 {CSWIFT_R_BN_CTX_FULL                    ,"BN_CTX full"},
220 {CSWIFT_R_BN_EXPAND_FAIL                 ,"bn_expand fail"},
221 {CSWIFT_R_BAD_KEY_SIZE                   ,"bad key size"},
222 {CSWIFT_R_REQUEST_FAILED                 ,"request failed"},
223 {CSWIFT_R_MISSING_KEY_COMPONENTS         ,"missing key components"},
224 {0,NULL}
225         };
226 /* The library number we obtain dynamically from the ERR code */
227 static int cswift_err_lib = -1;
228 #define CSWIFTerr(f,r) ERR_PUT_error(cswift_err_lib,(f),(r),__FILE__,__LINE__)
229 static void cswift_load_error_strings(void)
230         {
231         if(cswift_err_lib < 0)
232                 {
233                 if((cswift_err_lib = ERR_get_next_error_library()) <= 0)
234                         return;
235                 cswift_str_functs[0].error = ERR_PACK(cswift_err_lib,0,0);
236                 ERR_load_strings(cswift_err_lib, cswift_str_functs);
237                 }
238         }
239 #else
240 #define CSWIFTerr(f,r)                                  /* NOP */
241 static void cswift_load_error_strings(void) { }         /* NOP */
242 #endif
243
244 /* Constants used when creating the ENGINE */
245 static const char *engine_cswift_id = "cswift";
246 static const char *engine_cswift_name = "CryptoSwift hardware engine support";
247
248 /* This internal function is used by ENGINE_cswift() and possibly by the
249  * "dynamic" ENGINE support too */
250 static int bind_helper(ENGINE *e)
251         {
252 #ifndef OPENSSL_NO_RSA
253         const RSA_METHOD *meth1;
254 #endif
255 #ifndef OPENSSL_NO_DH
256         const DH_METHOD *meth2;
257 #endif
258         if(!ENGINE_set_id(e, engine_cswift_id) ||
259                         !ENGINE_set_name(e, engine_cswift_name) ||
260 #ifndef OPENSSL_NO_RSA
261                         !ENGINE_set_RSA(e, &cswift_rsa) ||
262 #endif
263 #ifndef OPENSSL_NO_DSA
264                         !ENGINE_set_DSA(e, &cswift_dsa) ||
265 #endif
266 #ifndef OPENSSL_NO_DH
267                         !ENGINE_set_DH(e, &cswift_dh) ||
268 #endif
269                         !ENGINE_set_BN_mod_exp(e, &cswift_mod_exp) ||
270                         !ENGINE_set_BN_mod_exp_crt(e, &cswift_mod_exp_crt) ||
271                         !ENGINE_set_init_function(e, cswift_init) ||
272                         !ENGINE_set_finish_function(e, cswift_finish) ||
273                         !ENGINE_set_ctrl_function(e, cswift_ctrl) ||
274                         !ENGINE_set_cmd_defns(e, cswift_cmd_defns))
275                 return 0;
276
277 #ifndef OPENSSL_NO_RSA
278         /* We know that the "PKCS1_SSLeay()" functions hook properly
279          * to the cswift-specific mod_exp and mod_exp_crt so we use
280          * those functions. NB: We don't use ENGINE_openssl() or
281          * anything "more generic" because something like the RSAref
282          * code may not hook properly, and if you own one of these
283          * cards then you have the right to do RSA operations on it
284          * anyway! */ 
285         meth1 = RSA_PKCS1_SSLeay();
286         cswift_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
287         cswift_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
288         cswift_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
289         cswift_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
290 #endif
291
292 #ifndef OPENSSL_NO_DH
293         /* Much the same for Diffie-Hellman */
294         meth2 = DH_OpenSSL();
295         cswift_dh.generate_key = meth2->generate_key;
296         cswift_dh.compute_key = meth2->compute_key;
297 #endif
298
299         /* Ensure the cswift error handling is set up */
300         cswift_load_error_strings();
301         return 1;
302         }
303
304 /* As this is only ever called once, there's no need for locking
305  * (indeed - the lock will already be held by our caller!!!) */
306 ENGINE *ENGINE_cswift(void)
307         {
308         ENGINE *ret = ENGINE_new();
309         if(!ret)
310                 return NULL;
311         if(!bind_helper(ret))
312                 {
313                 ENGINE_free(ret);
314                 return NULL;
315                 }
316         return ret;
317         }
318
319 /* This is a process-global DSO handle used for loading and unloading
320  * the CryptoSwift library. NB: This is only set (or unset) during an
321  * init() or finish() call (reference counts permitting) and they're
322  * operating with global locks, so this should be thread-safe
323  * implicitly. */
324 static DSO *cswift_dso = NULL;
325
326 /* These are the function pointers that are (un)set when the library has
327  * successfully (un)loaded. */
328 t_swAcquireAccContext *p_CSwift_AcquireAccContext = NULL;
329 t_swAttachKeyParam *p_CSwift_AttachKeyParam = NULL;
330 t_swSimpleRequest *p_CSwift_SimpleRequest = NULL;
331 t_swReleaseAccContext *p_CSwift_ReleaseAccContext = NULL;
332
333 /* Used in the DSO operations. */
334 static const char def_CSWIFT_LIBNAME[] = "swift";
335 static const char *CSWIFT_LIBNAME = def_CSWIFT_LIBNAME;
336 static const char *CSWIFT_F1 = "swAcquireAccContext";
337 static const char *CSWIFT_F2 = "swAttachKeyParam";
338 static const char *CSWIFT_F3 = "swSimpleRequest";
339 static const char *CSWIFT_F4 = "swReleaseAccContext";
340
341
342 /* CryptoSwift library functions and mechanics - these are used by the
343  * higher-level functions further down. NB: As and where there's no
344  * error checking, take a look lower down where these functions are
345  * called, the checking and error handling is probably down there. */
346
347 /* utility function to obtain a context */
348 static int get_context(SW_CONTEXT_HANDLE *hac)
349         {
350         SW_STATUS status;
351  
352         status = p_CSwift_AcquireAccContext(hac);
353         if(status != SW_OK)
354                 return 0;
355         return 1;
356         }
357  
358 /* similarly to release one. */
359 static void release_context(SW_CONTEXT_HANDLE hac)
360         {
361         p_CSwift_ReleaseAccContext(hac);
362         }
363
364 /* (de)initialisation functions. */
365 static int cswift_init(ENGINE *e)
366         {
367         SW_CONTEXT_HANDLE hac;
368         t_swAcquireAccContext *p1;
369         t_swAttachKeyParam *p2;
370         t_swSimpleRequest *p3;
371         t_swReleaseAccContext *p4;
372
373         if(cswift_dso != NULL)
374                 {
375                 CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_ALREADY_LOADED);
376                 goto err;
377                 }
378         /* Attempt to load libswift.so/swift.dll/whatever. */
379         cswift_dso = DSO_load(NULL, CSWIFT_LIBNAME, NULL, 0);
380         if(cswift_dso == NULL)
381                 {
382                 CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_NOT_LOADED);
383                 goto err;
384                 }
385         if(!(p1 = (t_swAcquireAccContext *)
386                                 DSO_bind_func(cswift_dso, CSWIFT_F1)) ||
387                         !(p2 = (t_swAttachKeyParam *)
388                                 DSO_bind_func(cswift_dso, CSWIFT_F2)) ||
389                         !(p3 = (t_swSimpleRequest *)
390                                 DSO_bind_func(cswift_dso, CSWIFT_F3)) ||
391                         !(p4 = (t_swReleaseAccContext *)
392                                 DSO_bind_func(cswift_dso, CSWIFT_F4)))
393                 {
394                 CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_NOT_LOADED);
395                 goto err;
396                 }
397         /* Copy the pointers */
398         p_CSwift_AcquireAccContext = p1;
399         p_CSwift_AttachKeyParam = p2;
400         p_CSwift_SimpleRequest = p3;
401         p_CSwift_ReleaseAccContext = p4;
402         /* Try and get a context - if not, we may have a DSO but no
403          * accelerator! */
404         if(!get_context(&hac))
405                 {
406                 CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_UNIT_FAILURE);
407                 goto err;
408                 }
409         release_context(hac);
410         /* Everything's fine. */
411         return 1;
412 err:
413         if(cswift_dso)
414                 DSO_free(cswift_dso);
415         p_CSwift_AcquireAccContext = NULL;
416         p_CSwift_AttachKeyParam = NULL;
417         p_CSwift_SimpleRequest = NULL;
418         p_CSwift_ReleaseAccContext = NULL;
419         return 0;
420         }
421
422 static int cswift_finish(ENGINE *e)
423         {
424         if(cswift_dso == NULL)
425                 {
426                 CSWIFTerr(CSWIFT_F_CSWIFT_FINISH,CSWIFT_R_NOT_LOADED);
427                 return 0;
428                 }
429         if(!DSO_free(cswift_dso))
430                 {
431                 CSWIFTerr(CSWIFT_F_CSWIFT_FINISH,CSWIFT_R_UNIT_FAILURE);
432                 return 0;
433                 }
434         cswift_dso = NULL;
435         p_CSwift_AcquireAccContext = NULL;
436         p_CSwift_AttachKeyParam = NULL;
437         p_CSwift_SimpleRequest = NULL;
438         p_CSwift_ReleaseAccContext = NULL;
439         return 1;
440         }
441
442 static int cswift_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
443         {
444         int initialised = ((cswift_dso == NULL) ? 0 : 1);
445         switch(cmd)
446                 {
447         case CSWIFT_CMD_SO_PATH:
448                 if(p == NULL)
449                         {
450                         CSWIFTerr(CSWIFT_F_CSWIFT_CTRL,ERR_R_PASSED_NULL_PARAMETER);
451                         return 0;
452                         }
453                 if(initialised)
454                         {
455                         CSWIFTerr(CSWIFT_F_CSWIFT_CTRL,CSWIFT_R_ALREADY_LOADED);
456                         return 0;
457                         }
458                 CSWIFT_LIBNAME = (const char *)p;
459                 return 1;
460         default:
461                 break;
462                 }
463         CSWIFTerr(CSWIFT_F_CSWIFT_CTRL,CSWIFT_R_CTRL_COMMAND_NOT_IMPLEMENTED);
464         return 0;
465         }
466
467 /* Un petit mod_exp */
468 static int cswift_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
469                         const BIGNUM *m, BN_CTX *ctx)
470         {
471         /* I need somewhere to store temporary serialised values for
472          * use with the CryptoSwift API calls. A neat cheat - I'll use
473          * BIGNUMs from the BN_CTX but access their arrays directly as
474          * byte arrays <grin>. This way I don't have to clean anything
475          * up. */
476         BIGNUM *modulus;
477         BIGNUM *exponent;
478         BIGNUM *argument;
479         BIGNUM *result;
480         SW_STATUS sw_status;
481         SW_LARGENUMBER arg, res;
482         SW_PARAM sw_param;
483         SW_CONTEXT_HANDLE hac;
484         int to_return, acquired;
485  
486         modulus = exponent = argument = result = NULL;
487         to_return = 0; /* expect failure */
488         acquired = 0;
489  
490         if(!get_context(&hac))
491                 {
492                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_UNIT_FAILURE);
493                 goto err;
494                 }
495         acquired = 1;
496         /* Prepare the params */
497         BN_CTX_start(ctx);
498         modulus = BN_CTX_get(ctx);
499         exponent = BN_CTX_get(ctx);
500         argument = BN_CTX_get(ctx);
501         result = BN_CTX_get(ctx);
502         if(!result)
503                 {
504                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BN_CTX_FULL);
505                 goto err;
506                 }
507         if(!bn_wexpand(modulus, m->top) || !bn_wexpand(exponent, p->top) ||
508                 !bn_wexpand(argument, a->top) || !bn_wexpand(result, m->top))
509                 {
510                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BN_EXPAND_FAIL);
511                 goto err;
512                 }
513         sw_param.type = SW_ALG_EXP;
514         sw_param.up.exp.modulus.nbytes = BN_bn2bin(m,
515                 (unsigned char *)modulus->d);
516         sw_param.up.exp.modulus.value = (unsigned char *)modulus->d;
517         sw_param.up.exp.exponent.nbytes = BN_bn2bin(p,
518                 (unsigned char *)exponent->d);
519         sw_param.up.exp.exponent.value = (unsigned char *)exponent->d;
520         /* Attach the key params */
521         sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
522         switch(sw_status)
523                 {
524         case SW_OK:
525                 break;
526         case SW_ERR_INPUT_SIZE:
527                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BAD_KEY_SIZE);
528                 goto err;
529         default:
530                 {
531                 char tmpbuf[20];
532                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_REQUEST_FAILED);
533                 sprintf(tmpbuf, "%ld", sw_status);
534                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
535                 }
536                 goto err;
537                 }
538         /* Prepare the argument and response */
539         arg.nbytes = BN_bn2bin(a, (unsigned char *)argument->d);
540         arg.value = (unsigned char *)argument->d;
541         res.nbytes = BN_num_bytes(m);
542         memset(result->d, 0, res.nbytes);
543         res.value = (unsigned char *)result->d;
544         /* Perform the operation */
545         if((sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_MODEXP, &arg, 1,
546                 &res, 1)) != SW_OK)
547                 {
548                 char tmpbuf[20];
549                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_REQUEST_FAILED);
550                 sprintf(tmpbuf, "%ld", sw_status);
551                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
552                 goto err;
553                 }
554         /* Convert the response */
555         BN_bin2bn((unsigned char *)result->d, res.nbytes, r);
556         to_return = 1;
557 err:
558         if(acquired)
559                 release_context(hac);
560         BN_CTX_end(ctx);
561         return to_return;
562         }
563
564 /* Un petit mod_exp chinois */
565 static int cswift_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
566                         const BIGNUM *q, const BIGNUM *dmp1,
567                         const BIGNUM *dmq1, const BIGNUM *iqmp, BN_CTX *ctx)
568         {
569         SW_STATUS sw_status;
570         SW_LARGENUMBER arg, res;
571         SW_PARAM sw_param;
572         SW_CONTEXT_HANDLE hac;
573         BIGNUM *rsa_p = NULL;
574         BIGNUM *rsa_q = NULL;
575         BIGNUM *rsa_dmp1 = NULL;
576         BIGNUM *rsa_dmq1 = NULL;
577         BIGNUM *rsa_iqmp = NULL;
578         BIGNUM *argument = NULL;
579         BIGNUM *result = NULL;
580         int to_return = 0; /* expect failure */
581         int acquired = 0;
582  
583         if(!get_context(&hac))
584                 {
585                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_UNIT_FAILURE);
586                 goto err;
587                 }
588         acquired = 1;
589         /* Prepare the params */
590         BN_CTX_start(ctx);
591         rsa_p = BN_CTX_get(ctx);
592         rsa_q = BN_CTX_get(ctx);
593         rsa_dmp1 = BN_CTX_get(ctx);
594         rsa_dmq1 = BN_CTX_get(ctx);
595         rsa_iqmp = BN_CTX_get(ctx);
596         argument = BN_CTX_get(ctx);
597         result = BN_CTX_get(ctx);
598         if(!result)
599                 {
600                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_CTX_FULL);
601                 goto err;
602                 }
603         if(!bn_wexpand(rsa_p, p->top) || !bn_wexpand(rsa_q, q->top) ||
604                         !bn_wexpand(rsa_dmp1, dmp1->top) ||
605                         !bn_wexpand(rsa_dmq1, dmq1->top) ||
606                         !bn_wexpand(rsa_iqmp, iqmp->top) ||
607                         !bn_wexpand(argument, a->top) ||
608                         !bn_wexpand(result, p->top + q->top))
609                 {
610                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL);
611                 goto err;
612                 }
613         sw_param.type = SW_ALG_CRT;
614         sw_param.up.crt.p.nbytes = BN_bn2bin(p, (unsigned char *)rsa_p->d);
615         sw_param.up.crt.p.value = (unsigned char *)rsa_p->d;
616         sw_param.up.crt.q.nbytes = BN_bn2bin(q, (unsigned char *)rsa_q->d);
617         sw_param.up.crt.q.value = (unsigned char *)rsa_q->d;
618         sw_param.up.crt.dmp1.nbytes = BN_bn2bin(dmp1,
619                 (unsigned char *)rsa_dmp1->d);
620         sw_param.up.crt.dmp1.value = (unsigned char *)rsa_dmp1->d;
621         sw_param.up.crt.dmq1.nbytes = BN_bn2bin(dmq1,
622                 (unsigned char *)rsa_dmq1->d);
623         sw_param.up.crt.dmq1.value = (unsigned char *)rsa_dmq1->d;
624         sw_param.up.crt.iqmp.nbytes = BN_bn2bin(iqmp,
625                 (unsigned char *)rsa_iqmp->d);
626         sw_param.up.crt.iqmp.value = (unsigned char *)rsa_iqmp->d;
627         /* Attach the key params */
628         sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
629         switch(sw_status)
630                 {
631         case SW_OK:
632                 break;
633         case SW_ERR_INPUT_SIZE:
634                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BAD_KEY_SIZE);
635                 goto err;
636         default:
637                 {
638                 char tmpbuf[20];
639                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_REQUEST_FAILED);
640                 sprintf(tmpbuf, "%ld", sw_status);
641                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
642                 }
643                 goto err;
644                 }
645         /* Prepare the argument and response */
646         arg.nbytes = BN_bn2bin(a, (unsigned char *)argument->d);
647         arg.value = (unsigned char *)argument->d;
648         res.nbytes = 2 * BN_num_bytes(p);
649         memset(result->d, 0, res.nbytes);
650         res.value = (unsigned char *)result->d;
651         /* Perform the operation */
652         if((sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_MODEXP_CRT, &arg, 1,
653                 &res, 1)) != SW_OK)
654                 {
655                 char tmpbuf[20];
656                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_REQUEST_FAILED);
657                 sprintf(tmpbuf, "%ld", sw_status);
658                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
659                 goto err;
660                 }
661         /* Convert the response */
662         BN_bin2bn((unsigned char *)result->d, res.nbytes, r);
663         to_return = 1;
664 err:
665         if(acquired)
666                 release_context(hac);
667         BN_CTX_end(ctx);
668         return to_return;
669         }
670  
671 #ifndef OPENSSL_NO_RSA
672 static int cswift_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa)
673         {
674         BN_CTX *ctx;
675         int to_return = 0;
676
677         if((ctx = BN_CTX_new()) == NULL)
678                 goto err;
679         if(!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp)
680                 {
681                 CSWIFTerr(CSWIFT_F_CSWIFT_RSA_MOD_EXP,CSWIFT_R_MISSING_KEY_COMPONENTS);
682                 goto err;
683                 }
684         to_return = cswift_mod_exp_crt(r0, I, rsa->p, rsa->q, rsa->dmp1,
685                 rsa->dmq1, rsa->iqmp, ctx);
686 err:
687         if(ctx)
688                 BN_CTX_free(ctx);
689         return to_return;
690         }
691 #endif
692
693 /* This function is aliased to mod_exp (with the mont stuff dropped). */
694 static int cswift_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
695                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
696         {
697         return cswift_mod_exp(r, a, p, m, ctx);
698         }
699
700 #ifndef OPENSSL_NO_DSA
701 static DSA_SIG *cswift_dsa_sign(const unsigned char *dgst, int dlen, DSA *dsa)
702         {
703         SW_CONTEXT_HANDLE hac;
704         SW_PARAM sw_param;
705         SW_STATUS sw_status;
706         SW_LARGENUMBER arg, res;
707         unsigned char *ptr;
708         BN_CTX *ctx;
709         BIGNUM *dsa_p = NULL;
710         BIGNUM *dsa_q = NULL;
711         BIGNUM *dsa_g = NULL;
712         BIGNUM *dsa_key = NULL;
713         BIGNUM *result = NULL;
714         DSA_SIG *to_return = NULL;
715         int acquired = 0;
716
717         if((ctx = BN_CTX_new()) == NULL)
718                 goto err;
719         if(!get_context(&hac))
720                 {
721                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_UNIT_FAILURE);
722                 goto err;
723                 }
724         acquired = 1;
725         /* Prepare the params */
726         BN_CTX_start(ctx);
727         dsa_p = BN_CTX_get(ctx);
728         dsa_q = BN_CTX_get(ctx);
729         dsa_g = BN_CTX_get(ctx);
730         dsa_key = BN_CTX_get(ctx);
731         result = BN_CTX_get(ctx);
732         if(!result)
733                 {
734                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BN_CTX_FULL);
735                 goto err;
736                 }
737         if(!bn_wexpand(dsa_p, dsa->p->top) ||
738                         !bn_wexpand(dsa_q, dsa->q->top) ||
739                         !bn_wexpand(dsa_g, dsa->g->top) ||
740                         !bn_wexpand(dsa_key, dsa->priv_key->top) ||
741                         !bn_wexpand(result, dsa->p->top))
742                 {
743                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BN_EXPAND_FAIL);
744                 goto err;
745                 }
746         sw_param.type = SW_ALG_DSA;
747         sw_param.up.dsa.p.nbytes = BN_bn2bin(dsa->p,
748                                 (unsigned char *)dsa_p->d);
749         sw_param.up.dsa.p.value = (unsigned char *)dsa_p->d;
750         sw_param.up.dsa.q.nbytes = BN_bn2bin(dsa->q,
751                                 (unsigned char *)dsa_q->d);
752         sw_param.up.dsa.q.value = (unsigned char *)dsa_q->d;
753         sw_param.up.dsa.g.nbytes = BN_bn2bin(dsa->g,
754                                 (unsigned char *)dsa_g->d);
755         sw_param.up.dsa.g.value = (unsigned char *)dsa_g->d;
756         sw_param.up.dsa.key.nbytes = BN_bn2bin(dsa->priv_key,
757                                 (unsigned char *)dsa_key->d);
758         sw_param.up.dsa.key.value = (unsigned char *)dsa_key->d;
759         /* Attach the key params */
760         sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
761         switch(sw_status)
762                 {
763         case SW_OK:
764                 break;
765         case SW_ERR_INPUT_SIZE:
766                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BAD_KEY_SIZE);
767                 goto err;
768         default:
769                 {
770                 char tmpbuf[20];
771                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_REQUEST_FAILED);
772                 sprintf(tmpbuf, "%ld", sw_status);
773                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
774                 }
775                 goto err;
776                 }
777         /* Prepare the argument and response */
778         arg.nbytes = dlen;
779         arg.value = (unsigned char *)dgst;
780         res.nbytes = BN_num_bytes(dsa->p);
781         memset(result->d, 0, res.nbytes);
782         res.value = (unsigned char *)result->d;
783         /* Perform the operation */
784         sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_DSS_SIGN, &arg, 1,
785                 &res, 1);
786         if(sw_status != SW_OK)
787                 {
788                 char tmpbuf[20];
789                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_REQUEST_FAILED);
790                 sprintf(tmpbuf, "%ld", sw_status);
791                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
792                 goto err;
793                 }
794         /* Convert the response */
795         ptr = (unsigned char *)result->d;
796         if((to_return = DSA_SIG_new()) == NULL)
797                 goto err;
798         to_return->r = BN_bin2bn((unsigned char *)result->d, 20, NULL);
799         to_return->s = BN_bin2bn((unsigned char *)result->d + 20, 20, NULL);
800
801 err:
802         if(acquired)
803                 release_context(hac);
804         if(ctx)
805                 {
806                 BN_CTX_end(ctx);
807                 BN_CTX_free(ctx);
808                 }
809         return to_return;
810         }
811
812 static int cswift_dsa_verify(const unsigned char *dgst, int dgst_len,
813                                 DSA_SIG *sig, DSA *dsa)
814         {
815         SW_CONTEXT_HANDLE hac;
816         SW_PARAM sw_param;
817         SW_STATUS sw_status;
818         SW_LARGENUMBER arg[2], res;
819         unsigned long sig_result;
820         BN_CTX *ctx;
821         BIGNUM *dsa_p = NULL;
822         BIGNUM *dsa_q = NULL;
823         BIGNUM *dsa_g = NULL;
824         BIGNUM *dsa_key = NULL;
825         BIGNUM *argument = NULL;
826         int to_return = -1;
827         int acquired = 0;
828
829         if((ctx = BN_CTX_new()) == NULL)
830                 goto err;
831         if(!get_context(&hac))
832                 {
833                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_UNIT_FAILURE);
834                 goto err;
835                 }
836         acquired = 1;
837         /* Prepare the params */
838         BN_CTX_start(ctx);
839         dsa_p = BN_CTX_get(ctx);
840         dsa_q = BN_CTX_get(ctx);
841         dsa_g = BN_CTX_get(ctx);
842         dsa_key = BN_CTX_get(ctx);
843         argument = BN_CTX_get(ctx);
844         if(!argument)
845                 {
846                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BN_CTX_FULL);
847                 goto err;
848                 }
849         if(!bn_wexpand(dsa_p, dsa->p->top) ||
850                         !bn_wexpand(dsa_q, dsa->q->top) ||
851                         !bn_wexpand(dsa_g, dsa->g->top) ||
852                         !bn_wexpand(dsa_key, dsa->pub_key->top) ||
853                         !bn_wexpand(argument, 40))
854                 {
855                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BN_EXPAND_FAIL);
856                 goto err;
857                 }
858         sw_param.type = SW_ALG_DSA;
859         sw_param.up.dsa.p.nbytes = BN_bn2bin(dsa->p,
860                                 (unsigned char *)dsa_p->d);
861         sw_param.up.dsa.p.value = (unsigned char *)dsa_p->d;
862         sw_param.up.dsa.q.nbytes = BN_bn2bin(dsa->q,
863                                 (unsigned char *)dsa_q->d);
864         sw_param.up.dsa.q.value = (unsigned char *)dsa_q->d;
865         sw_param.up.dsa.g.nbytes = BN_bn2bin(dsa->g,
866                                 (unsigned char *)dsa_g->d);
867         sw_param.up.dsa.g.value = (unsigned char *)dsa_g->d;
868         sw_param.up.dsa.key.nbytes = BN_bn2bin(dsa->pub_key,
869                                 (unsigned char *)dsa_key->d);
870         sw_param.up.dsa.key.value = (unsigned char *)dsa_key->d;
871         /* Attach the key params */
872         sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
873         switch(sw_status)
874                 {
875         case SW_OK:
876                 break;
877         case SW_ERR_INPUT_SIZE:
878                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BAD_KEY_SIZE);
879                 goto err;
880         default:
881                 {
882                 char tmpbuf[20];
883                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_REQUEST_FAILED);
884                 sprintf(tmpbuf, "%ld", sw_status);
885                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
886                 }
887                 goto err;
888                 }
889         /* Prepare the argument and response */
890         arg[0].nbytes = dgst_len;
891         arg[0].value = (unsigned char *)dgst;
892         arg[1].nbytes = 40;
893         arg[1].value = (unsigned char *)argument->d;
894         memset(arg[1].value, 0, 40);
895         BN_bn2bin(sig->r, arg[1].value + 20 - BN_num_bytes(sig->r));
896         BN_bn2bin(sig->s, arg[1].value + 40 - BN_num_bytes(sig->s));
897         res.nbytes = 4; /* unsigned long */
898         res.value = (unsigned char *)(&sig_result);
899         /* Perform the operation */
900         sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_DSS_VERIFY, arg, 2,
901                 &res, 1);
902         if(sw_status != SW_OK)
903                 {
904                 char tmpbuf[20];
905                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_REQUEST_FAILED);
906                 sprintf(tmpbuf, "%ld", sw_status);
907                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
908                 goto err;
909                 }
910         /* Convert the response */
911         to_return = ((sig_result == 0) ? 0 : 1);
912
913 err:
914         if(acquired)
915                 release_context(hac);
916         if(ctx)
917                 {
918                 BN_CTX_end(ctx);
919                 BN_CTX_free(ctx);
920                 }
921         return to_return;
922         }
923 #endif
924
925 #ifndef OPENSSL_NO_DH
926 /* This function is aliased to mod_exp (with the dh and mont dropped). */
927 static int cswift_mod_exp_dh(const DH *dh, BIGNUM *r,
928                 const BIGNUM *a, const BIGNUM *p,
929                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
930         {
931         return cswift_mod_exp(r, a, p, m, ctx);
932         }
933 #endif
934
935 /* This stuff is needed if this ENGINE is being compiled into a self-contained
936  * shared-library. */
937 #ifdef ENGINE_DYNAMIC_SUPPORT
938 static int bind_fn(ENGINE *e, const char *id)
939         {
940         if(id && (strcmp(id, engine_cswift_id) != 0))
941                 return 0;
942         if(!bind_helper(e))
943                 return 0;
944         return 1;
945         }       
946 IMPLEMENT_DYNAMIC_CHECK_FN()
947 IMPLEMENT_DYNAMIC_BIND_FN(bind_fn)
948 #endif /* ENGINE_DYNAMIC_SUPPORT */
949
950 #endif /* !OPENSSL_NO_HW_CSWIFT */
951 #endif /* !OPENSSL_NO_HW */